oxlint-tailwindcss 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -46,9 +46,14 @@ const DEFAULT_EXTRACTOR_CONFIG = {
46
46
  };
47
47
  let _cachedConfig = null;
48
48
  let _settingsResolved = false;
49
- function mergeUnique(defaults, extras) {
50
- if (!extras || extras.length === 0) return defaults;
51
- const set = new Set(defaults);
49
+ function mergeUnique(defaults, extras, exclusions) {
50
+ let base = defaults;
51
+ if (exclusions && exclusions.length > 0) {
52
+ const excludeSet = new Set(exclusions);
53
+ base = base.filter((d) => !excludeSet.has(d));
54
+ }
55
+ if (!extras || extras.length === 0) return base;
56
+ const set = new Set(base);
52
57
  for (const e of extras) set.add(e);
53
58
  return [...set];
54
59
  }
@@ -71,11 +76,14 @@ function getExtractorConfig(context) {
71
76
  _cachedConfig = DEFAULT_EXTRACTOR_CONFIG;
72
77
  return _cachedConfig;
73
78
  }
79
+ const exclude = tw.exclude;
80
+ const excludedPatternSources = new Set(exclude?.variablePatterns ?? []);
81
+ const filteredPatterns = excludedPatternSources.size > 0 ? DEFAULT_EXTRACTOR_CONFIG.variablePatterns.filter((re) => !excludedPatternSources.has(re.source)) : DEFAULT_EXTRACTOR_CONFIG.variablePatterns;
74
82
  _cachedConfig = {
75
- attributes: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.attributes, tw.attributes),
76
- callees: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.callees, tw.callees),
77
- tags: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.tags, tw.tags),
78
- variablePatterns: [...DEFAULT_EXTRACTOR_CONFIG.variablePatterns, ...(tw.variablePatterns ?? []).map((p) => new RegExp(p))]
83
+ attributes: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.attributes, tw.attributes, exclude?.attributes),
84
+ callees: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.callees, tw.callees, exclude?.callees),
85
+ tags: mergeUnique(DEFAULT_EXTRACTOR_CONFIG.tags, tw.tags, exclude?.tags),
86
+ variablePatterns: [...filteredPatterns, ...(tw.variablePatterns ?? []).map((p) => new RegExp(p))]
79
87
  };
80
88
  return _cachedConfig;
81
89
  }
