oxlint-tailwindcss 0.7.1 → 1.0.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
@@ -40,8 +40,7 @@ const DEFAULT_EXTRACTOR_CONFIG = {
40
40
  /^styles?$/
41
41
  ]
42
42
  };
43
- let _cachedConfig = null;
44
- let _settingsResolved = false;
43
+ const configCache = /* @__PURE__ */ new WeakMap();
45
44
  function mergeUnique(defaults, extras, exclusions) {
46
45
  let base = defaults;
47
46
  if (exclusions && exclusions.length > 0) {
@@ -54,34 +53,39 @@ function mergeUnique(defaults, extras, exclusions) {
54
53
  return [...set];
55
54
  }
56
55
  /**
57
- * Returns the extractor config, merging defaults with user settings from
58
- * `settings.tailwindcss`. Caches after the first successful settings read.
59
- * Falls back to DEFAULT_EXTRACTOR_CONFIG if settings are unavailable.
56
+ * Returns the extractor config for this rule context, merging defaults with
57
+ * user settings from `settings.tailwindcss`. The result is cached per
58
+ * context (WeakMap-keyed) so settings are read once per rule lifetime.
59
+ *
60
+ * In `createOnce` the settings getter throws — we fall back to the defaults
61
+ * without caching so the next visitor call (where settings ARE available)
62
+ * still resolves the user's overrides.
60
63
  */
61
64
  function getExtractorConfig(context) {
62
- if (_settingsResolved) return _cachedConfig;
65
+ const cached = configCache.get(context);
66
+ if (cached) return cached;
63
67
  let tw;
64
68
  try {
65
69
  const raw = context.settings?.tailwindcss;
66
70
  if (raw && typeof raw === "object") tw = raw;
67
- _settingsResolved = true;
68
71
  } catch {
69
72
  return DEFAULT_EXTRACTOR_CONFIG;
70
73
  }
71
74
  if (!tw) {
72
- _cachedConfig = DEFAULT_EXTRACTOR_CONFIG;
73
- return _cachedConfig;
75
+ configCache.set(context, DEFAULT_EXTRACTOR_CONFIG);
76
+ return DEFAULT_EXTRACTOR_CONFIG;
74
77
  }
75
78
  const exclude = tw.exclude;
76
79
  const excludedPatternSources = new Set(exclude?.variablePatterns ?? []);
77
80
  const filteredPatterns = excludedPatternSources.size > 0 ? DEFAULT_EXTRACTOR_CONFIG.variablePatterns.filter((re) => !excludedPatternSources.has(re.source)) : DEFAULT_EXTRACTOR_CONFIG.variablePatterns;
78
- _cachedConfig = {
81
+ const resolved = {
79
82
  attributes: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.attributes, tw.attributes, exclude?.attributes),
80
83
  callees: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.callees, tw.callees, exclude?.callees),
81
84
  tags: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.tags, tw.tags, exclude?.tags),
82
85
  variablePatterns: [...filteredPatterns, ...(tw.variablePatterns ?? []).map((p) => new RegExp(p))]
83
86
  };
84
- return _cachedConfig;
87
+ configCache.set(context, resolved);
88
+ return resolved;
85
89
  }
86
90
  /**
87
91
  * Creates the 4 standard AST visitor callbacks that all rules use.
@@ -134,7 +138,7 @@ function extractFromCallExpression(node, config = DEFAULT_EXTRACTOR_CONFIG) {
134
138
  if (calleeName === "tv") return extractFromTvCall(node);
135
139
  if (calleeName === "classed") return extractFromClassedCall(node);
136
140
  const results = [];
137
- for (const arg of node.arguments) results.push(...extractFromExpression(arg));
141
+ for (const arg of node.arguments) extractFromExpression(arg, results);
138
142
  return results;
139
143
  }
140
144
  /**
@@ -152,7 +156,7 @@ function extractFromTaggedTemplate(node, config = DEFAULT_EXTRACTOR_CONFIG) {
152
156
  */
153
157
  function extractObjectValues(node) {
154
158
  const results = [];
155
- for (const prop of node.properties) if (prop.type === "Property") results.push(...extractFromExpression(prop.value));
159
+ for (const prop of node.properties) if (prop.type === "Property") extractFromExpression(prop.value, results);
156
160
  return results;
157
161
  }
