oxlint-tailwindcss 1.0.0 → 1.0.1

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
@@ -1,10 +1,9 @@
1
1
  let _oxlint_plugins = require("@oxlint/plugins");
2
- let node_child_process = require("node:child_process");
2
+ let node_worker_threads = require("node:worker_threads");
3
3
  let node_crypto = require("node:crypto");
4
4
  let node_fs = require("node:fs");
5
5
  let node_path = require("node:path");
6
6
  let node_os = require("node:os");
7
- let node_worker_threads = require("node:worker_threads");
8
7
  //#region src/utils/extractors.ts
9
8
  /**
10
9
  * Preserves leading/trailing spaces in fixed class strings for template literals.
@@ -1044,21 +1043,51 @@ const TAILWIND_NODE_VERSION = entryPath !== null ? readVersionFromEntry(entryPat
1044
1043
  //#endregion
1045
1044
  //#region src/design-system/sync-loader.ts
1046
1045
  /**
1047
- * Synchronous design system loader using execFileSync.
1046
+ * Synchronous design system loader using a worker_thread.
1048
1047
  *
1049
1048
  * The problem: __unstable__loadDesignSystem is async, but oxlint's createOnce is sync.
1050
- * The solution: spawn a child process that loads the design system, pre-computes all
1051
- * data we need, and returns it as JSON via stdout. This runs ONCE at plugin init time.
1049
+ * The solution: run the design-system load + precompute in a worker_thread that writes
1050
+ * the result JSON straight to the disk cache and signals completion over a
1051
+ * SharedArrayBuffer, while the main thread blocks on `Atomics.wait`. This runs ONCE per
1052
+ * unique CSS entry point at plugin init time.
1053
+ *
1054
+ * Why a worker_thread and not a forked child process (the pre-1.1 design): `execFileSync`
1055
+ * does `fork()` of the oxlint host (Rust + embedded Node). Under Linux overcommit
1056
+ * accounting on memory-constrained CI runners, forking a large-RSS process is rejected
1057
+ * with `spawnSync … ENOMEM` even though the child immediately `exec`s (#24). A
1058
+ * worker_thread creates a thread in-process — no address-space duplication — so it is
1059
+ * immune. This mirrors what `sort-service.ts` / `canonicalize-service.ts` already do.
1052
1060
  *
1053
1061
  * For arbitrary values (bg-[#123]) that aren't in the class list, we use heuristics.
1054
1062
  */
