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