158
162
  /**
@@ -179,7 +183,7 @@ function extractFromClassedCall(node) {
179
183
  }
180
184
  skippedFirst = true;
181
185
  if (arg.type === "ObjectExpression") results.push(...extractFromCvaConfig(arg));
182
- else results.push(...extractFromExpression(arg));
186
+ else extractFromExpression(arg, results);
183
187
  }
184
188
  return results;
185
189
  }
@@ -190,7 +194,7 @@ function extractFromClassedCall(node) {
190
194
  function extractFromCvaCall(node) {
191
195
  const results = [];
192
196
  for (const arg of node.arguments) if (arg.type === "ObjectExpression") results.push(...extractFromCvaConfig(arg));
193
- else results.push(...extractFromExpression(arg));
197
+ else extractFromExpression(arg, results);
194
198
  return results;
195
199
  }
196
200
  /**
@@ -205,10 +209,10 @@ function extractFromCvaConfig(node) {
205
209
  const name = getPropertyName(prop.key);
206
210
  if (name === "variants" && prop.value.type === "ObjectExpression") for (const category of prop.value.properties) {
207
211
  if (category.type !== "Property" || category.value.type !== "ObjectExpression") continue;
208
- for (const variant of category.value.properties) if (variant.type === "Property") results.push(...extractFromExpression(variant.value));
212
+ for (const variant of category.value.properties) if (variant.type === "Property") extractFromExpression(variant.value, results);
209
213
  }
210
214
  else if (name === "compoundVariants" && prop.value.type === "ArrayExpression") results.push(...extractClassFromCompoundEntries(prop.value));
211
- else if (name === "defaultVariants") {} else results.push(...extractFromExpression(prop.value));
215
+ else if (name === "defaultVariants") {} else extractFromExpression(prop.value, results);
212
216
  }
213
217
  return results;
214
218
  }
@@ -219,7 +223,7 @@ function extractFromCvaConfig(node) {
219
223
  function extractFromTvCall(node) {
220
224
  const results = [];
221
225
  for (const arg of node.arguments) if (arg.type === "ObjectExpression") results.push(...extractFromTvConfig(arg));
222
- else results.push(...extractFromExpression(arg));
226
+ else extractFromExpression(arg, results);
223
227
  return results;
224
228
  }
225
229
  /**
@@ -232,20 +236,20 @@ function extractFromTvConfig(node) {
232
236
  for (const prop of node.properties) {
233
237
  if (prop.type !== "Property") continue;
234
238
  const name = getPropertyName(prop.key);
235
- if (name === "base") results.push(...extractFromExpression(prop.value));
239
+ if (name === "base") extractFromExpression(prop.value, results);
236
240
  else if (name === "slots" && prop.value.type === "ObjectExpression") {
237
- for (const slot of prop.value.properties) if (slot.type === "Property") results.push(...extractFromExpression(slot.value));
241
+ for (const slot of prop.value.properties) if (slot.type === "Property") extractFromExpression(slot.value, results);
238
242
  } else if (name === "variants" && prop.value.type === "ObjectExpression") for (const category of prop.value.properties) {
239
243
  if (category.type !== "Property" || category.value.type !== "ObjectExpression") continue;
240
244
  for (const variant of category.value.properties) {
241
245
  if (variant.type !== "Property") continue;
242
246
  if (variant.value.type === "ObjectExpression") {
243
- for (const slotProp of variant.value.properties) if (slotProp.type === "Property") results.push(...extractFromExpression(slotProp.value));
244
- } else results.push(...extractFromExpression(variant.value));
247
+ for (const slotProp of variant.value.properties) if (slotProp.type === "Property") extractFromExpression(slotProp.value, results);
248
+ } else extractFromExpression(variant.value, results);
245
249
  }
246
250
  }
247
251
  else if ((name === "compoundVariants" || name === "compoundSlots") && prop.value.type === "ArrayExpression") results.push(...extractClassFromCompoundEntries(prop.value));
248
- else if (name === "defaultVariants") {} else results.push(...extractFromExpression(prop.value));
252
+ else if (name === "defaultVariants") {} else extractFromExpression(prop.value, results);
249
253
  }
250
254
  return results;
251
255
  }
@@ -260,7 +264,7 @@ function extractClassFromCompoundEntries(node) {
260
264
  for (const prop of element.properties) {
261
265
  if (prop.type !== "Property") continue;
262
266
  const name = getPropertyName(prop.key);
263
- if (name === "class" || name === "className") results.push(...extractFromExpression(prop.value));
267
+ if (name === "class" || name === "className") extractFromExpression(prop.value, results);
264
268
  }
265
269
  }
266
270
  return results;
@@ -282,34 +286,51 @@ function extractFromVariableDeclarator(node, config = DEFAULT_EXTRACTOR_CONFIG)
282
286
  if (!node.init) return [];
283
287
  return extractFromExpression(node.init);
284
288
  }
285
- function extractFromExpression(node) {
286
- if (node.type === "Literal" && typeof node.value === "string") return [{
287
- value: node.value,
288
- node,
289
- range: [node.range[0] + 1, node.range[1] - 1]
290
- }];
291
- if (node.type === "TemplateLiteral") return extractFromTemplateLiteral(node);
292
- if (node.type === "ConditionalExpression") return [...extractFromExpression(node.consequent), ...extractFromExpression(node.alternate)];
293
- if (node.type === "LogicalExpression") return extractFromExpression(node.right);
289
+ /**
290
+ * Walk an expression and append every class-bearing location to `out`.
291
+ *
292
+ * Internal helpers pass their accumulator down to avoid the
293
+ * `extractFromExpression(x, results)` pattern, which allocates an
294
+ * intermediate array per recursive call. Public callers may omit `out` to
295
+ * receive a fresh array.
296
+ */
297
+ function extractFromExpression(node, out = []) {
298
+ if (node.type === "Literal" && typeof node.value === "string") {
299
+ out.push({
300
+ value: node.value,
301
+ node,
302
+ range: [node.range[0] + 1, node.range[1] - 1]
303
+ });
304
+ return out;
305
+ }
306
+ if (node.type === "TemplateLiteral") return appendFromTemplateLiteral(node, out);
307
+ if (node.type === "ConditionalExpression") {
308
+ extractFromExpression(node.consequent, out);
309
+ extractFromExpression(node.alternate, out);
310
+ return out;
311
+ }
312
+ if (node.type === "LogicalExpression") return extractFromExpression(node.right, out);
313
+ if (node.type === "ArrayExpression") {
314
+ for (const element of node.elements) if (element && element.type !== "SpreadElement") extractFromExpression(element, out);
315
+ return out;
316
+ }
294
317
  if (node.type === "ObjectExpression") {
295
- const results = [];
296
- for (const prop of node.properties) if (prop.type === "Property" && prop.key.type === "Literal" && typeof prop.key.value === "string") results.push({
318
+ for (const prop of node.properties) if (prop.type === "Property" && prop.key.type === "Literal" && typeof prop.key.value === "string") out.push({
297
319
  value: prop.key.value,
298
320
  node: prop.key,
299
321
  range: [prop.key.range[0] + 1, prop.key.range[1] - 1]
300
322
  });
301
- return results;
323
+ return out;
302
324
  }
303
- return [];
325
+ return out;
304
326
  }
305
- function extractFromTemplateLiteral(node) {
306
- const results = [];
327
+ function appendFromTemplateLiteral(node, out) {
307
328
  for (let i = 0; i < node.quasis.length; i++) {
308
329
  const quasi = node.quasis[i];
309
330
  const value = quasi.value.raw;
310
331
  if (value.trim().length > 0) {
311
332
  const start = quasi.range[0] + 1;
312
- results.push({
333
+ out.push({
313
334
  value,
314
335
  node: quasi,
315
336
  range: [start, start + value.length],
@@ -318,7 +339,10 @@ function extractFromTemplateLiteral(node) {
318
339
  });
319
340
  }
320
341
  }
321
- return results;
342
+ return out;
343
+ }
344
+ function extractFromTemplateLiteral(node) {
345
+ return appendFromTemplateLiteral(node, []);
322
346
  }
323
347
  function getCalleeName(node) {
324
348
  if (node.type === "Identifier") return node.name;
@@ -532,21 +556,6 @@ function findBestSuggestion(input, candidates, maxDistance = 3) {
532
556
  return best;
533
557
  }
534
558
  //#endregion
535
- //#region src/utils/floating-point.ts
536
- /**
537
- * Rounds rem/em/px values in class strings to avoid
538
- * JavaScript floating point issues.
539
- *
540
- * Example: "text-lg/[2.4000000000000004rem]" -> "text-lg/[2.4rem]"
541
- *
542
- * Regression test for: better-tailwindcss#320
543
- */
544
- function roundRemValue(className) {
545
- return className.replace(/\[(-?\d+\.\d{7,})(rem|em|px|%)\]/g, (_, num, unit) => {
546
- return `[${Number.parseFloat(Number.parseFloat(num).toFixed(6))}${unit}]`;
547
- });
548
- }
549
- //#endregion
550
559
  //#region src/utils/class-parser.ts
551
560
  /**
552
561
  * Extracts variants from a class string, respecting bracket depth.
@@ -653,23 +662,53 @@ function getArbitraryValue(cls) {
653
662
  }
654
663
  return null;
655
664
  }
656
- //#endregion
657
- //#region src/design-system/cache.ts
658
- /** Strip `!` modifier from start or end: `!flex` → `flex`, `flex!` → `flex` */
659
- function stripImportant(cls) {
660
- if (cls.startsWith("!")) return {
661
- bare: cls.slice(1),
662
- important: true
665
+ /**
666
+ * Strip the `!` important modifier from a utility's bare form (no variant
667
+ * prefix). Returns the bare string and the original position. Operate on
668
+ * the utility part — call `splitUtilityAndVariant` first if you have the
669
+ * full class. `parseClass` does both in one pass; use that when you need
670
+ * the full ParsedClass shape.
671
+ */
672
+ function splitImportant(utility) {
673
+ if (utility.startsWith("!")) return {
674
+ bare: utility.slice(1),
675
+ position: "prefix"
663
676
  };
664
- if (cls.endsWith("!")) return {
665
- bare: cls.slice(0, -1),
666
- important: true
677
+ if (utility.endsWith("!")) return {
678
+ bare: utility.slice(0, -1),
679
+ position: "suffix"
667
680
  };
668
681
  return {
669
- bare: cls,
670
- important: false
682
+ bare: utility,
683
+ position: null
671
684
  };
672
685
  }
686
+ /**
687
+ * Reattach `!` at the position recorded by `splitImportant`.
688
+ * The inverse of `splitImportant`: `reattachImportant(splitImportant(x).bare, splitImportant(x).position) === x`.
689
+ */
690
+ function reattachImportant(bare, position) {
691
+ if (position === "prefix") return `!${bare}`;
692
+ if (position === "suffix") return `${bare}!`;
693
+ return bare;
694
+ }
695
+ //#endregion
696
+ //#region src/utils/floating-point.ts
697
+ /**
698
+ * Rounds rem/em/px values in class strings to avoid
699
+ * JavaScript floating point issues.
700
+ *
701
+ * Example: "text-lg/[2.4000000000000004rem]" -> "text-lg/[2.4rem]"
702
+ *
703
+ * Regression test for: better-tailwindcss#320
704
+ */
705
+ function roundRemValue(className) {
706
+ return className.replace(/\[(-?\d+\.\d{7,})(rem|em|px|%)\]/g, (_, num, unit) => {
707
+ return `[${Number.parseFloat(Number.parseFloat(num).toFixed(6))}${unit}]`;
708
+ });
709
+ }
710
+ //#endregion
711
+ //#region src/design-system/cache.ts
673
712
  var DesignSystemCache = class DesignSystemCache {
674
713
  canonicalMap = /* @__PURE__ */ new Map();
675
714
  validitySet = /* @__PURE__ */ new Set();
@@ -710,12 +749,12 @@ var DesignSystemCache = class DesignSystemCache {
710
749
  const canonicalUtility = this.canonicalMap.get(utility);
711
750
  if (canonicalUtility !== void 0) return className.slice(0, className.length - utility.length) + canonicalUtility;
712
751
  }
713
- const { bare, important } = stripImportant(utility);
714
- if (important) {
752
+ const { bare, position } = splitImportant(utility);
753
+ if (position) {
715
754
  const canonicalBare = this.canonicalMap.get(bare);
716
755
  if (canonicalBare !== void 0) {
717
756
  const variantPrefix = className.slice(0, className.length - utility.length);
718
- return utility.startsWith("!") ? variantPrefix + "!" + canonicalBare : variantPrefix + canonicalBare + "!";
757
+ return position === "prefix" ? variantPrefix + "!" + canonicalBare : variantPrefix + canonicalBare + "!";
719
758
  }
720
759
  }
721
760
  return className;
@@ -745,6 +784,20 @@ var DesignSystemCache = class DesignSystemCache {
745
784
  if (variant.startsWith("aria-")) return (this.variantOrderMap.get("inert") ?? 48) + 2;
746
785
  return 0;
747
786
  }
787
+ _prefixOrderMap = null;
788
+ buildPrefixOrderMap() {
789
+ const index = /* @__PURE__ */ new Map();
790
+ for (const [cls, order] of this.orderMap) {
791
+ if (order === null) continue;
792
+ for (let i = cls.indexOf("-"); i >= 0; i = cls.indexOf("-", i + 1)) {
793
+ const p = cls.slice(0, i);
794
+ if (!index.has(p)) index.set(p, order);
795
+ const pd = p + "-";
796
+ if (!index.has(pd)) index.set(pd, order);
797
+ }
798
+ }
799
+ return index;
800
+ }
748
801
  /** Find the order of the first class matching a prefix (e.g. "max-w-" → order of "max-w-0") */
749
802
  findOrderByPrefix(prefix) {
750
803
  const withoutDash = prefix.endsWith("-") ? prefix.slice(0, -1) : null;
@@ -752,7 +805,8 @@ var DesignSystemCache = class DesignSystemCache {
752
805
  const order = this.orderMap.get(withoutDash);
753
806
  if (order != null) return order;
754
807
  }
755
- for (const [cls, order] of this.orderMap) if (cls.startsWith(prefix) && order != null) return order;
808
+ if (!this._prefixOrderMap) this._prefixOrderMap = this.buildPrefixOrderMap();
809
+ return this._prefixOrderMap.get(prefix);
756
810
  }
757
811
  getKnownPrefixes() {
758
812
  if (!this._knownPrefixes) {
@@ -768,7 +822,7 @@ var DesignSystemCache = class DesignSystemCache {
768
822
  if (this.validitySet.has(className)) return true;
769
823
  const utility = extractUtility(className);
770
824
  if (utility !== className && this.validitySet.has(utility)) return true;
771
- const { bare } = stripImportant(utility);
825
+ const { bare } = splitImportant(utility);
772
826
  if (bare !== utility && this.validitySet.has(bare)) return true;
773
827
  const slashIdx = bare.lastIndexOf("/");
774
828
  if (slashIdx > 0) {
@@ -792,8 +846,8 @@ var DesignSystemCache = class DesignSystemCache {
792
846
  const hasVariant = utility !== className;
793
847
  let baseOrder = this.orderMap.get(utility) ?? void 0;
794
848
  if (baseOrder === void 0) {
795
- const { bare, important } = stripImportant(utility);
796
- if (important) baseOrder = this.orderMap.get(bare) ?? void 0;
849
+ const { bare, position } = splitImportant(utility);
850
+ if (position) baseOrder = this.orderMap.get(bare) ?? void 0;
797
851
  }
798
852
  if (baseOrder === void 0) {
799
853
  const slashIdx = utility.lastIndexOf("/");
@@ -801,13 +855,13 @@ var DesignSystemCache = class DesignSystemCache {
801
855
  const base = utility.slice(0, slashIdx);
802
856
  baseOrder = this.orderMap.get(base) ?? void 0;
803
857
  if (baseOrder === void 0) {
804
- const { bare, important } = stripImportant(base);
805
- if (important) baseOrder = this.orderMap.get(bare) ?? void 0;
858
+ const { bare, position } = splitImportant(base);
859
+ if (position) baseOrder = this.orderMap.get(bare) ?? void 0;
806
860
  }
807
861
  }
808
862
  }
809
863
  if (baseOrder === void 0) {
810
- const stripped = stripImportant(utility).bare;
864
+ const stripped = splitImportant(utility).bare;
811
865
  const bracketIdx = stripped.indexOf("[");
812
866
  if (bracketIdx > 0) {
813
867
  const prefix = stripped.slice(0, bracketIdx);
@@ -815,7 +869,7 @@ var DesignSystemCache = class DesignSystemCache {
815
869
  }
816
870
  }
817
871
  if (baseOrder === void 0) {
818
- const stripped = stripImportant(utility).bare;
872
+ const stripped = splitImportant(utility).bare;
819
873
  const parenIdx = stripped.indexOf("(");
820
874
  if (parenIdx > 0) {
821
875
  const prefix = stripped.slice(0, parenIdx);
@@ -823,7 +877,7 @@ var DesignSystemCache = class DesignSystemCache {
823
877
  }
824
878
  }
825
879
  if (baseOrder === void 0) {
826
- const stripped = stripImportant(utility).bare;
880
+ const stripped = splitImportant(utility).bare;
827
881
  const numericMatch = /^(.+)-(\d+\.?\d*)$/.exec(stripped);
828
882
  if (numericMatch && this.getKnownPrefixes().has(numericMatch[1])) baseOrder = this.findOrderByPrefix(numericMatch[1] + "-");
829
883
  }
@@ -842,8 +896,8 @@ var DesignSystemCache = class DesignSystemCache {
842
896
  getCssProperties(className) {
843
897
  const result = this.cssPropsMap.get(className);
844
898
  if (result) return result;
845
- const { bare, important } = stripImportant(className);
846
- if (important) return this.cssPropsMap.get(bare) ?? [];
899
+ const { bare, position } = splitImportant(className);
900
+ if (position) return this.cssPropsMap.get(bare) ?? [];
847
901
  return [];
848
902
  }
849
903
  getVariantPriority(variant) {
@@ -855,12 +909,139 @@ var DesignSystemCache = class DesignSystemCache {
855
909
  getNamedEquivalent(className) {
856
910
  const result = this.arbitraryEquivMap.get(className);
857
911
  if (result) return result;
858
- const { bare, important } = stripImportant(className);
859
- if (important) return this.arbitraryEquivMap.get(bare) ?? null;
912
+ const { bare, position } = splitImportant(className);
913
+ if (position) return this.arbitraryEquivMap.get(bare) ?? null;
860
914
  return null;
861
915
  }
862
916
  };
863
917
  //#endregion
918
+ //#region src/utils/fatal.ts
919
+ /**
920
+ * Fatal error types and reporter for the deterministic v1 design.
921
+ *
922
+ * The plugin used to silently skip when the design system could not be
923
+ * loaded or the worker thread misbehaved. v1 fails loud: every DS-dependent
924
+ * rule catches these errors and surfaces them as a single fatal lint
925
+ * diagnostic so the user sees exactly what to fix.
926
+ */
927
+ /**
928
+ * The single `messageId` every DS-dependent rule uses to surface a fatal
929
+ * design-system load failure. Exported as a constant so the rule's
930
+ * `meta.messages` and `context.report()` calls in `reportFatalDsError`
931
+ * cannot drift apart silently.
932
+ */
933
+ const DS_UNAVAILABLE_MESSAGE_ID = "designSystemUnavailable";
934
+ /** Pre-shaped entry for `meta.messages`. Spread it: `messages: { ..., ...DS_UNAVAILABLE_MESSAGE }`. */
935
+ const DS_UNAVAILABLE_MESSAGE = { [DS_UNAVAILABLE_MESSAGE_ID]: "{{message}}" };
936
+ var OxlintTailwindError = class extends Error {
937
+ /** A short, actionable hint shown alongside the error message. */
938
+ hint;
939
+ constructor(message, hint, options) {
940
+ super(message, options);
941
+ this.name = this.constructor.name;
942
+ this.hint = hint;
943
+ }
944
+ };
945
+ /** No `settings.tailwindcss.entryPoint` was provided and a DS-dependent rule needs one. */
946
+ var MissingEntryPointError = class extends OxlintTailwindError {};
947
+ /** `settings.tailwindcss.entryPoint` is an array of strings — removed in v1. */
948
+ var DeprecatedEntryPointShapeError = class extends OxlintTailwindError {};
949
+ /** `__unstable__loadDesignSystem` failed (bad CSS path, malformed CSS, install issue). */
950
+ var DesignSystemLoadError = class extends OxlintTailwindError {};
951
+ /** The sort or canonicalize worker thread failed to initialize or timed out. */
952
+ var SortServiceError = class extends OxlintTailwindError {};
953
+ /** Type-guard: did this error originate from the plugin's fail-loud infrastructure? */
954
+ function isFatalError(err) {
955
+ return err instanceof OxlintTailwindError;
956
+ }
957
+ /**
958
+ * Format a fatal error into the diagnostic message a rule should report.
959
+ *
960
+ * Pulls in the optional `hint` (a one-line "here's how to fix it" follow-up)
961
+ * so the message is self-contained even when the user is reading it in an
962
+ * editor without the docs site open.
963
+ */
964
+ function formatFatalError(err) {
965
+ return err.hint ? `${err.message}\n\nHint: ${err.hint}` : err.message;
966
+ }
967
+ /**
968
+ * Helper for DS-dependent rules to convert a caught fatal error into a
969
+ * single diagnostic. Returns `true` if the error was reported (and the
970
+ * visitor should bail out), `false` otherwise — the rule layer rethrows
971
+ * non-fatal errors to surface real bugs.
972
+ */
973
+ function reportFatalDsError(context, err, node) {
974
+ if (!isFatalError(err)) return false;
975
+ context.report({
976
+ node,
977
+ messageId: DS_UNAVAILABLE_MESSAGE_ID,
978
+ data: { message: formatFatalError(err) }
979
+ });
980
+ return true;
981
+ }
982
+ /**
983
+ * Call `getDS()` and route fatal errors through `reportFatalDsError`.
984
+ *
985
+ * Returns the load result on success, or `null` after a fatal error has been
986
+ * reported (rules should `if (!ds) return` and exit the visitor). Non-fatal
987
+ * errors are re-thrown so genuine bugs aren't hidden.
988
+ */
989
+ function safeGetDS(getDS, context, node) {
990
+ try {
991
+ return getDS();
992
+ } catch (err) {
993
+ if (reportFatalDsError(context, err, node)) return null;
994
+ throw err;
995
+ }
996
+ }
997
+ //#endregion
998
+ //#region src/design-system/tailwind-node.ts
999
+ /**
1000
+ * Single source of truth for the resolved `@tailwindcss/node` entry path
1001
+ * and its installed version. Three call sites (sync-loader, sort-service,
1002
+ * canonicalize-service) used to each call `require.resolve` independently
1003
+ * — this module resolves once at load and exposes the results.
1004
+ *
1005
+ * The version is read from `dist/../package.json` (the published layout)
1006
+ * with a walk-up fallback for unconventional installs.
1007
+ */
1008
+ function resolveTailwindNodePath() {
1009
+ try {
1010
+ return require.resolve("@tailwindcss/node");
1011
+ } catch {
1012
+ return null;
1013
+ }
1014
+ }
1015
+ function readVersionFromEntry(entryPath) {
1016
+ let dir = (0, node_path.dirname)(entryPath);
1017
+ for (let i = 0; i < 5; i++) {
1018
+ const pkgJson = (0, node_path.join)(dir, "package.json");
1019
+ if ((0, node_fs.existsSync)(pkgJson)) try {
1020
+ const pkg = JSON.parse((0, node_fs.readFileSync)(pkgJson, "utf-8"));
1021
+ if (pkg.name === "@tailwindcss/node" && pkg.version) return pkg.version;
1022
+ } catch {}
1023
+ const parent = (0, node_path.dirname)(dir);
1024
+ if (parent === dir) break;
1025
+ dir = parent;
1026
+ }
1027
+ return "unknown";
1028
+ }
1029
+ const entryPath = resolveTailwindNodePath();
1030
+ /**
1031
+ * Absolute path to `@tailwindcss/node`'s main entry, or `null` if not
1032
+ * installed. Workers receive this path via workerData; the parent does
1033
+ * the resolution because module resolution from a child process's `eval`
1034
+ * context (with cwd inside a tmp dir or under pnpm strict workspaces) can
1035
+ * fail to find the bare specifier.
1036
+ */
1037
+ const TAILWIND_NODE_PATH = entryPath;
1038
+ /**
1039
+ * Installed `@tailwindcss/node` version, or `'unknown'`. Used as part of
1040
+ * the disk-cache key in sync-loader so cached precompute output is
1041
+ * invalidated when the consumer upgrades.
1042
+ */
1043
+ const TAILWIND_NODE_VERSION = entryPath !== null ? readVersionFromEntry(entryPath) : "unknown";
1044
+ //#endregion
864
1045
  //#region src/design-system/sync-loader.ts
865
1046
  /**
866
1047
  * Synchronous design system loader using execFileSync.
@@ -1193,7 +1374,12 @@ async function main() {
1193
1374
  }
1194
1375
  }
1195
1376
 
1196
- // Arbitrary equivalents: map arbitrary forms to named equivalents
1377
+ // Arbitrary equivalents: map arbitrary forms to named equivalents.
1378
+ // Enumerate every dash split point so multi-segment utilities (e.g.
1379
+ // bg-card-foreground) emit candidates for every prefix; lastIndexOf
1380
+ // alone drops the shorter prefix and misses multi-segment mappings.
1381
+ // Start at indexOf('-', 1) so negative utilities (e.g. -translate-x-1)
1382
+ // keep their leading '-' in every prefix instead of producing '' + '-[…]'.
1197
1383
  const arbitraryEquivalents = {};
1198
1384
  const candidates = [];
1199
1385
  for (const cls of validClasses) {
@@ -1205,10 +1391,10 @@ async function main() {
1205
1391
  const pvMatch = cssText.match(/^\\s+([\\w-]+)\\s*:\\s*(.+?)\\s*;?\\s*$/m);
1206
1392
  if (!pvMatch) continue;
1207
1393
  const value = pvMatch[2].trim().replace(/;$/, '');
1208
- const lastDash = cls.lastIndexOf('-');
1209
- if (lastDash <= 0) continue;
1210
- const prefix = cls.slice(0, lastDash);
1211
- candidates.push({ arbitraryForm: prefix + '-[' + value + ']', namedCls: cls, namedCss: cssText });
1394
+ for (let dashPos = cls.indexOf('-', 1); dashPos > 0; dashPos = cls.indexOf('-', dashPos + 1)) {
1395
+ const prefix = cls.slice(0, dashPos);
1396
+ candidates.push({ arbitraryForm: prefix + '-[' + value + ']', namedCls: cls, namedCss: cssText });
1397
+ }
1212
1398
  }
1213
1399
  function extractDeclarations(css) {
1214
1400
  const openBrace = css.indexOf('{');
@@ -1232,62 +1418,73 @@ async function main() {
1232
1418
  main().catch(e => { process.stderr.write(e.message); process.exit(1); });
1233
1419
  `;
1234
1420
  const CACHE_DIR = (0, node_path.join)((0, node_os.tmpdir)(), "oxlint-tailwindcss");
1235
- const CACHE_VERSION = 13;
1236
1421
  /**
1237
- * Two-level disk cache for monorepo deduplication:
1238
- *
1239
- * Level 1 — mtime index (.idx): maps path+mtime → content hash (fast-path, avoids reading CSS)
1240
- * Level 2 — content cache (.json): maps content hash → precomputed data (shared across packages)
1241
- *
1242
- * In monorepos, multiple packages with identical CSS (e.g. `@import 'tailwindcss'`) at different
1243
- * paths share a single content cache entry, avoiding redundant child process spawns.
1422
+ * Cache key derived from:
1423
+ * - md5(PRECOMPUTE_SCRIPT): auto-invalidates when our precompute logic changes,
1424
+ * since the shape and content of the cached JSON is fully determined by what
1425
+ * this script prints to stdout.
1426
+ * - @tailwindcss/node version: auto-invalidates when the consumer upgrades
1427
+ * tailwindcss (e.g. 4.2 → 4.3 adding `zoom-*`, `tab-*`, `scrollbar-*` etc.),
1428
+ * so `validClasses`, `cssProps`, `canonical`, and `arbitraryEquivalents`
1429
+ * reflect the installed version. @tailwindcss/node and tailwindcss are
1430
+ * published together, so their versions match.
1244
1431
  */
1245
- function getMtimeIndexPath(cssPath, mtime) {
1246
- return (0, node_path.join)(CACHE_DIR, `${(0, node_crypto.createHash)("md5").update(`v${CACHE_VERSION}:${cssPath}:${mtime}`).digest("hex")}.idx`);
1432
+ function computeCacheKey(scriptContent, tailwindVersion) {
1433
+ return `${(0, node_crypto.createHash)("md5").update(scriptContent).digest("hex").slice(0, 8)}:${tailwindVersion}`;
1247
1434
  }
1435
+ const CACHE_KEY = computeCacheKey(PRECOMPUTE_SCRIPT, TAILWIND_NODE_VERSION);
1248
1436
  function computeContentHash(content) {
1249
- return (0, node_crypto.createHash)("md5").update(`v${CACHE_VERSION}:${content}`).digest("hex");
1437
+ return (0, node_crypto.createHash)("md5").update(`${CACHE_KEY}:${content}`).digest("hex");
1250
1438
  }
1251
1439
  function getContentCachePath(contentHash) {
1252
1440
  return (0, node_path.join)(CACHE_DIR, `${contentHash}.json`);
1253
1441
  }
1254
1442
  function tryReadCache(cachePath) {
1443
+ const raw = tryReadRawCache(cachePath);
1444
+ if (raw === null) return null;
1445
+ try {
1446
+ return JSON.parse(raw);
1447
+ } catch {
1448
+ return null;
1449
+ }
1450
+ }
1451
+ function tryReadRawCache(cachePath) {
1255
1452
  try {
1256
- return JSON.parse((0, node_fs.readFileSync)(cachePath, "utf-8"));
1453
+ return (0, node_fs.readFileSync)(cachePath, "utf-8");
1257
1454
  } catch {
1258
1455
  return null;
1259
1456
  }
1260
1457
  }
1261
- function writeCacheFiles(contentCachePath, mtimeIndexPath, contentHash, data) {
1458
+ function writeCacheFile(contentCachePath, data) {
1262
1459
  try {
1263
1460
  (0, node_fs.mkdirSync)(CACHE_DIR, { recursive: true });
1264
1461
  (0, node_fs.writeFileSync)(contentCachePath, data);
1265
- (0, node_fs.writeFileSync)(mtimeIndexPath, contentHash);
1266
1462
  } catch {}
1267
1463
  }
1268
- function loadDesignSystemSync(cssPath, timeout) {
1269
- const resolvedPath = (0, node_path.resolve)(cssPath);
1464
+ const LOCK_POLL_MS = 50;
1465
+ const SLEEP_BUFFER = new Int32Array(new SharedArrayBuffer(4));
1466
+ function syncSleep(ms) {
1467
+ Atomics.wait(SLEEP_BUFFER, 0, 0, ms);
1468
+ }
1469
+ /** Age of the lock file in ms, or Infinity if it has already vanished. */
1470
+ function lockAgeMs(lockPath) {
1270
1471
  try {
1271
- const mtime = (0, node_fs.statSync)(resolvedPath).mtimeMs;
1272
- const mtimeIndexPath = getMtimeIndexPath(resolvedPath, mtime);
1273
- if ((0, node_fs.existsSync)(mtimeIndexPath)) try {
1274
- const cached = tryReadCache(getContentCachePath((0, node_fs.readFileSync)(mtimeIndexPath, "utf-8").trim()));
1275
- if (cached) return cached;
1276
- } catch {}
1277
- const contentHash = computeContentHash((0, node_fs.readFileSync)(resolvedPath, "utf-8"));
1278
- const contentCachePath = getContentCachePath(contentHash);
1279
- const cached = tryReadCache(contentCachePath);
1280
- if (cached) {
1281
- try {
1282
- (0, node_fs.mkdirSync)(CACHE_DIR, { recursive: true });
1283
- (0, node_fs.writeFileSync)(mtimeIndexPath, contentHash);
1284
- } catch {}
1285
- return cached;
1286
- }
1287
- const tailwindNodePath = require.resolve("@tailwindcss/node");
1288
- const stdout = (0, node_child_process.execFileSync)(process.execPath, ["-e", PRECOMPUTE_SCRIPT], {
1472
+ return Date.now() - (0, node_fs.statSync)(lockPath).mtimeMs;
1473
+ } catch {
1474
+ return Number.POSITIVE_INFINITY;
1475
+ }
1476
+ }
1477
+ function tryUnlink(path) {
1478
+ try {
1479
+ (0, node_fs.unlinkSync)(path);
1480
+ } catch {}
1481
+ }
1482
+ /** Fork the precompute child once. Throws `DesignSystemLoadError` on failure. */
1483
+ function runPrecompute(resolvedPath, tailwindNodePath, timeout) {
1484
+ try {
1485
+ return (0, node_child_process.execFileSync)(process.execPath, ["-e", PRECOMPUTE_SCRIPT], {
1289
1486
  encoding: "utf-8",
1290
- timeout: timeout ?? 3e4,
1487
+ timeout,
1291
1488
  maxBuffer: 50 * 1024 * 1024,
1292
1489
  env: {
1293
1490
  ...process.env,
@@ -1296,108 +1493,75 @@ function loadDesignSystemSync(cssPath, timeout) {
1296
1493
  },
1297
1494
  cwd: (0, node_path.dirname)(resolvedPath)
1298
1495
  });
1299
- writeCacheFiles(contentCachePath, mtimeIndexPath, contentHash, stdout);
1300
- return JSON.parse(stdout);
1301
- } catch (error) {
1302
- const msg = error instanceof Error ? error.message : String(error);
1303
- if (msg.includes("Cannot find module '@tailwindcss/node'")) console.error(`[oxlint-tailwindcss] Could not resolve '@tailwindcss/node' for "${resolvedPath}". If you are using pnpm with strict hoisting, add '@tailwindcss/node' as a direct devDependency, or upgrade oxlint-tailwindcss to >= 0.7.0 which resolves it from the plugin's own install location. DS-dependent rules will be skipped for this file.`);
1304
- else console.error(`[oxlint-tailwindcss] Failed to load design system from "${resolvedPath}":`, msg);
1305
- return null;
1496
+ } catch (cause) {
1497
+ const causeError = cause instanceof Error ? cause : void 0;
1498
+ throw new DesignSystemLoadError(`Failed to precompute design system from "${resolvedPath}": ${causeError?.message ?? String(cause)}`, "Check the CSS file for syntax errors. If this looks like a timeout, raise `settings.tailwindcss.timeout`.", { cause: causeError });
1306
1499
  }
1307
1500
  }
1308
- //#endregion
1309
- //#region src/design-system/auto-detect.ts
1310
- const IMPORT_RE = /@import\s+['"]([^'"]+)['"]/g;
1311
1501
  /**
1312
- * Resolves a CSS @import specifier to an absolute path.
1313
- * Handles relative paths and package imports (walks up to node_modules).
1502
+ * Return the raw precompute JSON for `contentHash`, forking at most one child
1503
+ * across all isolates competing for the same hash. Whoever wins the lock
1504
+ * computes and writes the cache; the rest wait for that file.
1314
1505
  */
1315
- function resolveImport(specifier, baseDir) {
1316
- if (specifier.startsWith(".")) return (0, node_path.resolve)(baseDir, specifier);
1317
- let dir = baseDir;
1318
- while (true) {
1319
- const candidate = (0, node_path.join)(dir, "node_modules", specifier);
1320
- if ((0, node_fs.existsSync)(candidate)) return candidate;
1321
- const parent = (0, node_path.dirname)(dir);
1322
- if (parent === dir) break;
1323
- dir = parent;
1506
+ function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath, timeout) {
1507
+ const lockPath = (0, node_path.join)(CACHE_DIR, `${contentHash}.lock`);
1508
+ const staleMs = timeout + 3e4;
1509
+ try {
1510
+ (0, node_fs.mkdirSync)(CACHE_DIR, { recursive: true });
1511
+ } catch {
1512
+ return runPrecompute(resolvedPath, tailwindNodePath, timeout);
1324
1513
  }
1325
- return null;
1326
- }
1327
- /**
1328
- * Checks if any @import in the CSS content points to a file containing a Tailwind signal.
1329
- * Only follows ONE level of imports — no recursion.
1330
- */
1331
- function hasTailwindSignalInImports(content, baseDir, signals) {
1332
- IMPORT_RE.lastIndex = 0;
1333
- let match;
1334
- while ((match = IMPORT_RE.exec(content)) !== null) {
1335
- const specifier = match[1];
1336
- if (specifier === "tailwindcss") continue;
1337
- const resolved = resolveImport(specifier, baseDir);
1338
- if (!resolved) continue;
1514
+ const start = Date.now();
1515
+ for (;;) {
1516
+ const raw = tryReadRawCache(cachePath);
1517
+ if (raw !== null) return raw;
1518
+ let lockFd;
1339
1519
  try {
1340
- const imported = (0, node_fs.readFileSync)(resolved, "utf-8");
1341
- if (signals.some((signal) => imported.includes(signal))) return true;
1342
- } catch {
1343
- continue;
1520
+ lockFd = (0, node_fs.openSync)(lockPath, "wx");
1521
+ } catch (cause) {
1522
+ if (cause.code === "EEXIST") {
1523
+ if (lockAgeMs(lockPath) > staleMs || Date.now() - start > staleMs * 2) tryUnlink(lockPath);
1524
+ else syncSleep(LOCK_POLL_MS);
1525
+ continue;
1526
+ }
1527
+ return runPrecompute(resolvedPath, tailwindNodePath, timeout);
1528
+ }
1529
+ try {
1530
+ const stdout = runPrecompute(resolvedPath, tailwindNodePath, timeout);
1531
+ writeCacheFile(cachePath, stdout);
1532
+ return stdout;
1533
+ } finally {
1534
+ (0, node_fs.closeSync)(lockFd);
1535
+ tryUnlink(lockPath);
1344
1536
  }
1345
1537
  }
1346
- return false;
1347
1538
  }
1348
- const CANDIDATE_DIRS = [
1349
- "src",
1350
- ".",
1351
- "app",
1352
- "styles",
1353
- "style",
1354
- "css",
1355
- "assets",
1356
- "assets/css",
1357
- "resources/css"
1358
- ];
1359
- const CANDIDATE_NAMES = [
1360
- "app",
1361
- "globals",
1362
- "global",
1363
- "style",
1364
- "styles",
1365
- "index",
1366
- "main",
1367
- "tailwind",
1368
- "tailwindcss"
1369
- ];
1370
- const CANDIDATE_PATHS = CANDIDATE_DIRS.flatMap((dir) => CANDIDATE_NAMES.map((name) => dir === "." ? `${name}.css` : `${dir}/${name}.css`));
1371
- const TAILWIND_SIGNALS = [
1372
- "@import \"tailwindcss\"",
1373
- "@import 'tailwindcss'",
1374
- "@tailwind base",
1375
- "@import tailwindcss"
1376
- ];
1377
1539
  /**
1378
- * Searches for the Tailwind CSS entry point by walking UP from the file
1379
- * being linted. Monorepo-aware: stops at package.json boundaries.
1540
+ * Synchronously load and precompute the design system for a CSS file.
1541
+ *
1542
+ * Throws `DesignSystemLoadError` on any failure (missing file, child
1543
+ * process error, missing `@tailwindcss/node`, etc.). Callers catch via
1544
+ * `reportFatalDsError` to surface a single Program-level diagnostic.
1380
1545
  */
1381
- function autoDetectEntryPoint(filePath) {
1382
- let currentDir = filePath ? (0, node_path.dirname)((0, node_path.resolve)(filePath)) : process.cwd();
1383
- for (let depth = 0; depth < 20; depth++) {
1384
- for (const candidate of CANDIDATE_PATHS) {
1385
- const fullPath = (0, node_path.join)(currentDir, candidate);
1386
- if (!(0, node_fs.existsSync)(fullPath)) continue;
1387
- try {
1388
- const content = (0, node_fs.readFileSync)(fullPath, "utf-8");
1389
- if (TAILWIND_SIGNALS.some((signal) => content.includes(signal))) return fullPath;
1390
- if (hasTailwindSignalInImports(content, (0, node_path.dirname)(fullPath), TAILWIND_SIGNALS)) return fullPath;
1391
- } catch {
1392
- continue;
1393
- }
1394
- }
1395
- if ((0, node_fs.existsSync)((0, node_path.join)(currentDir, "package.json"))) break;
1396
- const parentDir = (0, node_path.dirname)(currentDir);
1397
- if (parentDir === currentDir) break;
1398
- currentDir = parentDir;
1546
+ function loadDesignSystemSync(cssPath, timeout) {
1547
+ const resolvedPath = (0, node_path.resolve)(cssPath);
1548
+ let content;
1549
+ try {
1550
+ content = (0, node_fs.readFileSync)(resolvedPath, "utf-8");
1551
+ } catch (cause) {
1552
+ throw new DesignSystemLoadError(`Could not read CSS entry point: ${resolvedPath}`, "Verify the path resolves from the oxlint working directory and the file is readable.", { cause: cause instanceof Error ? cause : void 0 });
1553
+ }
1554
+ const contentHash = computeContentHash(content);
1555
+ const contentCachePath = getContentCachePath(contentHash);
1556
+ const cached = tryReadCache(contentCachePath);
1557
+ if (cached) return cached;
1558
+ if (TAILWIND_NODE_PATH === null) throw new DesignSystemLoadError(`Could not resolve '@tailwindcss/node' while loading "${resolvedPath}".`, "Install '@tailwindcss/node' (or upgrade oxlint-tailwindcss) and re-run.");
1559
+ const stdout = computeWithLock(resolvedPath, TAILWIND_NODE_PATH, contentHash, contentCachePath, timeout ?? 6e4);
1560
+ try {
1561
+ return JSON.parse(stdout);
1562
+ } catch (cause) {
1563
+ throw new DesignSystemLoadError(`Precompute output for "${resolvedPath}" was not valid JSON.`, "This is likely a bug in oxlint-tailwindcss. Please open an issue with the CSS that triggered it.", { cause: cause instanceof Error ? cause : void 0 });
1399
1564
  }
1400
- return null;
1401
1565
  }
1402
1566
  //#endregion
1403
1567
  //#region src/design-system/debug.ts
@@ -1428,48 +1592,143 @@ function debugLog(message) {
1428
1592
  if (_enabled || process.env.DEBUG === "oxlint-tailwindcss") console.error(`${PREFIX} ${message}`);
1429
1593
  }
1430
1594
  //#endregion
1595
+ //#region src/utils/context.ts
1596
+ /**
1597
+ * Safely read `context.options[0]`. Returns `undefined` if the getter throws
1598
+ * (oxlint < 1.31.0) or if options aren't populated yet.
1599
+ */
1600
+ function safeOptions(context) {
1601
+ try {
1602
+ return context.options?.[0] ?? void 0;
1603
+ } catch {
1604
+ return;
1605
+ }
1606
+ }
1607
+ /**
1608
+ * Safely read `context.settings`. Same try/catch pattern as `safeOptions`
1609
+ * for the createOnce-throws case.
1610
+ */
1611
+ function safeSettings(context) {
1612
+ try {
1613
+ return context.settings ?? void 0;
1614
+ } catch {
1615
+ return;
1616
+ }
1617
+ }
1618
+ /** Safely read `context.filename`. Same try/catch pattern. */
1619
+ function safeFilename(context) {
1620
+ try {
1621
+ return context.filename ?? void 0;
1622
+ } catch {
1623
+ return;
1624
+ }
1625
+ }
1626
+ /**
1627
+ * Lazily memoize a compiled options object across visitor calls.
1628
+ *
1629
+ * Every rule with options reinvents:
1630
+ *
1631
+ * let _x: CompiledOptions | null = null
1632
+ * function getX() {
1633
+ * if (_x === null) _x = compile(safeOptions<RawOptions>(context))
1634
+ * return _x
1635
+ * }
1636
+ *
1637
+ * This wraps the pattern: pass the context and a `compile` function (which
1638
+ * receives the raw options object — possibly undefined) and get a memoized
1639
+ * thunk back. Inside `createOnce`, options aren't available yet, so the first
1640
+ * visitor call triggers compilation; every subsequent call is O(1).
1641
+ */
1642
+ function createLazyOptions(context, compile) {
1643
+ let cached = null;
1644
+ return () => {
1645
+ if (cached) return cached.value;
1646
+ cached = { value: compile(safeOptions(context)) };
1647
+ return cached.value;
1648
+ };
1649
+ }
1650
+ //#endregion
1431
1651
  //#region src/design-system/loader.ts
1432
1652
  const dsCache = /* @__PURE__ */ new Map();
1433
- const autoDetectCache = /* @__PURE__ */ new Map();
1434
- let lastLoadedPath = null;
1653
+ function isEntryPointMapping(v) {
1654
+ if (typeof v !== "object" || v === null) return false;
1655
+ const m = v;
1656
+ return (typeof m.files === "string" || Array.isArray(m.files) && m.files.every((s) => typeof s === "string")) && typeof m.use === "string";
1657
+ }
1435
1658
  /**
1436
- * Extracts `entryPoint` from `context.settings.tailwindcss`.
1437
- * Supports both `string` and `string[]` (for monorepos).
1659
+ * Read `settings.tailwindcss.entryPoint` and normalize it to the v1 shape.
1660
+ *
1661
+ * Throws `DeprecatedEntryPointShapeError` if the legacy `string[]` shape is
1662
+ * still in use (removed in v1; the user must migrate to `{ files, use }[]`).
1438
1663
  */
1439
1664
  function entryPointFromSettings(settings) {
1440
1665
  const tw = settings?.tailwindcss;
1441
- if (tw && typeof tw === "object" && "entryPoint" in tw) {
1442
- const ep = tw.entryPoint;
1443
- if (typeof ep === "string") return ep;
1444
- if (Array.isArray(ep) && ep.length > 0 && ep.every((e) => typeof e === "string")) return ep;
1666
+ if (!tw || typeof tw !== "object" || !("entryPoint" in tw)) return void 0;
1667
+ const ep = tw.entryPoint;
1668
+ if (typeof ep === "string") return ep;
1669
+ if (Array.isArray(ep)) {
1670
+ if (ep.length === 0) return void 0;
1671
+ if (ep.every((e) => typeof e === "string")) throw new DeprecatedEntryPointShapeError("`settings.tailwindcss.entryPoint: string[]` was removed in v1.0.0.", "Convert each entry into an object with explicit globs:\n entryPoint: [\n { files: \"packages/app/**\", use: \"packages/app/src/styles.css\" },\n ...\n ]\nSee https://oxlint-tailwindcss.pages.dev/migration/v0-to-v1");
1672
+ if (ep.every(isEntryPointMapping)) return ep;
1673
+ throw new MissingEntryPointError("`settings.tailwindcss.entryPoint` must be either a string or an array of `{ files, use }` objects.", "Each item needs `files` (glob or array of globs) and `use` (path to a CSS file).");
1445
1674
  }
1446
1675
  }
1447
1676
  /**
1448
- * Given an array of entry points and a file path, pick the one that shares
1449
- * the longest common directory prefix with the file. Falls back to first entry.
1677
+ * Compile a minimal glob pattern to a regular expression.
1678
+ *
1679
+ * Supported syntax: `**` (any depth), `*` (any chars except `/`), `?` (one
1680
+ * char except `/`), plus literal segments. Anchored on both ends.
1681
+ *
1682
+ * Memoized across calls because `resolveByGlobMapping` runs per lint visit;
1683
+ * recompiling the same pattern per AST node would be wasted work.
1450
1684
  */
1451
- function resolveClosestEntryPoint(entryPoints, filePath) {
1452
- if (entryPoints.length === 1 || !filePath) return entryPoints[0];
1453
- const fileDir = (0, node_path.dirname)((0, node_path.resolve)(filePath));
1454
- let best = entryPoints[0];
1455
- let bestLen = 0;
1456
- for (const ep of entryPoints) {
1457
- const len = commonPrefixLength(fileDir, (0, node_path.dirname)((0, node_path.resolve)(ep)));
1458
- if (len > bestLen) {
1459
- bestLen = len;
1460
- best = ep;
1461
- }
1462
- }
1463
- return best;
1464
- }
1465
- function commonPrefixLength(a, b) {
1466
- const len = Math.min(a.length, b.length);
1685
+ const globRegexCache = /* @__PURE__ */ new Map();
1686
+ function globToRegExp(glob) {
1687
+ const cached = globRegexCache.get(glob);
1688
+ if (cached) return cached;
1689
+ let re = "";
1467
1690
  let i = 0;
1468
- while (i < len && a[i] === b[i]) i++;
1469
- return i;
1691
+ while (i < glob.length) {
1692
+ const c = glob[i];
1693
+ if (c === "*" && glob[i + 1] === "*") {
1694
+ re += ".*";
1695
+ i += 2;
1696
+ if (glob[i] === "/") i++;
1697
+ } else if (c === "*") {
1698
+ re += "[^/]*";
1699
+ i++;
1700
+ } else if (c === "?") {
1701
+ re += "[^/]";
1702
+ i++;
1703
+ } else if ("+()|.\\$^{}[]".includes(c)) {
1704
+ re += "\\" + c;
1705
+ i++;
1706
+ } else {
1707
+ re += c;
1708
+ i++;
1709
+ }
1710
+ }
1711
+ const compiled = new RegExp("^" + re + "$");
1712
+ globRegexCache.set(glob, compiled);
1713
+ return compiled;
1714
+ }
1715
+ function matchesAnyGlob(filePath, globs) {
1716
+ return (typeof globs === "string" ? [globs] : globs).some((g) => globToRegExp(g).test(filePath));
1717
+ }
1718
+ /**
1719
+ * Resolve a file path to its entry-point CSS via a mapping array.
1720
+ * First-match-wins. Paths are matched relative to `baseDir` (typically the
1721
+ * process CWD where oxlint runs), with forward-slash normalization for
1722
+ * cross-platform consistency. Returns the absolute CSS path, or `null` if
1723
+ * no mapping matches.
1724
+ */
1725
+ function resolveByGlobMapping(mappings, filePath, baseDir) {
1726
+ const relPath = (0, node_path.relative)(baseDir, (0, node_path.resolve)(filePath)).split("\\").join("/");
1727
+ for (const m of mappings) if (matchesAnyGlob(relPath, m.files)) return (0, node_path.resolve)(baseDir, m.use);
1728
+ return null;
1470
1729
  }
1471
1730
  /**
1472
- * Extracts `rootFontSize` from `context.settings.tailwindcss` (default: 16).
1731
+ * Extract `rootFontSize` from `settings.tailwindcss` (default: 16).
1473
1732
  */
1474
1733
  function rootFontSizeFromSettings(settings) {
1475
1734
  const tw = settings?.tailwindcss;
@@ -1479,9 +1738,6 @@ function rootFontSizeFromSettings(settings) {
1479
1738
  }
1480
1739
  return 16;
1481
1740
  }
1482
- /**
1483
- * Extracts `timeout` from `context.settings.tailwindcss`.
1484
- */
1485
1741
  function timeoutFromSettings(settings) {
1486
1742
  const tw = settings?.tailwindcss;
1487
1743
  if (tw && typeof tw === "object" && "timeout" in tw) {
@@ -1490,147 +1746,157 @@ function timeoutFromSettings(settings) {
1490
1746
  }
1491
1747
  }
1492
1748
  /**
1493
- * Cached auto-detect: caches by directory since all files in the same directory
1494
- * resolve to the same entry point. Avoids repeated filesystem walks.
1495
- */
1496
- function cachedAutoDetect(filePath) {
1497
- if (!filePath) return autoDetectEntryPoint(filePath);
1498
- const dir = (0, node_path.dirname)((0, node_path.resolve)(filePath));
1499
- const cached = autoDetectCache.get(dir);
1500
- if (cached !== void 0) return cached;
1501
- const result = autoDetectEntryPoint(filePath);
1502
- autoDetectCache.set(dir, result);
1503
- return result;
1504
- }
1505
- /**
1506
- * Returns the design system cache, loading synchronously on first call.
1507
- * Uses execFileSync internally to bridge the async Tailwind API.
1749
+ * Load the design system for a specific CSS entry point.
1508
1750
  *
1509
- * Supports multiple design systems: each unique CSS entry point gets its own cache.
1510
- * In monorepos, files in different packages auto-detect to different entry points
1511
- * and each gets the correct DS.
1751
+ * Throws `DesignSystemLoadError` if the load fails for any reason. Callers
1752
+ * (rules via `createLazyLoader`) catch via `reportFatalDsError` and surface
1753
+ * the failure as a single Program-level diagnostic.
1512
1754
  *
1513
- * Resolution order: rule option `entryPoint` > `settings.tailwindcss.entryPoint` > auto-detect.
1755
+ * Cached per absolute entry-point path, keyed by mtime. In monorepos each
1756
+ * unique CSS gets its own cache entry.
1514
1757
  */
1515
- function getLoadedDesignSystem(entryPoint, settings, filePath) {
1516
- const settingsEntry = entryPointFromSettings(settings);
1517
- const explicitEntry = entryPoint ?? (Array.isArray(settingsEntry) ? resolveClosestEntryPoint(settingsEntry, filePath) : settingsEntry);
1518
- const cssPath = explicitEntry ?? cachedAutoDetect(filePath) ?? lastLoadedPath;
1519
- if (!cssPath) return null;
1758
+ function getLoadedDesignSystem(cssPath, settings) {
1520
1759
  const resolvedPath = (0, node_path.resolve)(cssPath);
1760
+ let mtime;
1521
1761
  try {
1522
- const mtime = (0, node_fs.statSync)(resolvedPath).mtimeMs;
1523
- const cached = dsCache.get(resolvedPath);
1524
- if (cached && cached.mtime === mtime) {
1525
- if (explicitEntry) lastLoadedPath = resolvedPath;
1526
- return {
1527
- cache: cached.cache,
1528
- entryPoint: resolvedPath
1529
- };
1530
- }
1531
- const data = loadDesignSystemSync(resolvedPath, timeoutFromSettings(settings));
1532
- if (!data) return null;
1533
- const cache = DesignSystemCache.fromPrecomputed(data);
1534
- dsCache.set(resolvedPath, {
1535
- cache,
1536
- mtime
1537
- });
1538
- debugLog(`Loaded design system from "${resolvedPath}"`);
1539
- if (explicitEntry) lastLoadedPath = resolvedPath;
1540
- return {
1541
- cache,
1542
- entryPoint: resolvedPath
1543
- };
1544
- } catch {
1545
- return null;
1546
- }
1762
+ mtime = (0, node_fs.statSync)(resolvedPath).mtimeMs;
1763
+ } catch (cause) {
1764
+ throw new DesignSystemLoadError(`Could not stat CSS entry point: ${resolvedPath}`, "Check that the file exists and is readable. The path is resolved relative to the oxlint working directory.", { cause: cause instanceof Error ? cause : void 0 });
1765
+ }
1766
+ const cached = dsCache.get(resolvedPath);
1767
+ if (cached && cached.mtime === mtime) return {
1768
+ cache: cached.cache,
1769
+ entryPoint: resolvedPath
1770
+ };
1771
+ const data = loadDesignSystemSync(resolvedPath, timeoutFromSettings(settings));
1772
+ const cache = DesignSystemCache.fromPrecomputed(data);
1773
+ dsCache.set(resolvedPath, {
1774
+ cache,
1775
+ mtime
1776
+ });
1777
+ debugLog(`Loaded design system from "${resolvedPath}"`);
1778
+ return {
1779
+ cache,
1780
+ entryPoint: resolvedPath
1781
+ };
1547
1782
  }
1548
1783
  /**
1549
- * Creates a lazy DS loader that resolves the correct design system per file.
1784
+ * Lazy DS loader for a rule. Resolves the correct design system for each
1785
+ * file being linted, using (in priority order):
1786
+ *
1787
+ * 1. Rule option `entryPoint` (a string path).
1788
+ * 2. `settings.tailwindcss.entryPoint` as a string.
1789
+ * 3. `settings.tailwindcss.entryPoint` as an `EntryPointMapping[]` —
1790
+ * first matching glob (relative to CWD) wins.
1550
1791
  *
1551
- * In `createOnce`, `context.settings` and `context.filename` throw. When visitors
1552
- * run, they become available. The loader re-resolves when the filename changes,
1553
- * supporting monorepos where different files need different design systems.
1792
+ * If none of those produce an entry point for the current file, throws
1793
+ * `MissingEntryPointError`. If the resolved CSS fails to load, throws
1794
+ * `DesignSystemLoadError`. Both extend `OxlintTailwindError` and are
1795
+ * meant to be caught by `reportFatalDsError` in the rule's `check()`.
1554
1796
  *
1555
- * When a fixed entryPoint is provided (rule option or settings), it's used for all
1556
- * files and cached after first resolution.
1797
+ * `context.settings` and `context.filename` are unavailable in `createOnce`,
1798
+ * so the actual work is deferred until the returned thunk is invoked from
1799
+ * inside a visitor.
1557
1800
  */
1558
1801
  function createLazyLoader(context) {
1559
- let lastFilePath;
1560
- let lastResult = null;
1561
- let fixedEntryResolved = false;
1562
- let fixedResult = null;
1563
1802
  let debugInitialized = false;
1803
+ let lastFilePath;
1804
+ let lastResult;
1564
1805
  return () => {
1565
- let entryPoint;
1566
- try {
1567
- entryPoint = (context.options?.[0])?.entryPoint;
1568
- } catch {}
1569
- let settings;
1570
- try {
1571
- settings = context.settings;
1572
- } catch {}
1573
- let filePath;
1574
- try {
1575
- filePath = context.filename;
1576
- } catch {}
1806
+ const filePath = safeFilename(context);
1807
+ if (filePath !== void 0 && filePath === lastFilePath && lastResult) return lastResult;
1808
+ const ruleOptionEntry = safeOptions(context)?.entryPoint;
1809
+ const settings = safeSettings(context);
1577
1810
  if (!debugInitialized && settings) {
1578
1811
  debugInitialized = true;
1579
1812
  setDebugEnabled(isDebugEnabled(settings));
1580
1813
  }
1581
- const settingsEntry = entryPointFromSettings(settings);
1582
- const fixedEntry = entryPoint ?? (typeof settingsEntry === "string" ? settingsEntry : void 0);
1583
- if (fixedEntry) {
1584
- if (fixedEntryResolved) return fixedResult;
1585
- fixedEntryResolved = true;
1586
- fixedResult = getLoadedDesignSystem(fixedEntry, settings, filePath);
1587
- if (fixedResult && filePath) debugLog(`${(0, node_path.relative)(process.cwd(), filePath)} → ${(0, node_path.relative)(process.cwd(), fixedResult.entryPoint)}`);
1588
- return fixedResult;
1589
- }
1590
- if (Array.isArray(settingsEntry)) {
1591
- const closest = resolveClosestEntryPoint(settingsEntry, filePath);
1592
- if (filePath && filePath === lastFilePath) return lastResult;
1593
- if (filePath) lastFilePath = filePath;
1594
- lastResult = getLoadedDesignSystem(closest, settings, filePath);
1595
- if (lastResult && filePath) debugLog(`${(0, node_path.relative)(process.cwd(), filePath)} → ${(0, node_path.relative)(process.cwd(), lastResult.entryPoint)}`);
1596
- return lastResult;
1597
- }
1598
- if (filePath && filePath === lastFilePath) return lastResult;
1599
- if (filePath) lastFilePath = filePath;
1600
- lastResult = getLoadedDesignSystem(void 0, settings, filePath);
1601
- if (lastResult && filePath) debugLog(`${(0, node_path.relative)(process.cwd(), filePath)} → ${(0, node_path.relative)(process.cwd(), lastResult.entryPoint)}`);
1814
+ const cssPath = resolveEntryPointForFile(ruleOptionEntry, entryPointFromSettings(settings), filePath);
1815
+ lastFilePath = filePath;
1816
+ lastResult = getLoadedDesignSystem(cssPath, settings);
1817
+ if (filePath) debugLog(`${(0, node_path.relative)(process.cwd(), filePath)} → ${(0, node_path.relative)(process.cwd(), lastResult.entryPoint)}`);
1602
1818
  return lastResult;
1603
1819
  };
1604
1820
  }
1605
- //#endregion
1606
- //#region src/types.ts
1607
1821
  /**
1608
- * Safely read context.options.
1609
- *
1610
- * In oxlint, `context.options` is `null` inside `createOnce()` — options are
1611
- * only populated when visitors run. Call this lazily (inside `check()` or a
1612
- * visitor) to get the user's configured options.
1822
+ * Pure resolution from (rule option, settings entry, file path) to a CSS
1823
+ * entry-point path. Exported for testability.
1613
1824
  *
1614
- * In oxlint <1.31.0 the getter may throw — the try/catch handles that.
1825
+ * Throws `MissingEntryPointError` if nothing resolves. The error message
1826
+ * names the file so the user knows which one tripped the configuration.
1615
1827
  */
1616
- function safeOptions(context) {
1617
- try {
1618
- return context.options?.[0] ?? void 0;
1619
- } catch {
1620
- return;
1828
+ function resolveEntryPointForFile(ruleOptionEntry, settingsEntry, filePath) {
1829
+ if (ruleOptionEntry) return ruleOptionEntry;
1830
+ if (typeof settingsEntry === "string") return settingsEntry;
1831
+ if (Array.isArray(settingsEntry)) {
1832
+ if (!filePath) throw new MissingEntryPointError("`settings.tailwindcss.entryPoint` is a mapping array but no file path is available to match against.", "This usually means the rule ran outside the linter context. Open an issue if you see this in a real lint run.");
1833
+ const matched = resolveByGlobMapping(settingsEntry, filePath, process.cwd());
1834
+ if (matched) return matched;
1835
+ throw new MissingEntryPointError(`No \`entryPoint\` mapping matched \`${filePath}\`.`, "Add a mapping covering this file to `settings.tailwindcss.entryPoint`, or use a `\"**\"` fallback entry.");
1621
1836
  }
1837
+ throw new MissingEntryPointError(`\`settings.tailwindcss.entryPoint\` is required${filePath ? ` (linting \`${filePath}\`)` : ""}.`, "Set it to a string (single-project) or an array of `{ files, use }` mappings (monorepo).");
1622
1838
  }
1839
+ //#endregion
1840
+ //#region src/utils/report.ts
1623
1841
  /**
1624
- * Safely read context.settings.
1842
+ * Shared reporter for the "first-as-fix, rest-as-suggestion" pattern.
1843
+ *
1844
+ * Nine rules (enforce-canonical, enforce-logical, enforce-physical,
1845
+ * enforce-consistent-variable-syntax, enforce-consistent-important-position,
1846
+ * enforce-negative-arbitrary-values, no-deprecated-classes,
1847
+ * no-unnecessary-arbitrary-value, prefer-theme-tokens) all emit
1848
+ * replacements via the same shape:
1849
+ *
1850
+ * 1. Collect `{ cls, replacement }` entries from a class string.
1851
+ * 2. Rebuild the full class string with replacements applied.
1852
+ * 3. Emit ONE diagnostic with the autofix attached.
1853
+ * 4. Emit one MORE diagnostic per remaining offender, each carrying
1854
+ * the same autofix as a `suggest`.
1625
1855
  *
1626
- * Like `safeOptions`, `context.settings` may not be accessible in `createOnce()`.
1627
- * The try/catch handles that gracefully.
1856
+ * oxlint's fixer is single-shot per AST node, so multiple offenders in the
1857
+ * same class string can only get one mechanical fix; the rest stay as
1858
+ * suggestions the IDE can offer interactively.
1628
1859
  */
1629
- function safeSettings(context) {
1630
- try {
1631
- return context.settings ?? void 0;
1632
- } catch {
1633
- return;
1860
+ /**
1861
+ * Emit autofix + suggestion diagnostics for a list of class replacements.
1862
+ *
1863
+ * If `offending` is empty, no-op. The fixer's `replaceTextRange` is shared
1864
+ * across all diagnostics — the first one is the primary fix, the rest carry
1865
+ * the same fix as a suggestion (oxlint can only apply one autofix per node).
1866
+ */
1867
+ function reportClassReplacements(context, loc, split, classes, offending, options) {
1868
+ if (offending.length === 0) return;
1869
+ const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
1870
+ const fixedValue = rebuildClassString(split, classes.map((c) => replacements.get(c) ?? c));
1871
+ const replacementKey = options.replacementKey ?? "replacement";
1872
+ const suggestMessageId = options.suggestMessageId ?? "suggestReplace";
1873
+ const applyFix = (fixer) => fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
1874
+ const report = context.report;
1875
+ for (let i = 0; i < offending.length; i++) {
1876
+ const { cls, replacement } = offending[i];
1877
+ const primaryData = {
1878
+ className: cls,
1879
+ [replacementKey]: replacement
1880
+ };
1881
+ if (i === 0) report({
1882
+ node: loc.node,
1883
+ messageId: options.messageId,
1884
+ data: primaryData,
1885
+ fix: applyFix
1886
+ });
1887
+ else report({
1888
+ node: loc.node,
1889
+ messageId: options.messageId,
1890
+ data: primaryData,
1891
+ suggest: [{
1892
+ messageId: suggestMessageId,
1893
+ data: {
1894
+ className: cls,
1895
+ replacement
1896
+ },
1897
+ fix: applyFix
1898
+ }]
1899
+ });
1634
1900
  }
1635
1901
  }
1636
1902
  //#endregion
@@ -1663,71 +1929,30 @@ const noDeprecatedClasses = (0, _oxlint_plugins.defineRule)({
1663
1929
  additionalProperties: false
1664
1930
  }],
1665
1931
  hasSuggestions: true,
1932
+ defaultOptions: [{}],
1666
1933
  messages: {
1667
1934
  deprecated: "\"{{className}}\" is deprecated in Tailwind v4. Use \"{{replacement}}\" instead.",
1668
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
1935
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
1936
+ ...DS_UNAVAILABLE_MESSAGE
1669
1937
  }
1670
1938
  },
1671
1939
  createOnce(context) {
1672
1940
  const getDS = createLazyLoader(context);
1673
1941
  function check(locations) {
1674
- const dsResult = getDS();
1942
+ if (locations.length === 0) return;
1943
+ if (!safeGetDS(getDS, context, locations[0].node)) return;
1675
1944
  for (const loc of locations) {
1676
1945
  const split = splitClassesWithSeparators(loc.value);
1677
- const classes = split.classes;
1678
- const offending = [];
1679
- for (const cls of classes) {
1946
+ const offending = split.classes.flatMap((cls) => {
1680
1947
  const { utility, variant } = splitUtilityAndVariant(cls);
1681
- const hasImportantPrefix = utility.startsWith("!");
1682
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
1683
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
1948
+ const { bare: bareUtility, position } = splitImportant(utility);
1684
1949
  const replacement = DEPRECATED_MAP[bareUtility];
1685
- if (!replacement) continue;
1686
- if (dsResult) {
1687
- const canonical = dsResult.cache.canonicalize(bareUtility);
1688
- if (canonical !== bareUtility && canonical === replacement) {}
1689
- }
1690
- const fullReplacement = variant + (hasImportantPrefix ? "!" : "") + replacement + (hasImportantSuffix ? "!" : "");
1691
- offending.push({
1950
+ return replacement ? [{
1692
1951
  cls,
1693
- replacement: fullReplacement
1694
- });
1695
- }
1696
- if (offending.length === 0) continue;
1697
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
1698
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
1699
- for (let i = 0; i < offending.length; i++) {
1700
- const { cls, replacement } = offending[i];
1701
- if (i === 0) context.report({
1702
- node: loc.node,
1703
- messageId: "deprecated",
1704
- data: {
1705
- className: cls,
1706
- replacement
1707
- },
1708
- fix(fixer) {
1709
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
1710
- }
1711
- });
1712
- else context.report({
1713
- node: loc.node,
1714
- messageId: "deprecated",
1715
- data: {
1716
- className: cls,
1717
- replacement
1718
- },
1719
- suggest: [{
1720
- messageId: "suggestReplace",
1721
- data: {
1722
- className: cls,
1723
- replacement
1724
- },
1725
- fix(fixer) {
1726
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
1727
- }
1728
- }]
1729
- });
1730
- }
1952
+ replacement: variant + reattachImportant(replacement, position)
1953
+ }] : [];
1954
+ });
1955
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "deprecated" });
1731
1956
  }
1732
1957
  }
1733
1958
  return createExtractorVisitors(context, check);
@@ -1762,37 +1987,27 @@ const noUnknownClasses = (0, _oxlint_plugins.defineRule)({
1762
1987
  messages: {
1763
1988
  unknown: "\"{{className}}\" is not a valid Tailwind class.",
1764
1989
  unknownWithSuggestion: "\"{{className}}\" is not a valid Tailwind class. Did you mean \"{{suggestion}}\"?",
1765
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
1990
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
1991
+ ...DS_UNAVAILABLE_MESSAGE
1766
1992
  }
1767
1993
  },
1768
1994
  createOnce(context) {
1769
1995
  const getDS = createLazyLoader(context);
1770
- let _allowlist = null;
1771
- let _ignorePrefixes = null;
1772
- function getLazyOptions() {
1773
- if (_allowlist === null) {
1774
- const opts = safeOptions(context);
1775
- _allowlist = new Set(opts?.allowlist ?? []);
1776
- _ignorePrefixes = opts?.ignorePrefixes ?? [];
1777
- }
1778
- return {
1779
- allowlist: _allowlist,
1780
- ignorePrefixes: _ignorePrefixes
1781
- };
1782
- }
1996
+ const getLazyOptions = createLazyOptions(context, (o) => ({
1997
+ allowlist: new Set(o?.allowlist ?? []),
1998
+ ignorePrefixes: o?.ignorePrefixes ?? []
1999
+ }));
1783
2000
  function shouldIgnore(className) {
1784
2001
  const { allowlist, ignorePrefixes } = getLazyOptions();
1785
2002
  if (allowlist.has(className)) return true;
1786
2003
  return ignorePrefixes.some((prefix) => className.startsWith(prefix));
1787
2004
  }
1788
2005
  function stripModifiers(className) {
1789
- let stripped = className;
1790
- if (stripped.startsWith("!")) stripped = stripped.slice(1);
1791
- if (stripped.endsWith("!")) stripped = stripped.slice(0, -1);
1792
- return stripped;
2006
+ return splitImportant(className).bare;
1793
2007
  }
1794
2008
  function check(locations) {
1795
- const ds = getDS();
2009
+ if (locations.length === 0) return;
2010
+ const ds = safeGetDS(getDS, context, locations[0].node);
1796
2011
  if (!ds) return;
1797
2012
  const { cache } = ds;
1798
2013
  for (const loc of locations) {
@@ -1836,7 +2051,122 @@ const noUnknownClasses = (0, _oxlint_plugins.defineRule)({
1836
2051
  }
1837
2052
  });
1838
2053
  //#endregion
2054
+ //#region src/rules/no-conflicting-classes/spec.ts
2055
+ const COMPLEMENTARY_GROUPS = [
2056
+ {
2057
+ pattern: /^(from|via|to)-/,
2058
+ reason: "Gradient stops (`from-*`, `via-*`, `to-*`) share `--tw-gradient-stops`; different prefixes compose, same prefix conflicts."
2059
+ },
2060
+ {
2061
+ pattern: /^(transition|duration|ease|delay)(?:-|$)/,
2062
+ reason: "`transition-*` composes with `duration-*`, `ease-*`, `delay-*` — `transition-all` itself has no `--tw-*` vars so the heuristic misses it."
2063
+ },
2064
+ {
2065
+ pattern: /^-?(translate|scale|rotate|skew)-/,
2066
+ reason: "Transform axes (translate / scale / rotate / skew) compose into a single `transform`; the overlap is not captured in `cssProps`."
2067
+ },
2068
+ {
2069
+ pattern: /^-?mask-((?:linear|radial|conic|[trblxy])(?:-(?:from|via|to|at))?)(?:-|$)/,
2070
+ reason: "Mask gradients: different families (e.g. `mask-linear-*` vs `mask-radial-*`) or roles (`from`/`via`/`to`/`at`) compose; same family+role conflicts."
2071
+ },
2072
+ {
2073
+ pattern: /^prose(?:-|$)/,
2074
+ reason: "`prose` + `prose-sm`/`prose-lg`/`prose-xl` modify the same scope and are designed to compose."
2075
+ }
2076
+ ];
2077
+ const COMPOSITION_PAIRS = [
2078
+ {
2079
+ a: /^text-/,
2080
+ b: /^leading-/,
2081
+ reason: "`text-*` sets line-height via its size token; `leading-*` overrides it."
2082
+ },
2083
+ {
2084
+ a: /^text-/,
2085
+ b: /^tracking-/,
2086
+ reason: "`text-*` may set letter-spacing via its size token; `tracking-*` overrides it."
2087
+ },
2088
+ {
2089
+ a: /^border(?:-[0-9]|$)/,
2090
+ b: /^border-(?:solid|dashed|dotted|double|hidden|none)$/,
2091
+ reason: "`border-*` (width) composes with `border-{solid,dashed,…}` (style)."
2092
+ },
2093
+ {
2094
+ a: /^divide-/,
2095
+ b: /^border(?:-[trblxyse])?-/,
2096
+ reason: "`divide-*` styles direct children; `border-*` styles the element itself."
2097
+ },
2098
+ {
2099
+ a: /^prose(?:-|$)/,
2100
+ b: /^max-w-/,
2101
+ reason: "`prose` sets a default max-width; `max-w-*` overrides it."
2102
+ },
2103
+ {
2104
+ a: /^animate-in$/,
2105
+ b: /^(?:fade|spin|zoom|blur)-in(?:-|$)|^slide-in-from-/,
2106
+ reason: "`animate-in` initializes all `--tw-enter-*` vars; `*-in` modifiers each override one. (`tailwindcss-animate` / `tw-animate-css`.)"
2107
+ },
2108
+ {
2109
+ a: /^animate-out$/,
2110
+ b: /^(?:fade|spin|zoom|blur)-out(?:-|$)|^slide-out-to-/,
2111
+ reason: "`animate-out` initializes all `--tw-exit-*` vars; `*-out` modifiers each override one."
2112
+ },
2113
+ {
2114
+ a: /^mask-(?:add|subtract|intersect|exclude)$/,
2115
+ b: /^-?mask-(?:linear|radial|conic|[trblxy])-/,
2116
+ reason: "`mask-{add,subtract,intersect,exclude}` are mask-composite modes that compose with mask-gradient utilities."
2117
+ }
2118
+ ];
2119
+ //#endregion
1839
2120
  //#region src/rules/no-conflicting-classes.ts
2121
+ /**
2122
+ * Two utilities compose via CSS custom properties if both define their own
2123
+ * --tw-* properties that don't overlap — they each contribute to a shared
2124
+ * shorthand (e.g. `shadow` and `ring` both end up in `box-shadow` via
2125
+ * different intermediate vars).
2126
+ */
2127
+ function isCompositionViaCssVars(propsA, propsB) {
2128
+ const customA = propsA.filter((p) => p.startsWith("--"));
2129
+ const customB = propsB.filter((p) => p.startsWith("--"));
2130
+ if (customA.length === 0 || customB.length === 0) return false;
2131
+ return !customA.some((p) => customB.includes(p));
2132
+ }
2133
+ /**
2134
+ * Detect a narrowing override: the later class's CSS properties are a strict
2135
+ * subset of the earlier class's, so the later class refines one of the
2136
+ * shorthand's properties (size-4 h-6, rounded-t-lg rounded-tl-sm, truncate
2137
+ * text-clip). Direction-sensitive: the inverse means the wider later class
2138
+ * clobbers a prior narrower override.
2139
+ */
2140
+ function isNarrowingOverride(propsEarlier, propsLater) {
2141
+ if (propsLater.length === 0 || propsLater.length >= propsEarlier.length) return false;
2142
+ const setEarlier = new Set(propsEarlier);
2143
+ return propsLater.every((p) => setEarlier.has(p));
2144
+ }
2145
+ /**
2146
+ * Returns true if two classes (within the same variant) should NOT be reported
2147
+ * as conflicting despite sharing CSS properties. Pure: regex tables are passed
2148
+ * in (or default to the module-level constants).
2149
+ */
2150
+ function shouldSkipPair(a, b, propsA, propsB, rules = {}) {
2151
+ if (isCompositionViaCssVars(propsA, propsB)) return true;
2152
+ if (isNarrowingOverride(propsA, propsB)) return true;
2153
+ const ua = splitImportant(extractUtility(a)).bare;
2154
+ const ub = splitImportant(extractUtility(b)).bare;
2155
+ const groups = rules.complementaryGroups !== void 0 ? rules.complementaryGroups.map((pattern) => ({ pattern })) : COMPLEMENTARY_GROUPS;
2156
+ for (const { pattern: re } of groups) {
2157
+ const ma = ua.match(re);
2158
+ const mb = ub.match(re);
2159
+ if (!ma || !mb) continue;
2160
+ if (ma[1] === void 0) return true;
2161
+ if (ma[1] !== mb[1]) return true;
2162
+ }
2163
+ const pairs = rules.compositionPairs !== void 0 ? rules.compositionPairs.map(([a, b]) => ({
2164
+ a,
2165
+ b
2166
+ })) : COMPOSITION_PAIRS;
2167
+ for (const { a: reA, b: reB } of pairs) if (reA.test(ua) && reB.test(ub) || reA.test(ub) && reB.test(ua)) return true;
2168
+ return false;
2169
+ }
1840
2170
  const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
1841
2171
  meta: {
1842
2172
  type: "problem",
@@ -1846,12 +2176,17 @@ const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
1846
2176
  properties: { entryPoint: { type: "string" } },
1847
2177
  additionalProperties: false
1848
2178
  }],
1849
- messages: { conflict: "\"{{classA}}\" and \"{{classB}}\" affect {{properties}}. \"{{winner}}\" takes precedence (appears later)." }
2179
+ defaultOptions: [{}],
2180
+ messages: {
2181
+ conflict: "\"{{classA}}\" and \"{{classB}}\" affect {{properties}}. \"{{winner}}\" takes precedence (appears later).",
2182
+ ...DS_UNAVAILABLE_MESSAGE
2183
+ }
1850
2184
  },
1851
2185
  createOnce(context) {
1852
2186
  const getDS = createLazyLoader(context);
1853
2187
  function check(locations) {
1854
- const ds = getDS();
2188
+ if (locations.length === 0) return;
2189
+ const ds = safeGetDS(getDS, context, locations[0].node);
1855
2190
  if (!ds) return;
1856
2191
  const { cache } = ds;
1857
2192
  for (const loc of locations) {
@@ -1868,43 +2203,9 @@ const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
1868
2203
  if (variantClasses.length < 2) continue;
1869
2204
  const propsMap = /* @__PURE__ */ new Map();
1870
2205
  for (const cls of variantClasses) {
1871
- let utility = extractUtility(cls);
1872
- if (utility.startsWith("!")) utility = utility.slice(1);
1873
- else if (utility.endsWith("!")) utility = utility.slice(0, -1);
1874
- const props = cache.getCssProperties(utility);
2206
+ const props = cache.getCssProperties(splitImportant(extractUtility(cls)).bare);
1875
2207
  propsMap.set(cls, props);
1876
2208
  }
1877
- const COMPLEMENTARY_GROUPS = [
1878
- /^(?:from|via|to)-/,
1879
- /^(?:transition|duration|ease|delay)(?:-|$)/,
1880
- /^-?(?:translate|scale|rotate|skew)-/,
1881
- /^prose(?:-|$)/
1882
- ];
1883
- const COMPOSITION_PAIRS = [
1884
- [/^text-/, /^leading-/],
1885
- [/^text-/, /^tracking-/],
1886
- [/^border(?:-[0-9]|$)/, /^border-(?:solid|dashed|dotted|double|hidden|none)$/],
1887
- [/^divide-/, /^border(?:-[trblxyse])?-/],
1888
- [/^prose(?:-|$)/, /^max-w-/]
1889
- ];
1890
- function isCompositionViaCssVars(propsA, propsB) {
1891
- const customA = propsA.filter((p) => p.startsWith("--"));
1892
- const customB = propsB.filter((p) => p.startsWith("--"));
1893
- if (customA.length === 0 || customB.length === 0) return false;
1894
- return !customA.some((p) => customB.includes(p));
1895
- }
1896
- function shouldSkipPair(a, b, propsA, propsB) {
1897
- if (isCompositionViaCssVars(propsA, propsB)) return true;
1898
- let ua = extractUtility(a);
1899
- let ub = extractUtility(b);
1900
- if (ua.startsWith("!")) ua = ua.slice(1);
1901
- else if (ua.endsWith("!")) ua = ua.slice(0, -1);
1902
- if (ub.startsWith("!")) ub = ub.slice(1);
1903
- else if (ub.endsWith("!")) ub = ub.slice(0, -1);
1904
- for (const re of COMPLEMENTARY_GROUPS) if (re.test(ua) && re.test(ub)) return true;
1905
- for (const [reA, reB] of COMPOSITION_PAIRS) if (reA.test(ua) && reB.test(ub) || reA.test(ub) && reB.test(ua)) return true;
1906
- return false;
1907
- }
1908
2209
  for (let i = 0; i < variantClasses.length; i++) {
1909
2210
  const classA = variantClasses[i];
1910
2211
  const propsA = propsMap.get(classA) ?? [];
@@ -1935,42 +2236,168 @@ const noConflictingClasses = (0, _oxlint_plugins.defineRule)({
1935
2236
  }
1936
2237
  });
1937
2238
  //#endregion
1938
- //#region src/design-system/canonicalize-service.ts
2239
+ //#region src/design-system/ds-worker.ts
1939
2240
  /**
1940
- * Persistent canonicalize service using worker_threads + SharedArrayBuffer.
1941
- *
1942
- * Calls `ds.canonicalizeCandidates([cls], { rem })` dynamically via a worker
1943
- * thread. Same pattern as sort-service.ts — loads the DS once, then accepts
1944
- * requests synchronously via Atomics.wait().
2241
+ * Generic worker-thread service wrapping `__unstable__loadDesignSystem`.
1945
2242
  *
1946
- * This enables canonicalization of arbitrary user classes (e.g. `p-[2px]` → `p-0.5`)
1947
- * which can't be precomputed because the input space is infinite.
2243
+ * `sort-service.ts` and `canonicalize-service.ts` used to be near-byte-identical
2244
+ * (~500 LOC) — both spawned a worker that loaded the design system, then served
2245
+ * synchronous requests over a SharedArrayBuffer using `Atomics.wait`. The only
2246
+ * real difference was the body of the request loop: `getClassOrder` vs
2247
+ * `canonicalizeCandidates`. This class encapsulates the entire shared protocol
2248
+ * — SharedArrayBuffer layout, state machine, lifecycle, fail-loud — and each
2249
+ * service shrinks to ~40 LOC of singleton + public signature.
1948
2250
  *
1949
- * ## Per-class cache (process-wide)
2251
+ * v1: failures throw `SortServiceError`. The error is sticky for the lifetime
2252
+ * of the process (per cssPath) so subsequent calls don't pay another
2253
+ * init-timeout cost. Callers wrap via `safeGetDS` to surface the failure as a
2254
+ * single `designSystemUnavailable` diagnostic.
2255
+ */
2256
+ const BUFFER_SIZE = 4 * 1024 * 1024;
2257
+ const HEADER_INTS = 4;
2258
+ const DATA_OFFSET = 20;
2259
+ const INIT_TIMEOUT = 6e4;
2260
+ const REQUEST_TIMEOUT = 3e4;
2261
+ var DesignSystemWorker = class {
2262
+ opts;
2263
+ ready = null;
2264
+ lastError = null;
2265
+ constructor(opts) {
2266
+ this.opts = opts;
2267
+ }
2268
+ /**
2269
+ * Ensure the worker is running and pointed at `cssPath`. Returns the
2270
+ * ready state. Throws `SortServiceError` on any failure (init timeout,
2271
+ * spawn error, DS-load error). Sticky: subsequent calls for the same
2272
+ * cssPath rethrow without retrying.
2273
+ */
2274
+ ensure(cssPath) {
2275
+ if (this.lastError && this.ready?.cssPath === cssPath) throw this.lastError;
2276
+ if (this.ready && this.ready.cssPath === cssPath) return this.ready;
2277
+ if (this.ready) this.cleanup();
2278
+ this.lastError = null;
2279
+ if (TAILWIND_NODE_PATH === null) {
2280
+ this.lastError = new SortServiceError(`Could not resolve '@tailwindcss/node' for the ${this.opts.serviceName} worker.`, "Install '@tailwindcss/node' (or upgrade oxlint-tailwindcss) and re-run.");
2281
+ throw this.lastError;
2282
+ }
2283
+ const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
2284
+ const controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
2285
+ const lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
2286
+ const dataArea = new Uint8Array(sharedBuffer, DATA_OFFSET);
2287
+ let worker;
2288
+ try {
2289
+ worker = new node_worker_threads.Worker(this.opts.workerScript, {
2290
+ eval: true,
2291
+ workerData: {
2292
+ sharedBuffer,
2293
+ cssPath,
2294
+ tailwindNodePath: TAILWIND_NODE_PATH
2295
+ }
2296
+ });
2297
+ } catch (cause) {
2298
+ this.lastError = new SortServiceError(`Failed to spawn ${this.opts.serviceName} worker for "${cssPath}".`, "This is unexpected; please open an issue with the error details.", { cause: cause instanceof Error ? cause : void 0 });
2299
+ throw this.lastError;
2300
+ }
2301
+ worker.unref();
2302
+ worker.on("error", (err) => {
2303
+ this.lastError = new SortServiceError(`${this.opts.serviceName} worker died: ${err.message}`, "The worker will not be restarted in this process. Restart the lint session.", { cause: err });
2304
+ });
2305
+ if (Atomics.wait(controlArray, 2, 0, INIT_TIMEOUT) === "timed-out") {
2306
+ this.lastError = new SortServiceError(`${this.opts.serviceName} worker timed out loading the design system from "${cssPath}" after ${INIT_TIMEOUT}ms.`, "Raise settings.tailwindcss.timeout if your machine is slow, or verify the CSS imports resolve.");
2307
+ this.terminateWorker(worker);
2308
+ throw this.lastError;
2309
+ }
2310
+ if (controlArray[2] === -1) {
2311
+ this.lastError = new SortServiceError(`${this.opts.serviceName} worker failed to load the design system from "${cssPath}".`, "Verify @tailwindcss/node is installed and the CSS file (and its imports) is valid.");
2312
+ this.terminateWorker(worker);
2313
+ throw this.lastError;
2314
+ }
2315
+ this.ready = {
2316
+ worker,
2317
+ controlArray,
2318
+ lengthView,
2319
+ dataArea,
2320
+ cssPath
2321
+ };
2322
+ return this.ready;
2323
+ }
2324
+ /**
2325
+ * Send a request to the worker and synchronously wait for the response.
2326
+ * Throws `SortServiceError` on any failure.
2327
+ */
2328
+ callSync(cssPath, req) {
2329
+ const state = this.ensure(cssPath);
2330
+ const requestBytes = Buffer.from(JSON.stringify(req), "utf-8");
2331
+ 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.");
2332
+ state.dataArea.set(requestBytes, 0);
2333
+ state.lengthView.setUint32(0, requestBytes.length);
2334
+ Atomics.store(state.controlArray, 0, 1);
2335
+ Atomics.notify(state.controlArray, 0);
2336
+ if (Atomics.wait(state.controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
2337
+ this.lastError = new SortServiceError(`${this.opts.serviceName} worker request timed out after ${REQUEST_TIMEOUT}ms.`, "Raise settings.tailwindcss.timeout if your machine is slow.");
2338
+ this.cleanup();
2339
+ throw this.lastError;
2340
+ }
2341
+ const responseLen = state.lengthView.getUint32(0);
2342
+ const responseStr = Buffer.from(state.dataArea.slice(0, responseLen)).toString("utf-8");
2343
+ Atomics.store(state.controlArray, 1, 0);
2344
+ let parsed;
2345
+ try {
2346
+ parsed = JSON.parse(responseStr);
2347
+ } catch (cause) {
2348
+ this.lastError = 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 });
2349
+ this.cleanup();
2350
+ throw this.lastError;
2351
+ }
2352
+ if (parsed === null) {
2353
+ this.lastError = new SortServiceError(`${this.opts.serviceName} worker returned null — request body was rejected.`, "This is a bug; please open an issue with the input that triggered it.");
2354
+ this.cleanup();
2355
+ throw this.lastError;
2356
+ }
2357
+ return parsed;
2358
+ }
2359
+ reset() {
2360
+ this.cleanup();
2361
+ this.lastError = null;
2362
+ }
2363
+ cleanup() {
2364
+ if (this.ready) {
2365
+ this.terminateWorker(this.ready.worker);
2366
+ this.ready = null;
2367
+ }
2368
+ }
2369
+ terminateWorker(worker) {
2370
+ try {
2371
+ worker.terminate();
2372
+ } catch {}
2373
+ }
2374
+ };
2375
+ //#endregion
2376
+ //#region src/design-system/canonicalize-service.ts
2377
+ /**
2378
+ * Persistent canonicalize service backed by `DesignSystemWorker`.
1950
2379
  *
1951
- * Results are cached by `cssPath\0rem\0class`. The worker is invoked only for
1952
- * cache misses. In practice the cache converges quickly — after the first few
1953
- * files any given class has been seen, and every subsequent lookup is O(1).
2380
+ * Calls `ds.canonicalizeCandidates([cls], { rem })` one class at a time
2381
+ * (the design system deduplicates its input, so batching changes the
2382
+ * result shape — see sync-loader.ts). The shared protocol lives in
2383
+ * `./ds-worker.ts`.
1954
2384
  *
1955
- * ## Per-class worker calls
2385
+ * ## Per-class cache (process-wide)
1956
2386
  *
1957
- * `ds.canonicalizeCandidates` deduplicates its input (see sync-loader.ts note),
1958
- * so the worker MUST call it one class at a time to preserve input order/length.
1959
- * The cache amortizes the per-call overhead.
1960
- */
1961
- const BUFFER_SIZE$1 = 4 * 1024 * 1024;
1962
- const HEADER_INTS$1 = 4;
1963
- const DATA_OFFSET$1 = HEADER_INTS$1 * 4 + 4;
1964
- const INIT_TIMEOUT$1 = 3e4;
1965
- const REQUEST_TIMEOUT$1 = 1e4;
1966
- const WORKER_SCRIPT$1 = `
2387
+ * Results are cached by `${cssPath}\0${rem}\0${class}`. The worker is
2388
+ * invoked only for cache misses. In practice the cache converges quickly —
2389
+ * after the first few files any given class has been seen, and every
2390
+ * subsequent lookup is O(1).
2391
+ */
2392
+ const canonWorker = new DesignSystemWorker({
2393
+ workerScript: `
1967
2394
  const { workerData } = require('worker_threads');
1968
2395
 
1969
2396
  async function main() {
1970
2397
  const { sharedBuffer, cssPath } = workerData;
1971
- const control = new Int32Array(sharedBuffer, 0, ${HEADER_INTS$1});
1972
- const lengthView = new DataView(sharedBuffer, ${HEADER_INTS$1 * 4}, 4);
1973
- const dataArea = new Uint8Array(sharedBuffer, ${DATA_OFFSET$1});
2398
+ const control = new Int32Array(sharedBuffer, 0, 4);
2399
+ const lengthView = new DataView(sharedBuffer, 4 * 4, 4);
2400
+ const dataArea = new Uint8Array(sharedBuffer, 4 * 4 + 4);
1974
2401
 
1975
2402
  let ds;
1976
2403
  try {
@@ -1985,14 +2412,11 @@ async function main() {
1985
2412
  return;
1986
2413
  }
1987
2414
 
1988
- // Signal ready
1989
2415
  Atomics.store(control, 2, 1);
1990
2416
  Atomics.notify(control, 2);
1991
2417
 
1992
- // Request loop
1993
2418
  while (true) {
1994
2419
  Atomics.wait(control, 0, 0);
1995
-
1996
2420
  const len = lengthView.getUint32(0);
1997
2421
  const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
1998
2422
  Atomics.store(control, 0, 0);
@@ -2014,117 +2438,32 @@ async function main() {
2014
2438
 
2015
2439
  dataArea.set(response, 0);
2016
2440
  lengthView.setUint32(0, response.length);
2017
-
2018
2441
  Atomics.store(control, 1, 1);
2019
2442
  Atomics.notify(control, 1);
2020
2443
  }
2021
2444
  }
2022
2445
  main();
2023
- `;
2024
- let worker$1 = null;
2025
- let controlArray$1 = null;
2026
- let lengthView$1 = null;
2027
- let dataArea$1 = null;
2028
- let initialized$1 = false;
2029
- let available$1 = true;
2030
- let currentCssPath$1 = null;
2031
- const canonCache = /* @__PURE__ */ new Map();
2032
- function ensureService$1(cssPath) {
2033
- if (initialized$1 && currentCssPath$1 === cssPath) return available$1;
2034
- if (initialized$1) {
2035
- cleanup$1();
2036
- initialized$1 = false;
2037
- available$1 = true;
2038
- controlArray$1 = null;
2039
- lengthView$1 = null;
2040
- dataArea$1 = null;
2041
- }
2042
- initialized$1 = true;
2043
- currentCssPath$1 = cssPath;
2044
- try {
2045
- const tailwindNodePath = require.resolve("@tailwindcss/node");
2046
- const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE$1);
2047
- controlArray$1 = new Int32Array(sharedBuffer, 0, HEADER_INTS$1);
2048
- lengthView$1 = new DataView(sharedBuffer, HEADER_INTS$1 * 4, 4);
2049
- dataArea$1 = new Uint8Array(sharedBuffer, DATA_OFFSET$1);
2050
- worker$1 = new node_worker_threads.Worker(WORKER_SCRIPT$1, {
2051
- eval: true,
2052
- workerData: {
2053
- sharedBuffer,
2054
- cssPath,
2055
- tailwindNodePath
2056
- }
2057
- });
2058
- worker$1.unref();
2059
- worker$1.on("error", () => {
2060
- available$1 = false;
2061
- worker$1 = null;
2062
- });
2063
- worker$1.on("exit", () => {
2064
- worker$1 = null;
2065
- });
2066
- if (Atomics.wait(controlArray$1, 2, 0, INIT_TIMEOUT$1) === "timed-out" || controlArray$1[2] === -1) {
2067
- available$1 = false;
2068
- cleanup$1();
2069
- return false;
2070
- }
2071
- return true;
2072
- } catch {
2073
- available$1 = false;
2074
- cleanup$1();
2075
- return false;
2076
- }
2077
- }
2078
- function cleanup$1() {
2079
- if (worker$1) {
2080
- try {
2081
- worker$1.terminate();
2082
- } catch {}
2083
- worker$1 = null;
2084
- }
2085
- }
2446
+ `,
2447
+ serviceName: "canonicalize"
2448
+ });
2086
2449
  /**
2087
- * Round-trip raw worker call for a batch of classes (no caching).
2088
- * Returns the canonicalized class array (same length/order as input),
2089
- * or null if the service is unavailable.
2450
+ * Process-wide cache of canonicalized classes.
2451
+ * Key: `${cssPath}\0${rem}\0${className}` — isolates monorepos (multiple
2452
+ * DSs) and different rem settings. Value: canonicalized class string.
2090
2453
  */
2091
- function callWorker(classes, rem) {
2092
- if (!controlArray$1 || !dataArea$1 || !lengthView$1) return null;
2093
- try {
2094
- const request = Buffer.from(JSON.stringify({
2095
- classes,
2096
- rem
2097
- }), "utf-8");
2098
- if (request.length > BUFFER_SIZE$1 - DATA_OFFSET$1) return null;
2099
- dataArea$1.set(request, 0);
2100
- lengthView$1.setUint32(0, request.length);
2101
- Atomics.store(controlArray$1, 0, 1);
2102
- Atomics.notify(controlArray$1, 0);
2103
- if (Atomics.wait(controlArray$1, 1, 0, REQUEST_TIMEOUT$1) === "timed-out") {
2104
- available$1 = false;
2105
- cleanup$1();
2106
- return null;
2107
- }
2108
- const responseLen = lengthView$1.getUint32(0);
2109
- const responseStr = Buffer.from(dataArea$1.slice(0, responseLen)).toString("utf-8");
2110
- Atomics.store(controlArray$1, 1, 0);
2111
- return JSON.parse(responseStr);
2112
- } catch {
2113
- available$1 = false;
2114
- cleanup$1();
2115
- return null;
2116
- }
2117
- }
2454
+ const canonCache = /* @__PURE__ */ new Map();
2118
2455
  /**
2119
- * Canonicalize classes using the Tailwind CSS design system via worker thread.
2120
- * Returns the canonicalized class array (same length/order as input), or null
2121
- * if the service is unavailable.
2456
+ * Canonicalize classes via the worker thread.
2457
+ *
2458
+ * Throws `SortServiceError` on any worker failure (init timeout, request
2459
+ * timeout, worker crash). Callers should wrap via `safeGetDS` so the
2460
+ * failure surfaces as a single `designSystemUnavailable` diagnostic.
2122
2461
  *
2123
- * Uses a process-wide per-class cache: the worker is invoked only for classes
2462
+ * Returns an array the same length and order as `classes`. Uses a
2463
+ * process-wide per-class cache: the worker is invoked only for classes
2124
2464
  * not already seen with this (cssPath, rem) combination.
2125
2465
  */
2126
2466
  function canonicalizeClassesSync(cssPath, classes, rem) {
2127
- if (!ensureService$1(cssPath)) return null;
2128
2467
  const out = Array.from({ length: classes.length });
2129
2468
  const missingIdx = [];
2130
2469
  const missing = [];
@@ -2140,8 +2479,11 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
2140
2479
  }
2141
2480
  if (missing.length === 0) return out;
2142
2481
  const uniqueMissing = [...new Set(missing)];
2143
- const fresh = callWorker(uniqueMissing, rem);
2144
- if (!fresh || fresh.length !== uniqueMissing.length) return null;
2482
+ const fresh = canonWorker.callSync(cssPath, {
2483
+ classes: uniqueMissing,
2484
+ rem
2485
+ });
2486
+ if (fresh.length !== uniqueMissing.length) throw new SortServiceError(`Canonicalize worker returned ${fresh.length} results for ${uniqueMissing.length} inputs.`, "This is a bug; please open an issue.");
2145
2487
  const freshByClass = /* @__PURE__ */ new Map();
2146
2488
  for (let k = 0; k < uniqueMissing.length; k++) freshByClass.set(uniqueMissing[k], fresh[k]);
2147
2489
  for (let j = 0; j < missing.length; j++) {
@@ -2155,20 +2497,20 @@ function canonicalizeClassesSync(cssPath, classes, rem) {
2155
2497
  //#endregion
2156
2498
  //#region src/rules/enforce-canonical.ts
2157
2499
  /**
2158
- * Preserve the user's ! position after canonicalization.
2159
- * canonicalizeCandidates always normalizes ! to suffix, but
2160
- * enforce-consistent-important-position handles that separately.
2500
+ * Preserve the user's `!` position after canonicalization.
2501
+ *
2502
+ * `canonicalizeCandidates` normalizes `!` to suffix; this restores the
2503
+ * original prefix-or-suffix-or-none position so `enforce-consistent-important-position`
2504
+ * remains the single source of truth for ! placement policy.
2505
+ *
2506
+ * Bracket-aware via `splitUtilityAndVariant` — arbitrary variants like
2507
+ * `[&>svg]:!w-4` round-trip correctly.
2161
2508
  */
2162
2509
  function preserveImportantPosition(original, canonicalized) {
2163
- const origHasPrefix = original.startsWith("!") || /^[a-z0-9[\]*@-]*:!/.test(original);
2164
- const origHasSuffix = original.endsWith("!") && !origHasPrefix;
2165
- if (!origHasPrefix && !origHasSuffix) return canonicalized.replace(/!/g, "");
2166
- const bare = canonicalized.replace(/!/g, "");
2167
- if (origHasPrefix) {
2168
- const variantPrefix = bare.slice(0, bare.length - bare.replace(/^[a-z0-9[\]*@-]*:/g, "").length);
2169
- return variantPrefix + "!" + bare.slice(variantPrefix.length);
2170
- }
2171
- return bare + "!";
2510
+ const { position } = splitImportant(splitUtilityAndVariant(original).utility);
2511
+ const { utility, variant } = splitUtilityAndVariant(canonicalized);
2512
+ const bare = splitImportant(utility).bare;
2513
+ return variant + reattachImportant(bare, position);
2172
2514
  }
2173
2515
  const enforceCanonical = (0, _oxlint_plugins.defineRule)({
2174
2516
  meta: {
@@ -2181,9 +2523,11 @@ const enforceCanonical = (0, _oxlint_plugins.defineRule)({
2181
2523
  additionalProperties: false
2182
2524
  }],
2183
2525
  hasSuggestions: true,
2526
+ defaultOptions: [{}],
2184
2527
  messages: {
2185
2528
  nonCanonical: "\"{{className}}\" can be written as \"{{canonical}}\". Use the canonical form.",
2186
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2529
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
2530
+ ...DS_UNAVAILABLE_MESSAGE
2187
2531
  }
2188
2532
  },
2189
2533
  createOnce(context) {
@@ -2194,7 +2538,8 @@ const enforceCanonical = (0, _oxlint_plugins.defineRule)({
2194
2538
  return _rem;
2195
2539
  }
2196
2540
  function check(locations) {
2197
- const ds = getDS();
2541
+ if (locations.length === 0) return;
2542
+ const ds = safeGetDS(getDS, context, locations[0].node);
2198
2543
  if (!ds) return;
2199
2544
  const { cache, entryPoint } = ds;
2200
2545
  for (const loc of locations) {
@@ -2208,51 +2553,18 @@ const enforceCanonical = (0, _oxlint_plugins.defineRule)({
2208
2553
  arbitrary.push(classes[i]);
2209
2554
  } else canonicals[i] = cache.canonicalize(classes[i]);
2210
2555
  if (arbitrary.length > 0) {
2211
- const dynamic = canonicalizeClassesSync(entryPoint, arbitrary, getRem());
2212
- if (dynamic) for (let k = 0; k < arbitrary.length; k++) canonicals[arbitraryIdx[k]] = preserveImportantPosition(arbitrary[k], dynamic[k]);
2213
- else for (let k = 0; k < arbitrary.length; k++) canonicals[arbitraryIdx[k]] = cache.canonicalize(arbitrary[k]);
2214
- }
2215
- let firstNonCanonical = true;
2216
- for (let i = 0; i < classes.length; i++) {
2217
- const cls = classes[i];
2218
- const canonical = canonicals[i];
2219
- if (canonical === cls) continue;
2220
- if (firstNonCanonical) {
2221
- firstNonCanonical = false;
2222
- const fixedValue = rebuildClassString(split, canonicals);
2223
- context.report({
2224
- node: loc.node,
2225
- messageId: "nonCanonical",
2226
- data: {
2227
- className: cls,
2228
- canonical
2229
- },
2230
- fix(fixer) {
2231
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2232
- }
2233
- });
2234
- } else {
2235
- const fixedValue = rebuildClassString(split, canonicals);
2236
- context.report({
2237
- node: loc.node,
2238
- messageId: "nonCanonical",
2239
- data: {
2240
- className: cls,
2241
- canonical
2242
- },
2243
- suggest: [{
2244
- messageId: "suggestReplace",
2245
- data: {
2246
- className: cls,
2247
- replacement: canonical
2248
- },
2249
- fix(fixer) {
2250
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2251
- }
2252
- }]
2253
- });
2254
- }
2556
+ const rem = getRem();
2557
+ const dynamic = safeGetDS(() => canonicalizeClassesSync(entryPoint, arbitrary, rem), context, loc.node);
2558
+ if (!dynamic) return;
2559
+ for (let k = 0; k < arbitrary.length; k++) canonicals[arbitraryIdx[k]] = preserveImportantPosition(arbitrary[k], dynamic[k]);
2255
2560
  }
2561
+ reportClassReplacements(context, loc, split, classes, classes.flatMap((cls, i) => canonicals[i] === cls ? [] : [{
2562
+ cls,
2563
+ replacement: canonicals[i]
2564
+ }]), {
2565
+ messageId: "nonCanonical",
2566
+ replacementKey: "canonical"
2567
+ });
2256
2568
  }
2257
2569
  }
2258
2570
  return createExtractorVisitors(context, check);
@@ -2261,31 +2573,21 @@ const enforceCanonical = (0, _oxlint_plugins.defineRule)({
2261
2573
  //#endregion
2262
2574
  //#region src/design-system/sort-service.ts
2263
2575
  /**
2264
- * Persistent sort service using worker_threads + SharedArrayBuffer.
2576
+ * Persistent sort service backed by `DesignSystemWorker`.
2265
2577
  *
2266
- * The problem: `ds.getClassOrder()` is the only way to get the exact official
2267
- * Tailwind CSS sort order (matching oxfmt/prettier-plugin-tailwindcss), but the
2268
- * design system is async to load and the oxlint plugin API is sync.
2269
- *
2270
- * The solution: spawn a Worker thread that loads the DS once, then accepts sort
2271
- * requests via SharedArrayBuffer + Atomics. The parent uses `Atomics.wait()`
2272
- * (with timeout) for synchronous blocking without risk of infinite hangs.
2273
- *
2274
- * Falls back gracefully if the worker fails to initialize within the timeout.
2578
+ * Calls `ds.getClassOrder(classes)` and returns the class names in the
2579
+ * Tailwind-canonical order. The shared protocol (SharedArrayBuffer,
2580
+ * Atomics.wait, fail-loud, sticky lastError) lives in `./ds-worker.ts`.
2275
2581
  */
2276
- const BUFFER_SIZE = 4 * 1024 * 1024;
2277
- const HEADER_INTS = 4;
2278
- const DATA_OFFSET = HEADER_INTS * 4 + 4;
2279
- const INIT_TIMEOUT = 3e4;
2280
- const REQUEST_TIMEOUT = 1e4;
2281
- const WORKER_SCRIPT = `
2582
+ const sortWorker = new DesignSystemWorker({
2583
+ workerScript: `
2282
2584
  const { workerData } = require('worker_threads');
2283
2585
 
2284
2586
  async function main() {
2285
2587
  const { sharedBuffer, cssPath } = workerData;
2286
- const control = new Int32Array(sharedBuffer, 0, ${HEADER_INTS});
2287
- const lengthView = new DataView(sharedBuffer, ${HEADER_INTS * 4}, 4);
2288
- const dataArea = new Uint8Array(sharedBuffer, ${DATA_OFFSET});
2588
+ const control = new Int32Array(sharedBuffer, 0, 4);
2589
+ const lengthView = new DataView(sharedBuffer, 4 * 4, 4);
2590
+ const dataArea = new Uint8Array(sharedBuffer, 4 * 4 + 4);
2289
2591
 
2290
2592
  let ds;
2291
2593
  try {
@@ -2300,17 +2602,14 @@ async function main() {
2300
2602
  return;
2301
2603
  }
2302
2604
 
2303
- // Signal ready
2304
2605
  Atomics.store(control, 2, 1);
2305
2606
  Atomics.notify(control, 2);
2306
2607
 
2307
- // Request loop
2308
2608
  while (true) {
2309
- Atomics.wait(control, 0, 0); // wait for requestSignal !== 0
2310
-
2609
+ Atomics.wait(control, 0, 0);
2311
2610
  const len = lengthView.getUint32(0);
2312
2611
  const requestStr = Buffer.from(dataArea.slice(0, len)).toString('utf-8');
2313
- Atomics.store(control, 0, 0); // consume request
2612
+ Atomics.store(control, 0, 0);
2314
2613
 
2315
2614
  let response;
2316
2615
  try {
@@ -2331,102 +2630,24 @@ async function main() {
2331
2630
 
2332
2631
  dataArea.set(response, 0);
2333
2632
  lengthView.setUint32(0, response.length);
2334
-
2335
- Atomics.store(control, 1, 1); // signal response
2633
+ Atomics.store(control, 1, 1);
2336
2634
  Atomics.notify(control, 1);
2337
2635
  }
2338
2636
  }
2339
2637
  main();
2340
- `;
2341
- let worker = null;
2342
- let controlArray = null;
2343
- let lengthView = null;
2344
- let dataArea = null;
2345
- let initialized = false;
2346
- let available = true;
2347
- let currentCssPath = null;
2348
- function ensureService(cssPath) {
2349
- if (initialized && currentCssPath === cssPath) return available;
2350
- if (initialized) {
2351
- cleanup();
2352
- initialized = false;
2353
- available = true;
2354
- controlArray = null;
2355
- lengthView = null;
2356
- dataArea = null;
2357
- }
2358
- initialized = true;
2359
- currentCssPath = cssPath;
2360
- try {
2361
- const tailwindNodePath = require.resolve("@tailwindcss/node");
2362
- const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);
2363
- controlArray = new Int32Array(sharedBuffer, 0, HEADER_INTS);
2364
- lengthView = new DataView(sharedBuffer, HEADER_INTS * 4, 4);
2365
- dataArea = new Uint8Array(sharedBuffer, DATA_OFFSET);
2366
- worker = new node_worker_threads.Worker(WORKER_SCRIPT, {
2367
- eval: true,
2368
- workerData: {
2369
- sharedBuffer,
2370
- cssPath,
2371
- tailwindNodePath
2372
- }
2373
- });
2374
- worker.unref();
2375
- worker.on("error", () => {
2376
- available = false;
2377
- worker = null;
2378
- });
2379
- worker.on("exit", () => {
2380
- worker = null;
2381
- });
2382
- if (Atomics.wait(controlArray, 2, 0, INIT_TIMEOUT) === "timed-out" || controlArray[2] === -1) {
2383
- available = false;
2384
- cleanup();
2385
- return false;
2386
- }
2387
- return true;
2388
- } catch {
2389
- available = false;
2390
- cleanup();
2391
- return false;
2392
- }
2393
- }
2394
- function cleanup() {
2395
- if (worker) {
2396
- try {
2397
- worker.terminate();
2398
- } catch {}
2399
- worker = null;
2400
- }
2401
- }
2638
+ `,
2639
+ serviceName: "sort"
2640
+ });
2402
2641
  /**
2403
- * Sort classes using the official Tailwind CSS sort order via worker thread.
2404
- * Returns the sorted class array, or null if the service is unavailable.
2642
+ * Sort classes via worker thread using the official Tailwind class order.
2643
+ *
2644
+ * Throws `SortServiceError` on any failure (worker init timeout, request
2645
+ * timeout, worker crash, payload too large). Callers should wrap via
2646
+ * `safeGetDS` so the failure surfaces as a single `designSystemUnavailable`
2647
+ * diagnostic instead of crashing the lint.
2405
2648
  */
2406
2649
  function sortClassesSync(cssPath, classes) {
2407
- if (!ensureService(cssPath)) return null;
2408
- if (!controlArray || !dataArea || !lengthView) return null;
2409
- try {
2410
- const request = Buffer.from(JSON.stringify(classes), "utf-8");
2411
- if (request.length > BUFFER_SIZE - DATA_OFFSET) return null;
2412
- dataArea.set(request, 0);
2413
- lengthView.setUint32(0, request.length);
2414
- Atomics.store(controlArray, 0, 1);
2415
- Atomics.notify(controlArray, 0);
2416
- if (Atomics.wait(controlArray, 1, 0, REQUEST_TIMEOUT) === "timed-out") {
2417
- available = false;
2418
- cleanup();
2419
- return null;
2420
- }
2421
- const responseLen = lengthView.getUint32(0);
2422
- const responseStr = Buffer.from(dataArea.slice(0, responseLen)).toString("utf-8");
2423
- Atomics.store(controlArray, 1, 0);
2424
- return JSON.parse(responseStr);
2425
- } catch {
2426
- available = false;
2427
- cleanup();
2428
- return null;
2429
- }
2650
+ return sortWorker.callSync(cssPath, classes);
2430
2651
  }
2431
2652
  //#endregion
2432
2653
  //#region src/rules/enforce-sort-order.ts
@@ -2446,31 +2667,23 @@ const enforceSortOrder = (0, _oxlint_plugins.defineRule)({
2446
2667
  },
2447
2668
  additionalProperties: false
2448
2669
  }],
2449
- messages: { unsorted: "Tailwind classes are not in the recommended order." }
2670
+ defaultOptions: [{ mode: "default" }],
2671
+ messages: {
2672
+ unsorted: "Tailwind classes are not in the recommended order.",
2673
+ ...DS_UNAVAILABLE_MESSAGE
2674
+ }
2450
2675
  },
2451
2676
  createOnce(context) {
2452
2677
  const getDS = createLazyLoader(context);
2453
- let _mode = null;
2454
- function getMode() {
2455
- if (_mode === null) _mode = safeOptions(context)?.mode ?? "default";
2456
- return _mode;
2457
- }
2678
+ const getMode = createLazyOptions(context, (o) => o?.mode ?? "default");
2458
2679
  function check(locations) {
2459
- const ds = getDS();
2680
+ if (locations.length === 0) return;
2681
+ const ds = safeGetDS(getDS, context, locations[0].node);
2460
2682
  if (!ds) return;
2461
2683
  const { cache, entryPoint } = ds;
2462
2684
  const mode = getMode();
2463
2685
  function sortDefault(classes) {
2464
- const dynamic = sortClassesSync(entryPoint, classes);
2465
- if (dynamic) return dynamic;
2466
- return [...cache.getClassOrder(classes)].sort((a, b) => {
2467
- if (a[1] === null && b[1] === null) return 0;
2468
- if (a[1] === null) return -1;
2469
- if (b[1] === null) return 1;
2470
- if (a[1] < b[1]) return -1;
2471
- if (a[1] > b[1]) return 1;
2472
- return 0;
2473
- }).map(([name]) => name);
2686
+ return sortClassesSync(entryPoint, classes);
2474
2687
  }
2475
2688
  function sortStrict(classes) {
2476
2689
  const groups = /* @__PURE__ */ new Map();
@@ -2514,7 +2727,8 @@ const enforceSortOrder = (0, _oxlint_plugins.defineRule)({
2514
2727
  const split = splitClassesWithSeparators(loc.value);
2515
2728
  const classes = split.classes;
2516
2729
  if (classes.length < 2) continue;
2517
- const sortedNames = mode === "strict" ? sortStrict(classes) : sortDefault(classes);
2730
+ const sortedNames = mode === "strict" ? sortStrict(classes) : safeGetDS(() => sortDefault(classes), context, loc.node);
2731
+ if (!sortedNames) return;
2518
2732
  if (classes.every((name, i) => name === sortedNames[i])) continue;
2519
2733
  context.report({
2520
2734
  node: loc.node,
@@ -2612,8 +2826,7 @@ const enforceShorthand = (0, _oxlint_plugins.defineRule)({
2612
2826
  const classSet = new Set(classes);
2613
2827
  const values = /* @__PURE__ */ new Set();
2614
2828
  for (const cls of classes) {
2615
- const bare = cls.startsWith("!") ? cls.slice(1) : cls.endsWith("!") ? cls.slice(0, -1) : cls;
2616
- const match = VALUE_RE.exec(bare);
2829
+ const match = VALUE_RE.exec(splitImportant(cls).bare);
2617
2830
  if (match) values.add(match[1]);
2618
2831
  }
2619
2832
  for (const value of values) {
@@ -2647,180 +2860,234 @@ const enforceShorthand = (0, _oxlint_plugins.defineRule)({
2647
2860
  }
2648
2861
  });
2649
2862
  //#endregion
2863
+ //#region src/utils/allowlist.ts
2864
+ /**
2865
+ * Shared regex-allowlist helpers used by rules that accept an `allowlist`
2866
+ * option of regex source strings (currently enforce-logical / enforce-physical).
2867
+ *
2868
+ * Invalid regex sources are skipped rather than thrown so a typo in one
2869
+ * pattern doesn't blow up the entire lint run.
2870
+ */
2871
+ function compileRegexList(patterns) {
2872
+ if (!patterns || patterns.length === 0) return [];
2873
+ const compiled = [];
2874
+ for (const p of patterns) try {
2875
+ compiled.push(new RegExp(p));
2876
+ } catch {}
2877
+ return compiled;
2878
+ }
2879
+ function matchesAny(value, list) {
2880
+ return list.some((re) => re.test(value));
2881
+ }
2882
+ //#endregion
2650
2883
  //#region src/rules/enforce-logical.ts
2651
- const PHYSICAL_TO_LOGICAL = {
2652
- ml: "ms",
2653
- mr: "me",
2654
- pl: "ps",
2655
- pr: "pe",
2656
- left: "start",
2657
- right: "end",
2658
- "border-l": "border-s",
2659
- "border-r": "border-e",
2660
- "rounded-l": "rounded-s",
2661
- "rounded-r": "rounded-e",
2662
- "rounded-tl": "rounded-ss",
2663
- "rounded-tr": "rounded-se",
2664
- "rounded-bl": "rounded-es",
2665
- "rounded-br": "rounded-ee",
2666
- "scroll-ml": "scroll-ms",
2667
- "scroll-mr": "scroll-me",
2668
- "scroll-pl": "scroll-ps",
2669
- "scroll-pr": "scroll-pe"
2670
- };
2671
- const enforceLogical = (0, _oxlint_plugins.defineRule)({
2672
- meta: {
2673
- type: "suggestion",
2674
- docs: { description: "Enforce logical (RTL-friendly) Tailwind CSS properties instead of physical ones" },
2675
- fixable: "code",
2676
- schema: [],
2677
- hasSuggestions: true,
2678
- messages: {
2679
- useLogical: "\"{{className}}\" uses a physical property. Use \"{{replacement}}\" for LTR/RTL support.",
2680
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2884
+ const LOGICAL_PHYSICAL_SCHEMA = {
2885
+ type: "object",
2886
+ properties: {
2887
+ allowlist: {
2888
+ type: "array",
2889
+ items: { type: "string" }
2890
+ },
2891
+ direction: {
2892
+ type: "string",
2893
+ enum: [
2894
+ "inline",
2895
+ "block",
2896
+ "both"
2897
+ ]
2681
2898
  }
2682
2899
  },
2683
- createOnce(context) {
2684
- function convertClass(cls) {
2685
- const { utility, variant } = splitUtilityAndVariant(cls);
2686
- const hasImportantPrefix = utility.startsWith("!");
2687
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
2688
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
2689
- for (const [physical, logical] of Object.entries(PHYSICAL_TO_LOGICAL)) if (bareUtility === physical || bareUtility.startsWith(`${physical}-`)) {
2690
- const suffix = bareUtility.slice(physical.length);
2691
- return `${variant}${hasImportantPrefix ? "!" : ""}${logical}${suffix}${hasImportantSuffix ? "!" : ""}`;
2692
- }
2693
- return null;
2900
+ additionalProperties: false
2901
+ };
2902
+ const PHYSICAL_TO_LOGICAL_MAPPINGS = [
2903
+ {
2904
+ from: "ml",
2905
+ to: "ms",
2906
+ axis: "inline"
2907
+ },
2908
+ {
2909
+ from: "mr",
2910
+ to: "me",
2911
+ axis: "inline"
2912
+ },
2913
+ {
2914
+ from: "pl",
2915
+ to: "ps",
2916
+ axis: "inline"
2917
+ },
2918
+ {
2919
+ from: "pr",
2920
+ to: "pe",
2921
+ axis: "inline"
2922
+ },
2923
+ {
2924
+ from: "left",
2925
+ to: "start",
2926
+ axis: "inline"
2927
+ },
2928
+ {
2929
+ from: "right",
2930
+ to: "end",
2931
+ axis: "inline"
2932
+ },
2933
+ {
2934
+ from: "border-l",
2935
+ to: "border-s",
2936
+ axis: "inline"
2937
+ },
2938
+ {
2939
+ from: "border-r",
2940
+ to: "border-e",
2941
+ axis: "inline"
2942
+ },
2943
+ {
2944
+ from: "rounded-l",
2945
+ to: "rounded-s",
2946
+ axis: "inline"
2947
+ },
2948
+ {
2949
+ from: "rounded-r",
2950
+ to: "rounded-e",
2951
+ axis: "inline"
2952
+ },
2953
+ {
2954
+ from: "rounded-tl",
2955
+ to: "rounded-ss",
2956
+ axis: "inline"
2957
+ },
2958
+ {
2959
+ from: "rounded-tr",
2960
+ to: "rounded-se",
2961
+ axis: "inline"
2962
+ },
2963
+ {
2964
+ from: "rounded-bl",
2965
+ to: "rounded-es",
2966
+ axis: "inline"
2967
+ },
2968
+ {
2969
+ from: "rounded-br",
2970
+ to: "rounded-ee",
2971
+ axis: "inline"
2972
+ },
2973
+ {
2974
+ from: "scroll-ml",
2975
+ to: "scroll-ms",
2976
+ axis: "inline"
2977
+ },
2978
+ {
2979
+ from: "scroll-mr",
2980
+ to: "scroll-me",
2981
+ axis: "inline"
2982
+ },
2983
+ {
2984
+ from: "scroll-pl",
2985
+ to: "scroll-ps",
2986
+ axis: "inline"
2987
+ },
2988
+ {
2989
+ from: "scroll-pr",
2990
+ to: "scroll-pe",
2991
+ axis: "inline"
2992
+ }
2993
+ ];
2994
+ /** Invert a directional table. enforce-physical consumes this. */
2995
+ function invertAxisMappings(mappings) {
2996
+ return mappings.map((m) => ({
2997
+ from: m.to,
2998
+ to: m.from,
2999
+ axis: m.axis
3000
+ }));
3001
+ }
3002
+ Object.fromEntries(PHYSICAL_TO_LOGICAL_MAPPINGS.map((m) => [m.from, m.to]));
3003
+ /**
3004
+ * Build the `check` callback for a directional-rewrite rule. Both
3005
+ * enforce-logical and enforce-physical instantiate this with their own
3006
+ * mapping table and messageId; the rule's `createOnce` wires it through
3007
+ * `createExtractorVisitors`.
3008
+ *
3009
+ * Owns: option compilation (allowlist + direction), per-class conversion
3010
+ * (linear scan of the mapping table respecting `!`-prefix/suffix), and
3011
+ * the `reportClassReplacements` dispatch.
3012
+ */
3013
+ function createDirectionalMapper(context, opts) {
3014
+ const getState = createLazyOptions(context, (o) => ({
3015
+ allowlist: compileRegexList(o?.allowlist),
3016
+ direction: o?.direction ?? "both"
3017
+ }));
3018
+ function convertClass(cls) {
3019
+ const { allowlist, direction } = getState();
3020
+ if (matchesAny(cls, allowlist)) return null;
3021
+ const { utility, variant } = splitUtilityAndVariant(cls);
3022
+ const { bare: bareUtility, position } = splitImportant(utility);
3023
+ for (const { from, to, axis } of opts.mappings) {
3024
+ if (direction !== "both" && direction !== axis) continue;
3025
+ if (bareUtility === from || bareUtility.startsWith(`${from}-`)) return `${variant}${reattachImportant(to + bareUtility.slice(from.length), position)}`;
2694
3026
  }
2695
- function check(locations) {
2696
- for (const loc of locations) {
2697
- const split = splitClassesWithSeparators(loc.value);
2698
- const classes = split.classes;
2699
- const offending = [];
2700
- for (const cls of classes) {
2701
- const converted = convertClass(cls);
2702
- if (converted) offending.push({
2703
- cls,
2704
- replacement: converted
2705
- });
2706
- }
2707
- if (offending.length === 0) continue;
2708
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
2709
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
2710
- for (let i = 0; i < offending.length; i++) {
2711
- const { cls, replacement } = offending[i];
2712
- if (i === 0) context.report({
2713
- node: loc.node,
2714
- messageId: "useLogical",
2715
- data: {
2716
- className: cls,
2717
- replacement
2718
- },
2719
- fix(fixer) {
2720
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2721
- }
2722
- });
2723
- else context.report({
2724
- node: loc.node,
2725
- messageId: "useLogical",
2726
- data: {
2727
- className: cls,
2728
- replacement
2729
- },
2730
- suggest: [{
2731
- messageId: "suggestReplace",
2732
- data: {
2733
- className: cls,
2734
- replacement
2735
- },
2736
- fix(fixer) {
2737
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2738
- }
2739
- }]
2740
- });
2741
- }
2742
- }
3027
+ return null;
3028
+ }
3029
+ function check(locations) {
3030
+ for (const loc of locations) {
3031
+ const split = splitClassesWithSeparators(loc.value);
3032
+ const offending = split.classes.flatMap((cls) => {
3033
+ const converted = convertClass(cls);
3034
+ return converted ? [{
3035
+ cls,
3036
+ replacement: converted
3037
+ }] : [];
3038
+ });
3039
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: opts.messageId });
2743
3040
  }
2744
- return createExtractorVisitors(context, check);
2745
3041
  }
2746
- });
2747
- //#endregion
2748
- //#region src/rules/enforce-physical.ts
2749
- const LOGICAL_TO_PHYSICAL = {};
2750
- for (const [physical, logical] of Object.entries(PHYSICAL_TO_LOGICAL)) LOGICAL_TO_PHYSICAL[logical] = physical;
2751
- const enforcePhysical = (0, _oxlint_plugins.defineRule)({
3042
+ return { check };
3043
+ }
3044
+ const enforceLogical = (0, _oxlint_plugins.defineRule)({
2752
3045
  meta: {
2753
3046
  type: "suggestion",
2754
- docs: { description: "Enforce physical Tailwind CSS properties instead of logical ones for consistency in LTR-only projects" },
2755
- fixable: "code",
2756
- schema: [],
2757
- hasSuggestions: true,
2758
- messages: {
2759
- usePhysical: "\"{{className}}\" uses a logical property. Use \"{{replacement}}\" for consistency.",
2760
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2761
- }
2762
- },
2763
- createOnce(context) {
2764
- function convertClass(cls) {
2765
- const { utility, variant } = splitUtilityAndVariant(cls);
2766
- const hasImportantPrefix = utility.startsWith("!");
2767
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
2768
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
2769
- for (const [logical, physical] of Object.entries(LOGICAL_TO_PHYSICAL)) if (bareUtility === logical || bareUtility.startsWith(`${logical}-`)) {
2770
- const suffix = bareUtility.slice(logical.length);
2771
- return `${variant}${hasImportantPrefix ? "!" : ""}${physical}${suffix}${hasImportantSuffix ? "!" : ""}`;
2772
- }
2773
- return null;
2774
- }
2775
- function check(locations) {
2776
- for (const loc of locations) {
2777
- const split = splitClassesWithSeparators(loc.value);
2778
- const classes = split.classes;
2779
- const offending = [];
2780
- for (const cls of classes) {
2781
- const converted = convertClass(cls);
2782
- if (converted) offending.push({
2783
- cls,
2784
- replacement: converted
2785
- });
2786
- }
2787
- if (offending.length === 0) continue;
2788
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
2789
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
2790
- for (let i = 0; i < offending.length; i++) {
2791
- const { cls, replacement } = offending[i];
2792
- if (i === 0) context.report({
2793
- node: loc.node,
2794
- messageId: "usePhysical",
2795
- data: {
2796
- className: cls,
2797
- replacement
2798
- },
2799
- fix(fixer) {
2800
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2801
- }
2802
- });
2803
- else context.report({
2804
- node: loc.node,
2805
- messageId: "usePhysical",
2806
- data: {
2807
- className: cls,
2808
- replacement
2809
- },
2810
- suggest: [{
2811
- messageId: "suggestReplace",
2812
- data: {
2813
- className: cls,
2814
- replacement
2815
- },
2816
- fix(fixer) {
2817
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
2818
- }
2819
- }]
2820
- });
2821
- }
2822
- }
3047
+ docs: { description: "Enforce logical (RTL-friendly) Tailwind CSS properties instead of physical ones" },
3048
+ fixable: "code",
3049
+ schema: [LOGICAL_PHYSICAL_SCHEMA],
3050
+ hasSuggestions: true,
3051
+ defaultOptions: [{
3052
+ allowlist: [],
3053
+ direction: "both"
3054
+ }],
3055
+ messages: {
3056
+ useLogical: "\"{{className}}\" uses a physical property. Use \"{{replacement}}\" for LTR/RTL support.",
3057
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
3058
+ }
3059
+ },
3060
+ createOnce(context) {
3061
+ const { check } = createDirectionalMapper(context, {
3062
+ mappings: PHYSICAL_TO_LOGICAL_MAPPINGS,
3063
+ messageId: "useLogical"
3064
+ });
3065
+ return createExtractorVisitors(context, check);
3066
+ }
3067
+ });
3068
+ //#endregion
3069
+ //#region src/rules/enforce-physical.ts
3070
+ const enforcePhysical = (0, _oxlint_plugins.defineRule)({
3071
+ meta: {
3072
+ type: "suggestion",
3073
+ docs: { description: "Enforce physical Tailwind CSS properties instead of logical ones for consistency in LTR-only projects" },
3074
+ fixable: "code",
3075
+ schema: [LOGICAL_PHYSICAL_SCHEMA],
3076
+ hasSuggestions: true,
3077
+ defaultOptions: [{
3078
+ allowlist: [],
3079
+ direction: "both"
3080
+ }],
3081
+ messages: {
3082
+ usePhysical: "\"{{className}}\" uses a logical property. Use \"{{replacement}}\" for consistency.",
3083
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
2823
3084
  }
3085
+ },
3086
+ createOnce(context) {
3087
+ const { check } = createDirectionalMapper(context, {
3088
+ mappings: invertAxisMappings(PHYSICAL_TO_LOGICAL_MAPPINGS),
3089
+ messageId: "usePhysical"
3090
+ });
2824
3091
  return createExtractorVisitors(context, check);
2825
3092
  }
2826
3093
  });
@@ -2840,11 +3107,7 @@ const maxClassCount = (0, _oxlint_plugins.defineRule)({
2840
3107
  messages: { tooMany: "Too many Tailwind classes ({{count}}). Maximum allowed is {{max}}. Consider extracting into a component or utility." }
2841
3108
  },
2842
3109
  createOnce(context) {
2843
- let _max = null;
2844
- function getMax() {
2845
- if (_max === null) _max = safeOptions(context)?.max ?? DEFAULT_MAX;
2846
- return _max;
2847
- }
3110
+ const getMax = createLazyOptions(context, (o) => o?.max ?? DEFAULT_MAX);
2848
3111
  function check(locations) {
2849
3112
  const max = getMax();
2850
3113
  for (const loc of locations) {
@@ -2890,26 +3153,23 @@ const noRestrictedClasses = (0, _oxlint_plugins.defineRule)({
2890
3153
  },
2891
3154
  additionalProperties: false
2892
3155
  }],
3156
+ defaultOptions: [{
3157
+ classes: [],
3158
+ patterns: []
3159
+ }],
2893
3160
  messages: {
2894
3161
  restricted: "\"{{className}}\" is restricted.",
2895
3162
  restrictedWithMessage: "\"{{className}}\" is restricted: {{message}}"
2896
3163
  }
2897
3164
  },
2898
3165
  createOnce(context) {
2899
- let _config = null;
2900
- function getConfig() {
2901
- if (_config === null) {
2902
- const options = safeOptions(context);
2903
- _config = {
2904
- restrictedClasses: new Set(options?.classes ?? []),
2905
- patterns: (options?.patterns ?? []).map((p) => ({
2906
- regex: new RegExp(p.pattern),
2907
- message: p.message
2908
- }))
2909
- };
2910
- }
2911
- return _config;
2912
- }
3166
+ const getConfig = createLazyOptions(context, (o) => ({
3167
+ restrictedClasses: new Set(o?.classes ?? []),
3168
+ patterns: (o?.patterns ?? []).map((p) => ({
3169
+ regex: new RegExp(p.pattern),
3170
+ message: p.message
3171
+ }))
3172
+ }));
2913
3173
  function check(locations) {
2914
3174
  const { restrictedClasses, patterns } = getConfig();
2915
3175
  if (restrictedClasses.size === 0 && patterns.length === 0) return;
@@ -2960,14 +3220,11 @@ const noArbitraryValue = (0, _oxlint_plugins.defineRule)({
2960
3220
  } },
2961
3221
  additionalProperties: false
2962
3222
  }],
3223
+ defaultOptions: [{ allow: [] }],
2963
3224
  messages: { noArbitrary: "\"{{className}}\" uses an arbitrary value. Use a design token or extend your theme instead." }
2964
3225
  },
2965
3226
  createOnce(context) {
2966
- let _allowPrefixes = null;
2967
- function getAllowPrefixes() {
2968
- if (_allowPrefixes === null) _allowPrefixes = safeOptions(context)?.allow ?? [];
2969
- return _allowPrefixes;
2970
- }
3227
+ const getAllowPrefixes = createLazyOptions(context, (o) => o?.allow ?? []);
2971
3228
  function isAllowed(utility) {
2972
3229
  return getAllowPrefixes().some((prefix) => utility.startsWith(prefix));
2973
3230
  }
@@ -2976,9 +3233,7 @@ const noArbitraryValue = (0, _oxlint_plugins.defineRule)({
2976
3233
  const classes = splitClasses(loc.value);
2977
3234
  for (const cls of classes) {
2978
3235
  if (!hasArbitraryValue(cls)) continue;
2979
- let utility = extractUtility(cls);
2980
- if (utility.startsWith("!")) utility = utility.slice(1);
2981
- else if (utility.endsWith("!")) utility = utility.slice(0, -1);
3236
+ const utility = splitImportant(extractUtility(cls)).bare;
2982
3237
  if (isAllowed(utility)) continue;
2983
3238
  context.report({
2984
3239
  node: loc.node,
@@ -3015,11 +3270,7 @@ const enforceConsistentImportantPosition = (0, _oxlint_plugins.defineRule)({
3015
3270
  }
3016
3271
  },
3017
3272
  createOnce(context) {
3018
- let _position = null;
3019
- function getPosition() {
3020
- if (_position === null) _position = safeOptions(context)?.position ?? "suffix";
3021
- return _position;
3022
- }
3273
+ const getPosition = createLazyOptions(context, (o) => o?.position ?? "suffix");
3023
3274
  function fixUtility(utility, variantPfx) {
3024
3275
  const position = getPosition();
3025
3276
  if (position === "prefix" && utility.endsWith("!") && !utility.startsWith("!")) return `${variantPfx}!${utility.slice(0, -1)}`;
@@ -3027,54 +3278,18 @@ const enforceConsistentImportantPosition = (0, _oxlint_plugins.defineRule)({
3027
3278
  return null;
3028
3279
  }
3029
3280
  function check(locations) {
3030
- const position = getPosition();
3281
+ const messageId = getPosition() === "prefix" ? "usePrefix" : "useSuffix";
3031
3282
  for (const loc of locations) {
3032
3283
  const split = splitClassesWithSeparators(loc.value);
3033
- const classes = split.classes;
3034
- const offending = [];
3035
- for (const cls of classes) {
3284
+ const offending = split.classes.flatMap((cls) => {
3036
3285
  const { utility, variant } = splitUtilityAndVariant(cls);
3037
3286
  const fixed = fixUtility(utility, variant);
3038
- if (fixed) offending.push({
3287
+ return fixed ? [{
3039
3288
  cls,
3040
3289
  replacement: fixed
3041
- });
3042
- }
3043
- if (offending.length === 0) continue;
3044
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
3045
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
3046
- for (let i = 0; i < offending.length; i++) {
3047
- const { cls, replacement } = offending[i];
3048
- if (i === 0) context.report({
3049
- node: loc.node,
3050
- messageId: position === "prefix" ? "usePrefix" : "useSuffix",
3051
- data: {
3052
- className: cls,
3053
- replacement
3054
- },
3055
- fix(fixer) {
3056
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3057
- }
3058
- });
3059
- else context.report({
3060
- node: loc.node,
3061
- messageId: position === "prefix" ? "usePrefix" : "useSuffix",
3062
- data: {
3063
- className: cls,
3064
- replacement
3065
- },
3066
- suggest: [{
3067
- messageId: "suggestReplace",
3068
- data: {
3069
- className: cls,
3070
- replacement
3071
- },
3072
- fix(fixer) {
3073
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3074
- }
3075
- }]
3076
- });
3077
- }
3290
+ }] : [];
3291
+ });
3292
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId });
3078
3293
  }
3079
3294
  }
3080
3295
  return createExtractorVisitors(context, check);
@@ -3117,50 +3332,14 @@ const enforceNegativeArbitraryValues = (0, _oxlint_plugins.defineRule)({
3117
3332
  function check(locations) {
3118
3333
  for (const loc of locations) {
3119
3334
  const split = splitClassesWithSeparators(loc.value);
3120
- const classes = split.classes;
3121
- const offending = [];
3122
- for (const cls of classes) {
3335
+ const offending = split.classes.flatMap((cls) => {
3123
3336
  const fixed = fixClass(cls);
3124
- if (fixed) offending.push({
3337
+ return fixed ? [{
3125
3338
  cls,
3126
3339
  replacement: fixed
3127
- });
3128
- }
3129
- if (offending.length === 0) continue;
3130
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
3131
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
3132
- for (let i = 0; i < offending.length; i++) {
3133
- const { cls, replacement } = offending[i];
3134
- if (i === 0) context.report({
3135
- node: loc.node,
3136
- messageId: "moveNegative",
3137
- data: {
3138
- className: cls,
3139
- replacement
3140
- },
3141
- fix(fixer) {
3142
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3143
- }
3144
- });
3145
- else context.report({
3146
- node: loc.node,
3147
- messageId: "moveNegative",
3148
- data: {
3149
- className: cls,
3150
- replacement
3151
- },
3152
- suggest: [{
3153
- messageId: "suggestReplace",
3154
- data: {
3155
- className: cls,
3156
- replacement
3157
- },
3158
- fix(fixer) {
3159
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3160
- }
3161
- }]
3162
- });
3163
- }
3340
+ }] : [];
3341
+ });
3342
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "moveNegative" });
3164
3343
  }
3165
3344
  }
3166
3345
  return createExtractorVisitors(context, check);
@@ -3172,22 +3351,18 @@ const EXPLICIT_VAR_RE = /^([a-z][a-z0-9-]*(?:-[a-z0-9]+)*)-\[var\((--[a-zA-Z0-9-
3172
3351
  const SHORTHAND_VAR_RE = /^([a-z][a-z0-9-]*(?:-[a-z0-9]+)*)-\((--[a-zA-Z0-9-]+)\)$/;
3173
3352
  function convertClass(cls, syntax) {
3174
3353
  const { utility, variant } = splitUtilityAndVariant(cls);
3175
- const hasImportantPrefix = utility.startsWith("!");
3176
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
3177
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
3178
- const importantStart = hasImportantPrefix ? "!" : "";
3179
- const importantEnd = hasImportantSuffix ? "!" : "";
3354
+ const { bare: bareUtility, position } = splitImportant(utility);
3180
3355
  if (syntax === "shorthand") {
3181
3356
  const match = EXPLICIT_VAR_RE.exec(bareUtility);
3182
3357
  if (match) {
3183
3358
  const [, prefix, varName] = match;
3184
- return `${variant}${importantStart}${prefix}-(${varName})${importantEnd}`;
3359
+ return `${variant}${reattachImportant(`${prefix}-(${varName})`, position)}`;
3185
3360
  }
3186
3361
  } else {
3187
3362
  const match = SHORTHAND_VAR_RE.exec(bareUtility);
3188
3363
  if (match) {
3189
3364
  const [, prefix, varName] = match;
3190
- return `${variant}${importantStart}${prefix}-[var(${varName})]${importantEnd}`;
3365
+ return `${variant}${reattachImportant(`${prefix}-[var(${varName})]`, position)}`;
3191
3366
  }
3192
3367
  }
3193
3368
  return null;
@@ -3214,60 +3389,20 @@ const enforceConsistentVariableSyntax = (0, _oxlint_plugins.defineRule)({
3214
3389
  }
3215
3390
  },
3216
3391
  createOnce(context) {
3217
- let _syntax = null;
3218
- function getSyntax() {
3219
- if (_syntax === null) _syntax = safeOptions(context)?.syntax ?? "shorthand";
3220
- return _syntax;
3221
- }
3392
+ const getSyntax = createLazyOptions(context, (o) => o?.syntax ?? "shorthand");
3222
3393
  function check(locations) {
3223
3394
  const syntax = getSyntax();
3395
+ const messageId = syntax === "shorthand" ? "useShorthand" : "useExplicit";
3224
3396
  for (const loc of locations) {
3225
3397
  const split = splitClassesWithSeparators(loc.value);
3226
- const classes = split.classes;
3227
- const offending = [];
3228
- for (const cls of classes) {
3398
+ const offending = split.classes.flatMap((cls) => {
3229
3399
  const converted = convertClass(cls, syntax);
3230
- if (converted) offending.push({
3400
+ return converted ? [{
3231
3401
  cls,
3232
3402
  replacement: converted
3233
- });
3234
- }
3235
- if (offending.length === 0) continue;
3236
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
3237
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
3238
- const messageId = syntax === "shorthand" ? "useShorthand" : "useExplicit";
3239
- for (let i = 0; i < offending.length; i++) {
3240
- const { cls, replacement } = offending[i];
3241
- if (i === 0) context.report({
3242
- node: loc.node,
3243
- messageId,
3244
- data: {
3245
- className: cls,
3246
- replacement
3247
- },
3248
- fix(fixer) {
3249
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3250
- }
3251
- });
3252
- else context.report({
3253
- node: loc.node,
3254
- messageId,
3255
- data: {
3256
- className: cls,
3257
- replacement
3258
- },
3259
- suggest: [{
3260
- messageId: "suggestReplace",
3261
- data: {
3262
- className: cls,
3263
- replacement
3264
- },
3265
- fix(fixer) {
3266
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3267
- }
3268
- }]
3269
- });
3270
- }
3403
+ }] : [];
3404
+ });
3405
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId });
3271
3406
  }
3272
3407
  }
3273
3408
  return createExtractorVisitors(context, check);
@@ -3313,9 +3448,7 @@ const KNOWN_PREFIXES = [
3313
3448
  * Used to group utilities by their property type.
3314
3449
  */
3315
3450
  function getUtilityPrefix(utility) {
3316
- let u = utility;
3317
- if (u.startsWith("!")) u = u.slice(1);
3318
- else if (u.endsWith("!")) u = u.slice(0, -1);
3451
+ let u = splitImportant(utility).bare;
3319
3452
  if (u.startsWith("-")) u = u.slice(1);
3320
3453
  for (const prefix of KNOWN_PREFIXES) if (u === prefix || u.startsWith(`${prefix}-`)) return prefix;
3321
3454
  const dashIdx = u.indexOf("-");
@@ -3337,14 +3470,7 @@ const noDarkWithoutLight = (0, _oxlint_plugins.defineRule)({
3337
3470
  messages: { missingBase: "\"{{className}}\" uses the {{variant}} variant, but there is no base \"{{prefix}}-*\" class on this element." }
3338
3471
  },
3339
3472
  createOnce(context) {
3340
- let _watchedVariants = null;
3341
- function getWatchedVariants() {
3342
- if (_watchedVariants === null) {
3343
- const options = safeOptions(context);
3344
- _watchedVariants = new Set(options?.variants ?? DEFAULT_VARIANTS);
3345
- }
3346
- return _watchedVariants;
3347
- }
3473
+ const getWatchedVariants = createLazyOptions(context, (o) => new Set(o?.variants ?? DEFAULT_VARIANTS));
3348
3474
  function check(locations) {
3349
3475
  const watchedVariants = getWatchedVariants();
3350
3476
  for (const loc of locations) {
@@ -3415,8 +3541,10 @@ const LCH_RE = /^lch\s*\(/;
3415
3541
  const LAB_RE = /^lab\s*\(/;
3416
3542
  const HWB_RE = /^hwb\s*\(/;
3417
3543
  const COLOR_RE = /^color\s*\(/;
3544
+ const VAR_REF_RE = /var\(\s*--[\w-]+/i;
3418
3545
  function isHardcodedColor(value) {
3419
3546
  const trimmed = value.trim();
3547
+ if (VAR_REF_RE.test(trimmed)) return false;
3420
3548
  return HEX_RE.test(trimmed) || RGB_RE.test(trimmed) || HSL_RE.test(trimmed) || OKLCH_RE.test(trimmed) || OKLAB_RE.test(trimmed) || LCH_RE.test(trimmed) || LAB_RE.test(trimmed) || HWB_RE.test(trimmed) || COLOR_RE.test(trimmed);
3421
3549
  }
3422
3550
  function isColorUtility(utility) {
@@ -3438,17 +3566,11 @@ const noHardcodedColors = (0, _oxlint_plugins.defineRule)({
3438
3566
  },
3439
3567
  additionalProperties: false
3440
3568
  }],
3569
+ defaultOptions: [{ allow: [] }],
3441
3570
  messages: { noHardcoded: "\"{{className}}\" uses a hardcoded color value. Use a design token from your theme instead." }
3442
3571
  },
3443
3572
  createOnce(context) {
3444
- let _allowlist = null;
3445
- function getAllowlist() {
3446
- if (_allowlist === null) {
3447
- const options = safeOptions(context);
3448
- _allowlist = new Set(options?.allow ?? []);
3449
- }
3450
- return _allowlist;
3451
- }
3573
+ const getAllowlist = createLazyOptions(context, (o) => new Set(o?.allow ?? []));
3452
3574
  function check(locations) {
3453
3575
  const allowlist = getAllowlist();
3454
3576
  for (const loc of locations) {
@@ -3456,9 +3578,7 @@ const noHardcodedColors = (0, _oxlint_plugins.defineRule)({
3456
3578
  for (const cls of classes) {
3457
3579
  if (allowlist.has(cls)) continue;
3458
3580
  if (!hasArbitraryValue(cls)) continue;
3459
- let utility = extractUtility(cls);
3460
- if (utility.startsWith("!")) utility = utility.slice(1);
3461
- else if (utility.endsWith("!")) utility = utility.slice(0, -1);
3581
+ const utility = splitImportant(extractUtility(cls)).bare;
3462
3582
  if (!isColorUtility(utility)) continue;
3463
3583
  const value = getArbitraryValue(cls);
3464
3584
  if (!value) continue;
@@ -3629,6 +3749,7 @@ const consistentVariantOrder = (0, _oxlint_plugins.defineRule)({
3629
3749
  additionalProperties: false
3630
3750
  }],
3631
3751
  hasSuggestions: true,
3752
+ defaultOptions: [{}],
3632
3753
  messages: {
3633
3754
  wrongOrder: "\"{{className}}\" has variants in wrong order. Use \"{{replacement}}\" instead.",
3634
3755
  suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
@@ -3636,54 +3757,33 @@ const consistentVariantOrder = (0, _oxlint_plugins.defineRule)({
3636
3757
  },
3637
3758
  createOnce(context) {
3638
3759
  const getDS = createLazyLoader(context);
3639
- let _config = null;
3640
- function getConfig() {
3641
- if (_config === null) {
3642
- const options = safeOptions(context);
3643
- const dsCache = getDS()?.cache ?? null;
3644
- const priorityMap = /* @__PURE__ */ new Map();
3645
- if (options?.order) {
3646
- for (let i = 0; i < options.order.length; i++) priorityMap.set(options.order[i], i);
3647
- _config = {
3648
- priorityMap,
3649
- fallbackPriority: options.order.length,
3650
- dsCache
3651
- };
3652
- } else if (dsCache && dsCache.hasVariantOrder()) {
3653
- for (const variant of DEFAULT_VARIANT_ORDER) {
3654
- const p = dsCache.getVariantPriority(variant);
3655
- if (p !== null) priorityMap.set(variant, p);
3656
- }
3657
- _config = {
3658
- priorityMap,
3659
- fallbackPriority: Number.MAX_SAFE_INTEGER,
3660
- dsCache
3661
- };
3662
- } else {
3663
- for (let i = 0; i < DEFAULT_VARIANT_ORDER.length; i++) priorityMap.set(DEFAULT_VARIANT_ORDER[i], i);
3664
- _config = {
3665
- priorityMap,
3666
- fallbackPriority: DEFAULT_VARIANT_ORDER.length,
3667
- dsCache
3668
- };
3669
- }
3760
+ const getPriority = createLazyOptions(context, (o) => {
3761
+ let dsCache = null;
3762
+ try {
3763
+ dsCache = getDS().cache;
3764
+ } catch (err) {
3765
+ if (!isFatalError(err)) throw err;
3766
+ }
3767
+ if (o?.order) {
3768
+ const map = /* @__PURE__ */ new Map();
3769
+ for (let i = 0; i < o.order.length; i++) map.set(o.order[i], i);
3770
+ const fallback = o.order.length;
3771
+ return (v) => map.get(v) ?? fallback;
3670
3772
  }
3671
- return _config;
3672
- }
3673
- function getVariantPriority(variant) {
3674
- const { priorityMap, fallbackPriority, dsCache } = getConfig();
3675
- const priority = priorityMap.get(variant);
3676
- if (priority !== void 0) return priority;
3677
3773
  if (dsCache && dsCache.hasVariantOrder()) {
3678
- const dsPriority = dsCache.getVariantPriority(variant);
3679
- if (dsPriority !== null) return dsPriority;
3774
+ const ds = dsCache;
3775
+ return (v) => ds.getVariantPriority(v) ?? Number.MAX_SAFE_INTEGER;
3680
3776
  }
3681
- return fallbackPriority;
3682
- }
3777
+ const map = /* @__PURE__ */ new Map();
3778
+ for (let i = 0; i < DEFAULT_VARIANT_ORDER.length; i++) map.set(DEFAULT_VARIANT_ORDER[i], i);
3779
+ const fallback = DEFAULT_VARIANT_ORDER.length;
3780
+ return (v) => map.get(v) ?? fallback;
3781
+ });
3683
3782
  function reorderClass(cls) {
3684
3783
  const variants = extractVariants(cls);
3685
3784
  if (variants.length < 2) return null;
3686
- const sorted = [...variants].sort((a, b) => getVariantPriority(a) - getVariantPriority(b));
3785
+ const priorityOf = getPriority();
3786
+ const sorted = [...variants].sort((a, b) => priorityOf(a) - priorityOf(b));
3687
3787
  const nonPseudo = [];
3688
3788
  const pseudo = [];
3689
3789
  for (const v of sorted) if (PSEUDO_ELEMENTS.has(v)) pseudo.push(v);
@@ -3768,16 +3868,8 @@ const enforceConsistentLineWrapping = (0, _oxlint_plugins.defineRule)({
3768
3868
  }
3769
3869
  },
3770
3870
  createOnce(context) {
3771
- let _printWidth = null;
3772
- function getPrintWidth() {
3773
- if (_printWidth === null) _printWidth = safeOptions(context)?.printWidth ?? DEFAULT_PRINT_WIDTH;
3774
- return _printWidth;
3775
- }
3776
- let _classesPerLine = null;
3777
- function getClassesPerLine() {
3778
- if (_classesPerLine === null) _classesPerLine = safeOptions(context)?.classesPerLine ?? void 0;
3779
- return _classesPerLine;
3780
- }
3871
+ const getPrintWidth = createLazyOptions(context, (o) => o?.printWidth ?? DEFAULT_PRINT_WIDTH);
3872
+ const getClassesPerLine = createLazyOptions(context, (o) => o?.classesPerLine);
3781
3873
  function check(locations) {
3782
3874
  const printWidth = getPrintWidth();
3783
3875
  const classesPerLine = getClassesPerLine();
@@ -3836,69 +3928,33 @@ const noUnnecessaryArbitraryValue = (0, _oxlint_plugins.defineRule)({
3836
3928
  additionalProperties: false
3837
3929
  }],
3838
3930
  hasSuggestions: true,
3931
+ defaultOptions: [{}],
3839
3932
  messages: {
3840
3933
  unnecessaryArbitrary: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named class instead.",
3841
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
3934
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
3935
+ ...DS_UNAVAILABLE_MESSAGE
3842
3936
  }
3843
3937
  },
3844
3938
  createOnce(context) {
3845
3939
  const getDS = createLazyLoader(context);
3846
3940
  function check(locations) {
3847
- const ds = getDS();
3941
+ if (locations.length === 0) return;
3942
+ const ds = safeGetDS(getDS, context, locations[0].node);
3848
3943
  if (!ds) return;
3849
3944
  const { cache } = ds;
3850
3945
  for (const loc of locations) {
3851
3946
  const split = splitClassesWithSeparators(loc.value);
3852
- const classes = split.classes;
3853
- const offending = [];
3854
- for (const cls of classes) {
3855
- if (!hasArbitraryValue(cls)) continue;
3947
+ const offending = split.classes.flatMap((cls) => {
3948
+ if (!hasArbitraryValue(cls)) return [];
3856
3949
  const { utility, variant } = splitUtilityAndVariant(cls);
3857
- const hasImportantPrefix = utility.startsWith("!");
3858
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
3859
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
3950
+ const { bare: bareUtility, position } = splitImportant(utility);
3860
3951
  const named = cache.getNamedEquivalent(bareUtility);
3861
- if (!named) continue;
3862
- offending.push({
3952
+ return named ? [{
3863
3953
  cls,
3864
- replacement: variant + (hasImportantPrefix ? "!" : "") + named + (hasImportantSuffix ? "!" : "")
3865
- });
3866
- }
3867
- if (offending.length === 0) continue;
3868
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
3869
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
3870
- for (let i = 0; i < offending.length; i++) {
3871
- const { cls, replacement } = offending[i];
3872
- if (i === 0) context.report({
3873
- node: loc.node,
3874
- messageId: "unnecessaryArbitrary",
3875
- data: {
3876
- className: cls,
3877
- replacement
3878
- },
3879
- fix(fixer) {
3880
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3881
- }
3882
- });
3883
- else context.report({
3884
- node: loc.node,
3885
- messageId: "unnecessaryArbitrary",
3886
- data: {
3887
- className: cls,
3888
- replacement
3889
- },
3890
- suggest: [{
3891
- messageId: "suggestReplace",
3892
- data: {
3893
- className: cls,
3894
- replacement
3895
- },
3896
- fix(fixer) {
3897
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3898
- }
3899
- }]
3900
- });
3901
- }
3954
+ replacement: variant + reattachImportant(named, position)
3955
+ }] : [];
3956
+ });
3957
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "unnecessaryArbitrary" });
3902
3958
  }
3903
3959
  }
3904
3960
  return createExtractorVisitors(context, check);
@@ -3942,73 +3998,37 @@ const preferThemeTokens = (0, _oxlint_plugins.defineRule)({
3942
3998
  additionalProperties: false
3943
3999
  }],
3944
4000
  hasSuggestions: true,
4001
+ defaultOptions: [{}],
3945
4002
  messages: {
3946
4003
  preferNamed: "\"{{className}}\" can be written as \"{{replacement}}\". Use the named theme token.",
3947
- suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\"."
4004
+ suggestReplace: "Replace \"{{className}}\" with \"{{replacement}}\".",
4005
+ ...DS_UNAVAILABLE_MESSAGE
3948
4006
  }
3949
4007
  },
3950
4008
  createOnce(context) {
3951
4009
  const getDS = createLazyLoader(context);
3952
4010
  function check(locations) {
3953
- const ds = getDS();
4011
+ if (locations.length === 0) return;
4012
+ const ds = safeGetDS(getDS, context, locations[0].node);
3954
4013
  if (!ds) return;
3955
4014
  const { cache } = ds;
3956
4015
  for (const loc of locations) {
3957
4016
  const split = splitClassesWithSeparators(loc.value);
3958
- const classes = split.classes;
3959
- const offending = [];
3960
- for (const cls of classes) {
4017
+ const offending = split.classes.flatMap((cls) => {
3961
4018
  const { utility, variant } = splitUtilityAndVariant(cls);
3962
- const hasImportantPrefix = utility.startsWith("!");
3963
- const hasImportantSuffix = !hasImportantPrefix && utility.endsWith("!");
3964
- const bareUtility = hasImportantPrefix ? utility.slice(1) : hasImportantSuffix ? utility.slice(0, -1) : utility;
4019
+ const { bare: bareUtility, position } = splitImportant(utility);
3965
4020
  const match = detectRawVariable(bareUtility);
3966
- if (!match) continue;
4021
+ if (!match) return [];
3967
4022
  const candidate = `${match.prefix}-${match.varName}${match.modifier}`;
3968
- if (!cache.isValid(candidate)) continue;
4023
+ if (!cache.isValid(candidate)) return [];
3969
4024
  const namedEquivalent = cache.getNamedEquivalent(bareUtility);
3970
- if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) continue;
3971
- const replacement = variant + (hasImportantPrefix ? "!" : "") + candidate + (hasImportantSuffix ? "!" : "");
3972
- offending.push({
4025
+ if (namedEquivalent && namedEquivalent === `${match.prefix}-${match.varName}`) return [];
4026
+ return [{
3973
4027
  cls,
3974
- replacement
3975
- });
3976
- }
3977
- if (offending.length === 0) continue;
3978
- const replacements = new Map(offending.map(({ cls, replacement }) => [cls, replacement]));
3979
- const fixedValue = rebuildClassString(split, classes.map((cls) => replacements.get(cls) ?? cls));
3980
- for (let i = 0; i < offending.length; i++) {
3981
- const { cls, replacement } = offending[i];
3982
- if (i === 0) context.report({
3983
- node: loc.node,
3984
- messageId: "preferNamed",
3985
- data: {
3986
- className: cls,
3987
- replacement
3988
- },
3989
- fix(fixer) {
3990
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
3991
- }
3992
- });
3993
- else context.report({
3994
- node: loc.node,
3995
- messageId: "preferNamed",
3996
- data: {
3997
- className: cls,
3998
- replacement
3999
- },
4000
- suggest: [{
4001
- messageId: "suggestReplace",
4002
- data: {
4003
- className: cls,
4004
- replacement
4005
- },
4006
- fix(fixer) {
4007
- return fixer.replaceTextRange(loc.range, preserveSpaces(loc, fixedValue));
4008
- }
4009
- }]
4010
- });
4011
- }
4028
+ replacement: variant + reattachImportant(candidate, position)
4029
+ }];
4030
+ });
4031
+ reportClassReplacements(context, loc, split, split.classes, offending, { messageId: "preferNamed" });
4012
4032
  }
4013
4033
  }
4014
4034
  return createExtractorVisitors(context, check);