1055
1063
  const PRECOMPUTE_SCRIPT = `
1056
- // Resolve @tailwindcss/node via an absolute path passed in by the parent
1057
- // process — bare-specifier lookup from this child's cwd fails under pnpm
1058
- // strict workspaces (the module lives under node_modules/.pnpm/... which
1059
- // is not on the resolution path from the consumer's project root).
1060
- const { __unstable__loadDesignSystem } = require(process.env.TAILWIND_NODE_PATH);
1061
- const { readFileSync } = require('fs');
1064
+ // Runs as a worker_thread (NOT a forked child process). Inputs arrive via
1065
+ // workerData; the result is written straight to the disk cache and completion
1066
+ // is signaled over the SharedArrayBuffer's control[2] (0=loading, 1=done,
1067
+ // -1=error), mirroring sort-service.ts / canonicalize-service.ts.
1068
+ const { workerData } = require('worker_threads');
1069
+ const { tailwindNodePath, cssPath: WD_CSS_PATH, cachePath: WD_CACHE_PATH, tmpPath: WD_TMP_PATH, sharedBuffer } = workerData;
1070
+ const control = new Int32Array(sharedBuffer, 0, 4);
1071
+ // On failure, write the error message into the data region so the main thread
1072
+ // can surface the real cause instead of a bare "undefined".
1073
+ const errLengthView = new DataView(sharedBuffer, 16, 4);
1074
+ const errDataArea = new Uint8Array(sharedBuffer, 20);
1075
+ function signalError(e) {
1076
+ try {
1077
+ const msg = Buffer.from(String((e && e.message) || e || 'unknown precompute error'), 'utf-8');
1078
+ const n = Math.min(msg.length, errDataArea.length);
1079
+ errDataArea.set(msg.subarray(0, n), 0);
1080
+ errLengthView.setUint32(0, n);
1081
+ } catch {}
1082
+ Atomics.store(control, 2, -1);
1083
+ Atomics.notify(control, 2);
1084
+ }
1085
+ // Resolve @tailwindcss/node via an absolute path passed in by the parent —
1086
+ // bare-specifier lookup from the worker's cwd fails under pnpm strict
1087
+ // workspaces (the module lives under node_modules/.pnpm/... which is not on the
1088
+ // resolution path from the consumer's project root).
1089
+ const { __unstable__loadDesignSystem } = require(tailwindNodePath);
1090
+ const { readFileSync, writeFileSync, renameSync } = require('fs');
1062
1091
  const { dirname, resolve } = require('path');
1063
1092
 
1064
1093
  function resolveImport(specifier, baseDir) {
@@ -1135,7 +1164,7 @@ function extractComponentClasses(cssPath, baseDir) {
1135
1164
  }
1136
1165
 
1137
1166
  async function main() {
1138
- const cssPath = process.env.TAILWIND_CSS_PATH;
1167
+ const cssPath = WD_CSS_PATH;
1139
1168
  const css = readFileSync(cssPath, 'utf-8');
1140
1169
  const base = dirname(cssPath);
1141
1170
  const ds = await __unstable__loadDesignSystem(css, { base });
@@ -1413,9 +1442,15 @@ async function main() {
1413
1442
  }
1414
1443
  }
1415
1444
 
1416
- process.stdout.write(JSON.stringify({ validClasses, canonical, order, cssProps, variantOrder, componentClasses, arbitraryEquivalents }));
1445
+ const json = JSON.stringify({ validClasses, canonical, order, cssProps, variantOrder, componentClasses, arbitraryEquivalents });
1446
+ // Atomic write: write to a unique temp path then rename, so a peer isolate
1447
+ // busy-waiting on the cache file never observes a half-written JSON.
1448
+ writeFileSync(WD_TMP_PATH, json);
1449
+ renameSync(WD_TMP_PATH, WD_CACHE_PATH);
1417
1450
  }
1418
- main().catch(e => { process.stderr.write(e.message); process.exit(1); });
1451
+ main()
1452
+ .then(() => { Atomics.store(control, 2, 1); Atomics.notify(control, 2); })
1453
+ .catch((e) => signalError(e));
1419
1454
  `;
1420
1455
  const CACHE_DIR = (0, node_path.join)((0, node_os.tmpdir)(), "oxlint-tailwindcss");