@@ -868,6 +876,10 @@ async function main() {
868
876
  const entries = ds.getClassList();
869
877
  const classNames = entries.map(e => e[0]);
870
878
 
879
+ // Index for O(1) lookups by class name (avoids O(N) indexOf/includes in later phases)
880
+ const classNameIndex = new Map();
881
+ for (let i = 0; i < classNames.length; i++) classNameIndex.set(classNames[i], i);
882
+
871
883
  // Validity: which classes produce CSS
872
884
  const cssResults = ds.candidatesToCss(classNames);
873
885
  const validClasses = classNames.filter((_, i) => cssResults[i] != null);
@@ -929,7 +941,7 @@ async function main() {
929
941
  // Sort order — include extra candidates so bare utilities (rounded, blur, etc.) get order
930
942
  const allForOrder = [...classNames];
931
943
  for (const cls of validClasses) {
932
- if (!classNames.includes(cls)) allForOrder.push(cls);
944
+ if (!classNameIndex.has(cls)) allForOrder.push(cls);
933
945
  }
934
946
  const order = {};
935
947
  const orderResults = ds.getClassOrder(allForOrder);
@@ -1059,7 +1071,8 @@ async function main() {
1059
1071
  const candidates = [];
1060
1072
  for (const cls of validClasses) {
1061
1073
  if (cls.includes('[') || cls.includes('/')) continue;
1062
- const idx = classNames.indexOf(cls);
1074
+ const idx = classNameIndex.get(cls);
1075
+ if (idx === undefined) continue;
1063
1076
  const cssText = cssResults[idx];
1064
1077
  if (!cssText) continue;
1065
1078
  const pvMatch = cssText.match(/^\\s+([\\w-]+)\\s*:\\s*(.+?)\\s*;?\\s*$/m);
@@ -1092,21 +1105,61 @@ async function main() {
1092
1105
  main().catch(e => { process.stderr.write(e.message); process.exit(1); });
1093
1106
  `;
1094
1107
  const CACHE_DIR = join(tmpdir(), "oxlint-tailwindcss");
1095
- const CACHE_VERSION = 10;
1096
- function getCachePath(cssPath, mtime) {
1097
- return join(CACHE_DIR, `${createHash("md5").update(`v${CACHE_VERSION}:${cssPath}:${mtime}`).digest("hex")}.json`);
1108
+ const CACHE_VERSION = 11;
1109
+ /**
1110
+ * Two-level disk cache for monorepo deduplication:
1111
+ *
1112
+ * Level 1 — mtime index (.idx): maps path+mtime → content hash (fast-path, avoids reading CSS)
1113
+ * Level 2 — content cache (.json): maps content hash → precomputed data (shared across packages)
1114
+ *
1115
+ * In monorepos, multiple packages with identical CSS (e.g. `@import 'tailwindcss'`) at different
1116
+ * paths share a single content cache entry, avoiding redundant child process spawns.
1117
+ */
1118
+ function getMtimeIndexPath(cssPath, mtime) {
1119
+ return join(CACHE_DIR, `${createHash("md5").update(`v${CACHE_VERSION}:${cssPath}:${mtime}`).digest("hex")}.idx`);
1120
+ }
1121
+ function computeContentHash(content) {
1122
+ return createHash("md5").update(`v${CACHE_VERSION}:${content}`).digest("hex");
1123
+ }
1124
+ function getContentCachePath(contentHash) {
1125
+ return join(CACHE_DIR, `${contentHash}.json`);
1126
+ }
1127
+ function tryReadCache(cachePath) {
1128
+ try {
1129
+ return JSON.parse(readFileSync(cachePath, "utf-8"));
1130
+ } catch {
1131
+ return null;
1132
+ }
1133
+ }
1134
+ function writeCacheFiles(contentCachePath, mtimeIndexPath, contentHash, data) {
1135
+ try {
1136
+ mkdirSync(CACHE_DIR, { recursive: true });
1137
+ writeFileSync(contentCachePath, data);
1138
+ writeFileSync(mtimeIndexPath, contentHash);
1139
+ } catch {}
1098
1140
  }
1099
- function loadDesignSystemSync(cssPath) {
1141
+ function loadDesignSystemSync(cssPath, timeout) {
1100
1142
  const resolvedPath = resolve(cssPath);
1101
1143
  try {
1102
1144
  const mtime = statSync(resolvedPath).mtimeMs;
1103
- const cachePath = getCachePath(resolvedPath, mtime);
1104
- if (existsSync(cachePath)) try {
1105
- return JSON.parse(readFileSync(cachePath, "utf-8"));
1145
+ const mtimeIndexPath = getMtimeIndexPath(resolvedPath, mtime);
1146
+ if (existsSync(mtimeIndexPath)) try {
1147
+ const cached = tryReadCache(getContentCachePath(readFileSync(mtimeIndexPath, "utf-8").trim()));
1148
+ if (cached) return cached;
1106
1149
  } catch {}
1150
+ const contentHash = computeContentHash(readFileSync(resolvedPath, "utf-8"));
1151
+ const contentCachePath = getContentCachePath(contentHash);
1152
+ const cached = tryReadCache(contentCachePath);
1153
+ if (cached) {
1154
+ try {
1155
+ mkdirSync(CACHE_DIR, { recursive: true });
1156
+ writeFileSync(mtimeIndexPath, contentHash);
1157
+ } catch {}
1158
+ return cached;
1159
+ }
1107
1160
  const stdout = execFileSync(process.execPath, ["-e", PRECOMPUTE_SCRIPT], {
1108
1161
  encoding: "utf-8",
1109
- timeout: 3e4,
1162
+ timeout: timeout ?? 3e4,
1110
1163
  maxBuffer: 50 * 1024 * 1024,
1111
1164
  env: {
1112
1165
  ...process.env,
@@ -1114,10 +1167,7 @@ function loadDesignSystemSync(cssPath) {
1114
1167
  },
1115
1168
  cwd: dirname(resolvedPath)
1116
1169
  });
1117
- try {
1118
- mkdirSync(CACHE_DIR, { recursive: true });
1119
- writeFileSync(cachePath, stdout);
1120
- } catch {}
1170
+ writeCacheFiles(contentCachePath, mtimeIndexPath, contentHash, stdout);
1121
1171
  return JSON.parse(stdout);
1122
1172
  } catch (error) {
1123
1173
  console.error(`[oxlint-tailwindcss] Failed to load design system from "${resolvedPath}":`, error instanceof Error ? error.message : error);
@@ -1126,6 +1176,44 @@ function loadDesignSystemSync(cssPath) {
1126
1176
  }
1127
1177
  //#endregion
1128
1178
  //#region src/design-system/auto-detect.ts
1179
+ const IMPORT_RE = /@import\s+['"]([^'"]+)['"]/g;
1180
+ /**
1181
+ * Resolves a CSS @import specifier to an absolute path.
1182
+ * Handles relative paths and package imports (walks up to node_modules).
1183
+ */
1184
+ function resolveImport(specifier, baseDir) {
1185
+ if (specifier.startsWith(".")) return resolve(baseDir, specifier);
1186
+ let dir = baseDir;
1187
+ while (true) {
1188
+ const candidate = join(dir, "node_modules", specifier);
1189
+ if (existsSync(candidate)) return candidate;
1190
+ const parent = dirname(dir);
1191
+ if (parent === dir) break;
1192
+ dir = parent;
1193
+ }
1194
+ return null;
1195
+ }
1196
+ /**
1197
+ * Checks if any @import in the CSS content points to a file containing a Tailwind signal.
1198
+ * Only follows ONE level of imports — no recursion.
1199
+ */
1200
+ function hasTailwindSignalInImports(content, baseDir, signals) {
1201
+ IMPORT_RE.lastIndex = 0;
1202
+ let match;
1203
+ while ((match = IMPORT_RE.exec(content)) !== null) {
1204
+ const specifier = match[1];
1205
+ if (specifier === "tailwindcss") continue;
1206
+ const resolved = resolveImport(specifier, baseDir);
1207
+ if (!resolved) continue;
1208
+ try {
1209
+ const imported = readFileSync(resolved, "utf-8");
1210
+ if (signals.some((signal) => imported.includes(signal))) return true;
1211
+ } catch {
1212
+ continue;
1213
+ }
1214
+ }
1215
+ return false;
1216
+ }
1129
1217
  const CANDIDATE_DIRS = [
1130
1218
  "src",
1131
1219
  ".",
@@ -1168,6 +1256,7 @@ function autoDetectEntryPoint(filePath) {
1168
1256
  try {
1169
1257
  const content = readFileSync(fullPath, "utf-8");
1170
1258
  if (TAILWIND_SIGNALS.some((signal) => content.includes(signal))) return fullPath;
1259
+ if (hasTailwindSignalInImports(content, dirname(fullPath), TAILWIND_SIGNALS)) return fullPath;
1171
1260
  } catch {
1172
1261
  continue;
1173
1262
  }
@@ -1181,6 +1270,7 @@ function autoDetectEntryPoint(filePath) {
1181
1270
  try {
1182
1271
  const content = readFileSync(fullPath, "utf-8");
1183
1272
  if (TAILWIND_SIGNALS.some((signal) => content.includes(signal))) return fullPath;
1273
+ if (hasTailwindSignalInImports(content, dirname(fullPath), TAILWIND_SIGNALS)) return fullPath;
1184
1274
  } catch {
1185
1275
  continue;
1186
1276
  }
@@ -1193,7 +1283,9 @@ function autoDetectEntryPoint(filePath) {
1193
1283
  }
1194
1284
  //#endregion
1195
1285
  //#region src/design-system/loader.ts
1196
- let singleton = null;
1286
+ const dsCache = /* @__PURE__ */ new Map();
1287
+ const autoDetectCache = /* @__PURE__ */ new Map();
1288
+ let lastLoadedPath = null;
1197
1289
  /**
1198
1290
  * Extracts `entryPoint` from `context.settings.tailwindcss`.
1199
1291
  */
@@ -1205,30 +1297,57 @@ function entryPointFromSettings(settings) {
1205
1297
  }
1206
1298
  }
1207
1299
  /**
1300
+ * Extracts `timeout` from `context.settings.tailwindcss`.
1301
+ */
1302
+ function timeoutFromSettings(settings) {
1303
+ const tw = settings?.tailwindcss;
1304
+ if (tw && typeof tw === "object" && "timeout" in tw) {
1305
+ const t = tw.timeout;
1306
+ if (typeof t === "number" && t > 0) return t;
1307
+ }
1308
+ }
1309
+ /**
1310
+ * Cached auto-detect: caches by directory since all files in the same directory
1311
+ * resolve to the same entry point. Avoids repeated filesystem walks.
1312
+ */
1313
+ function cachedAutoDetect(filePath) {
1314
+ if (!filePath) return autoDetectEntryPoint(filePath);
1315
+ const dir = dirname(resolve(filePath));
1316
+ const cached = autoDetectCache.get(dir);
1317
+ if (cached !== void 0) return cached;
1318
+ const result = autoDetectEntryPoint(filePath);
1319
+ autoDetectCache.set(dir, result);
1320
+ return result;
1321
+ }
1322
+ /**
1208
1323
  * Returns the design system cache, loading synchronously on first call.
1209
1324
  * Uses execFileSync internally to bridge the async Tailwind API.
1210
- * All rules receive the SAME instance.
1325
+ *
1326
+ * Supports multiple design systems: each unique CSS entry point gets its own cache.
1327
+ * In monorepos, files in different packages auto-detect to different entry points
1328
+ * and each gets the correct DS.
1211
1329
  *
1212
1330
  * Resolution order: rule option `entryPoint` > `settings.tailwindcss.entryPoint` > auto-detect.
1213
1331
  */
1214
1332
  function getLoadedDesignSystem(entryPoint, settings, filePath) {
1215
- const cssPath = entryPoint ?? entryPointFromSettings(settings) ?? singleton?.path ?? autoDetectEntryPoint(filePath);
1333
+ const cssPath = entryPoint ?? entryPointFromSettings(settings) ?? cachedAutoDetect(filePath) ?? lastLoadedPath;
1216
1334
  if (!cssPath) return null;
1217
1335
  const resolvedPath = resolve(cssPath);
1218
1336
  try {
1219
1337
  const mtime = statSync(resolvedPath).mtimeMs;
1220
- if (singleton !== null && singleton.path === resolvedPath && singleton.mtime === mtime) return {
1221
- cache: singleton.cache,
1338
+ const cached = dsCache.get(resolvedPath);
1339
+ if (cached && cached.mtime === mtime) return {
1340
+ cache: cached.cache,
1222
1341
  entryPoint: resolvedPath
1223
1342
  };
1224
- const data = loadDesignSystemSync(resolvedPath);
1343
+ const data = loadDesignSystemSync(resolvedPath, timeoutFromSettings(settings));
1225
1344
  if (!data) return null;
1226
1345
  const cache = DesignSystemCache.fromPrecomputed(data);
1227
- singleton = {
1346
+ dsCache.set(resolvedPath, {
1228
1347
  cache,
1229
- path: resolvedPath,
1230
1348
  mtime
1231
- };
1349
+ });
1350
+ lastLoadedPath = resolvedPath;
1232
1351
  return {
1233
1352
  cache,
1234
1353
  entryPoint: resolvedPath
@@ -1238,17 +1357,21 @@ function getLoadedDesignSystem(entryPoint, settings, filePath) {
1238
1357
  }
1239
1358
  }
1240
1359
  /**
1241
- * Creates a lazy DS loader that retries with more context as it becomes available.
1360
+ * Creates a lazy DS loader that resolves the correct design system per file.
1242
1361
  *
1243
1362
  * In `createOnce`, `context.settings` and `context.filename` throw. When visitors
1244
- * run, they become available. This function retries until it has the file path
1245
- * (meaning we're in a visitor with full context), then gives up.
1363
+ * run, they become available. The loader re-resolves when the filename changes,
1364
+ * supporting monorepos where different files need different design systems.
1365
+ *
1366
+ * When a fixed entryPoint is provided (rule option or settings), it's used for all
1367
+ * files and cached after first resolution.
1246
1368
  */
1247
1369
  function createLazyLoader(context) {
1248
- let result = null;
1249
1370
  let lastFilePath;
1371
+ let lastResult = null;
1372
+ let fixedEntryResolved = false;
1373
+ let fixedResult = null;
1250
1374
  return () => {
1251
- if (result) return result;
1252
1375
  let entryPoint;
1253
1376
  try {
1254
1377
  entryPoint = (context.options?.[0])?.entryPoint;
@@ -1261,10 +1384,17 @@ function createLazyLoader(context) {
1261
1384
  try {
1262
1385
  filePath = context.filename;
1263
1386
  } catch {}
1264
- if (filePath && filePath === lastFilePath) return null;
1387
+ const fixedEntry = entryPoint ?? entryPointFromSettings(settings);
1388
+ if (fixedEntry) {
1389
+ if (fixedEntryResolved) return fixedResult;
1390
+ fixedEntryResolved = true;
1391
+ fixedResult = getLoadedDesignSystem(fixedEntry, settings, filePath);
1392
+ return fixedResult;
1393
+ }
1394
+ if (filePath && filePath === lastFilePath) return lastResult;
1265
1395
  if (filePath) lastFilePath = filePath;
1266
- result = getLoadedDesignSystem(entryPoint, settings, filePath);
1267
- return result;
1396
+ lastResult = getLoadedDesignSystem(void 0, settings, filePath);
1397
+ return lastResult;
1268
1398
  };
1269
1399
  }
1270
1400
  //#endregion
@@ -1693,9 +1823,19 @@ let lengthView = null;
1693
1823
  let dataArea = null;
1694
1824
  let initialized = false;
1695
1825
  let available = true;
1826
+ let currentCssPath = null;
1696
1827
  function ensureService(cssPath) {
1697
- if (initialized) return available;
1828
+ if (initialized && currentCssPath === cssPath) return available;
1829
+ if (initialized) {
1830
+ cleanup();
1831
+ initialized = false;
1832
+ available = true;
1833
+ controlArray = null;
1834
+ lengthView = null;
1835
+ dataArea = null;
1836
+ }
1698
1837
  initialized = true;
1838
+ currentCssPath = cssPath;
1699
1839
  try {
1700
1840
  const tailwindNodePath = __require.resolve("@tailwindcss/node");
1701
1841
  const sharedBuffer = new SharedArrayBuffer(BUFFER_SIZE);