1421
1456
  /**
@@ -1455,12 +1490,6 @@ function tryReadRawCache(cachePath) {
1455
1490
  return null;
1456
1491
  }
1457
1492
  }
1458
- function writeCacheFile(contentCachePath, data) {
1459
- try {
1460
- (0, node_fs.mkdirSync)(CACHE_DIR, { recursive: true });
1461
- (0, node_fs.writeFileSync)(contentCachePath, data);
1462
- } catch {}
1463
- }
1464
1493
  const LOCK_POLL_MS = 50;
1465
1494
  const SLEEP_BUFFER = new Int32Array(new SharedArrayBuffer(4));
1466
1495
  function syncSleep(ms) {
@@ -1479,29 +1508,87 @@ function tryUnlink(path) {
1479
1508
  (0, node_fs.unlinkSync)(path);
1480
1509
  } catch {}
1481
1510
  }
1482
- /** Fork the precompute child once. Throws `DesignSystemLoadError` on failure. */
1483
- function runPrecompute(resolvedPath, tailwindNodePath, timeout) {
1511
+ /** control[2] — the worker's ready/done signal (0=loading, 1=done, -1=error). */
1512
+ const PRECOMPUTE_SIGNAL_INDEX = 2;
1513
+ const ERR_BUFFER_SIZE = 64 * 1024;
1514
+ let precomputeSeq = 0;
1515
+ /**
1516
+ * Choose the diagnostic hint based on the underlying error code. ENOMEM/EAGAIN
1517
+ * is memory pressure, not a CSS or timeout problem — the legacy hint pointed
1518
+ * users at the wrong levers (issue #24 / birdman CI report). Exported for tests.
1519
+ */
1520
+ function precomputeHint(cause) {
1521
+ const code = cause?.code;
1522
+ const message = cause instanceof Error ? cause.message : "";
1523
+ if (code === "ENOMEM" || code === "EAGAIN" || message.includes("ENOMEM")) return "The host ran out of memory spawning the precompute worker. This is rare now that precompute runs in a worker thread; if it persists, lower oxlint concurrency (e.g. `--threads`) or give the machine/CI runner more memory.";
1524
+ return "Check the CSS file (and its imports) for syntax errors. If this looks like a timeout, raise `settings.tailwindcss.timeout`.";
1525
+ }
1526
+ function precomputeLoadError(resolvedPath, cause) {
1527
+ const causeError = cause instanceof Error ? cause : void 0;
1528
+ return new DesignSystemLoadError(`Failed to precompute design system from "${resolvedPath}": ${causeError?.message ?? String(cause)}`, precomputeHint(cause), { cause: causeError });
1529
+ }
1530
+ /**
1531
+ * Run the precompute in a worker_thread (not a forked child). The worker loads
1532
+ * the design system in-process, writes the JSON straight to `cachePath`, and
1533
+ * signals completion over a SharedArrayBuffer; the main thread blocks on
1534
+ * `Atomics.wait`. Because worker_threads don't fork the host's address space,
1535
+ * this avoids the `spawnSync … ENOMEM` the fork-based path hit on
1536
+ * memory-constrained CI runners (#24).
1537
+ *
1538
+ * Throws `DesignSystemLoadError` on spawn failure, worker error, or timeout.
1539
+ * The worker writes the result itself, so this returns nothing — callers read
1540
+ * it back from `cachePath`.
1541
+ */
1542
+ function runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeout) {
1543
+ const sharedBuffer = new SharedArrayBuffer(ERR_BUFFER_SIZE);
1544
+ const control = new Int32Array(sharedBuffer, 0, 4);
1545
+ const errLengthView = new DataView(sharedBuffer, 16, 4);
1546
+ const errDataArea = new Uint8Array(sharedBuffer, 20);
1547
+ const tmpPath = `${cachePath}.tmp.${process.pid}.${node_worker_threads.threadId}.${precomputeSeq++}`;
1548
+ let worker;
1484
1549
  try {
1485
- return (0, node_child_process.execFileSync)(process.execPath, ["-e", PRECOMPUTE_SCRIPT], {
1486
- encoding: "utf-8",
1487
- timeout,
1488
- maxBuffer: 50 * 1024 * 1024,
1489
- env: {
1490
- ...process.env,
1491
- TAILWIND_CSS_PATH: resolvedPath,
1492
- TAILWIND_NODE_PATH: tailwindNodePath
1493
- },
1494
- cwd: (0, node_path.dirname)(resolvedPath)
1550
+ worker = new node_worker_threads.Worker(PRECOMPUTE_SCRIPT, {
1551
+ eval: true,
1552
+ workerData: {
1553
+ sharedBuffer,
1554
+ cssPath: resolvedPath,
1555
+ cachePath,
1556
+ tmpPath,
1557
+ tailwindNodePath
1558
+ }
1495
1559
  });
1496
1560
  } 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 });
1561
+ throw precomputeLoadError(resolvedPath, cause);
1499
1562
  }
1563
+ let workerError;
1564
+ worker.on("error", (err) => {
1565
+ workerError = err;
1566
+ });
1567
+ try {
1568
+ if (Atomics.wait(control, PRECOMPUTE_SIGNAL_INDEX, 0, timeout) === "timed-out") throw new DesignSystemLoadError(`Timed out precomputing design system from "${resolvedPath}" after ${timeout}ms.`, "Raise `settings.tailwindcss.timeout` if your machine or CI runner is slow, or verify the CSS imports resolve.");
1569
+ if (control[PRECOMPUTE_SIGNAL_INDEX] === -1) {
1570
+ const len = errLengthView.getUint32(0);
1571
+ throw precomputeLoadError(resolvedPath, len > 0 ? new Error(Buffer.from(errDataArea.slice(0, len)).toString("utf-8")) : workerError);
1572
+ }
1573
+ } finally {
1574
+ tryUnlink(tmpPath);
1575
+ worker.terminate();
1576
+ }
1577
+ }
1578
+ /**
1579
+ * Run the precompute worker, then read back the JSON it wrote to `cachePath`.
1580
+ * Used by both the lock-winner path and the uncoordinated degrade path.
1581
+ */
1582
+ function precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout) {
1583
+ runPrecomputeViaWorker(resolvedPath, tailwindNodePath, cachePath, timeout);
1584
+ const raw = tryReadRawCache(cachePath);
1585
+ if (raw === null) throw new DesignSystemLoadError(`Precompute worker finished but wrote no cache file for "${resolvedPath}".`, "This usually means the system temp directory is not writable; check its permissions.");
1586
+ return raw;
1500
1587
  }
1501
1588
  /**
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.
1589
+ * Return the raw precompute JSON for `contentHash`, spawning at most one
1590
+ * precompute worker across all isolates competing for the same hash. Whoever
1591
+ * wins the lock computes and writes the cache; the rest wait for that file.
1505
1592
  */
1506
1593
  function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath, timeout) {
1507
1594
  const lockPath = (0, node_path.join)(CACHE_DIR, `${contentHash}.lock`);
@@ -1509,7 +1596,7 @@ function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath,
1509
1596
  try {
1510
1597
  (0, node_fs.mkdirSync)(CACHE_DIR, { recursive: true });
1511
1598
  } catch {
1512
- return runPrecompute(resolvedPath, tailwindNodePath, timeout);
1599
+ return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1513
1600
  }
1514
1601
  const start = Date.now();
1515
1602
  for (;;) {
@@ -1524,12 +1611,10 @@ function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath,
1524
1611
  else syncSleep(LOCK_POLL_MS);
1525
1612
  continue;
1526
1613
  }
1527
- return runPrecompute(resolvedPath, tailwindNodePath, timeout);
1614
+ return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1528
1615
  }
1529
1616
  try {
1530
- const stdout = runPrecompute(resolvedPath, tailwindNodePath, timeout);
1531
- writeCacheFile(cachePath, stdout);
1532
- return stdout;
1617
+ return precomputeAndRead(resolvedPath, tailwindNodePath, cachePath, timeout);
1533
1618
  } finally {
1534
1619
  (0, node_fs.closeSync)(lockFd);
1535
1620
  tryUnlink(lockPath);
@@ -1539,8 +1624,8 @@ function computeWithLock(resolvedPath, tailwindNodePath, contentHash, cachePath,
1539
1624
  /**
1540
1625
  * Synchronously load and precompute the design system for a CSS file.
1541
1626
  *
1542
- * Throws `DesignSystemLoadError` on any failure (missing file, child
1543
- * process error, missing `@tailwindcss/node`, etc.). Callers catch via
1627
+ * Throws `DesignSystemLoadError` on any failure (missing file, worker
1628
+ * error, missing `@tailwindcss/node`, etc.). Callers catch via
1544
1629
  * `reportFatalDsError` to surface a single Program-level diagnostic.
1545
1630
  */
1546
1631
  function loadDesignSystemSync(cssPath, timeout) {
@@ -1556,9 +1641,9 @@ function loadDesignSystemSync(cssPath, timeout) {
1556
1641
  const cached = tryReadCache(contentCachePath);
1557
1642
  if (cached) return cached;
1558
1643
  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);
1644
+ const raw = computeWithLock(resolvedPath, TAILWIND_NODE_PATH, contentHash, contentCachePath, timeout ?? 6e4);
1560
1645
  try {
1561
- return JSON.parse(stdout);
1646
+ return JSON.parse(raw);
1562
1647
  } catch (cause) {
1563
1648
  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 });
1564
1649
  }
@@ -1650,6 +1735,17 @@ function createLazyOptions(context, compile) {
1650
1735
  //#endregion
1651
1736
  //#region src/design-system/loader.ts
1652
1737
  const dsCache = /* @__PURE__ */ new Map();
1738
+ /**
1739
+ * Memoizes DS-load FAILURES per entry point, keyed by `(resolvedPath, mtime)`.
1740
+ *
1741
+ * Without this, a single environmental failure (e.g. `spawnSync … ENOMEM` on a
1742
+ * constrained CI runner) was re-attempted on every AST node × every rule ×
1743
+ * every file — the storm that turned one failure into ~18k re-spawns and 21k
1744
+ * per-class errors (issue #24 / birdman report). Caching the failure collapses
1745
+ * it to one attempt per entry point per process. Keyed by mtime so fixing the
1746
+ * CSS (mtime changes) invalidates the entry and a fresh load is attempted.
1747
+ */
1748
+ const dsFailureCache = /* @__PURE__ */ new Map();
1653
1749
  function isEntryPointMapping(v) {
1654
1750
  if (typeof v !== "object" || v === null) return false;
1655
1751
  const m = v;
@@ -1768,7 +1864,18 @@ function getLoadedDesignSystem(cssPath, settings) {
1768
1864
  cache: cached.cache,
1769
1865
  entryPoint: resolvedPath
1770
1866
  };
1771
- const data = loadDesignSystemSync(resolvedPath, timeoutFromSettings(settings));
1867
+ const failed = dsFailureCache.get(resolvedPath);
1868
+ if (failed && failed.mtime === mtime) throw failed.error;
1869
+ let data;
1870
+ try {
1871
+ data = loadDesignSystemSync(resolvedPath, timeoutFromSettings(settings));
1872
+ } catch (err) {
1873
+ if (isFatalError(err)) dsFailureCache.set(resolvedPath, {
1874
+ error: err,
1875
+ mtime
1876
+ });
1877
+ throw err;
1878
+ }
1772
1879
  const cache = DesignSystemCache.fromPrecomputed(data);
1773
1880
  dsCache.set(resolvedPath, {
1774
1881
  cache,
@@ -1802,18 +1909,28 @@ function createLazyLoader(context) {
1802
1909
  let debugInitialized = false;
1803
1910
  let lastFilePath;
1804
1911
  let lastResult;
1912
+ let lastError;
1805
1913
  return () => {
1806
1914
  const filePath = safeFilename(context);
1807
- if (filePath !== void 0 && filePath === lastFilePath && lastResult) return lastResult;
1915
+ if (filePath !== void 0 && filePath === lastFilePath) {
1916
+ if (lastError) throw lastError;
1917
+ if (lastResult) return lastResult;
1918
+ }
1808
1919
  const ruleOptionEntry = safeOptions(context)?.entryPoint;
1809
1920
  const settings = safeSettings(context);
1810
1921
  if (!debugInitialized && settings) {
1811
1922
  debugInitialized = true;
1812
1923
  setDebugEnabled(isDebugEnabled(settings));
1813
1924
  }
1814
- const cssPath = resolveEntryPointForFile(ruleOptionEntry, entryPointFromSettings(settings), filePath);
1815
1925
  lastFilePath = filePath;
1816
- lastResult = getLoadedDesignSystem(cssPath, settings);
1926
+ lastResult = void 0;
1927
+ lastError = void 0;
1928
+ try {
1929
+ lastResult = getLoadedDesignSystem(resolveEntryPointForFile(ruleOptionEntry, entryPointFromSettings(settings), filePath), settings);
1930
+ } catch (err) {
1931
+ if (isFatalError(err) && err instanceof Error) lastError = err;
1932
+ throw err;
1933
+ }
1817
1934
  if (filePath) debugLog(`${(0, node_path.relative)(process.cwd(), filePath)} → ${(0, node_path.relative)(process.cwd(), lastResult.entryPoint)}`);
1818
1935
  return lastResult;
1819
1936
  };