Skip to content

Commit d190343

Browse files
authored
Use wasm as a fallback for @tailwindcss/oxide (#20383)
Right now, we use Rust for `@tailwindcss/oxide` which has 2 responsibilities: 1. Traverse the file system and figure out which files need to be scanned based on auto source detection and `@source` directives. 2. Given those files, extract possible Tailwind CSS classes which we call candidates. Since this is using native code, we use napi-rs to get native `.node` files on a per platform / arch basis. So far so good, however, if you are on an OS that doesn't have a prebuilt binary, you will receive an error that might look like this: ``` Error: Cannot find native binding. npm has a bug related to optional dependencies (npm/cli#4828). Please try `npm i` again after removing both package-lock.json and node_modules directory. at Object.<anonymous> (/private/var/folders/1k/bdv8blv93xq7qgwjdwc9z88h0000gn/T/tailwind-integrationspYHIVP/node_modules/.pnpm/@tailwindcss+oxide@file+..+..+..+..+..+..+..+Users+robin+github.com+tailwindlabs+tailwi_47ae1688f61c719f66c73e2ff35e430f/node_modules/@tailwindcss/oxide/index.js:573:19) at Module._compile (node:internal/modules/cjs/loader:1829:14) at Object..js (node:internal/modules/cjs/loader:1969:10) at Module.load (node:internal/modules/cjs/loader:1552:32) at Module._load (node:internal/modules/cjs/loader:1354:12) at wrapModuleLoad (node:internal/modules/cjs/loader:255:19) at Module.require (node:internal/modules/cjs/loader:1575:12) at require (node:internal/modules/helpers:191:16) at file:///private/var/folders/1k/bdv8blv93xq7qgwjdwc9z88h0000gn/T/tailwind-integrationspYHIVP/index.mjs:5:19 at ModuleJob.run (node:internal/modules/esm/module_job:437:25) { cause: Error: Cannot find module '@tailwindcss/oxide-darwin-arm64' ``` This means that we have to add support for these platforms, and there are some open PRs related to this, which could be closed by this PR: - #20327 - #20276 - #20201 Today we already have support for the big platforms out there: - Windows arm64 - Windows x64 - macOS arm64 - macOS x64 But then it starts to get a bit out of hand once we start looking at Linux based versions: - Android arm eabi - Android arm64 - Linux arm64 gnu - Linux arm64 gnueabihf - Linux arm64 musl - Linux x64 gnu - Linux x64 musl - freebsd x64 ... and then we have the pending list from the 3 PRs linked above. Adding support for all of these is not the end of the world, but it gets complex if we need to keep supporting more and more. Right now we rely on a bunch of non-default napi-rs setup in CI just to support these other platforms. This PR solves that by using the `wasm32-wasi` build as a universal fallback. The napi-rs generated loader already knows how to fall back to `@tailwindcss/oxide-wasm32-wasi`, but that package declared `"cpu": ["wasm32"]`, so npm/pnpm never installed it on real hardware. Removing that restriction means the package is installed everywhere, and the loader picks it up whenever no native binding exists. This PR also fixes a `UVWASI_EACCES` crash on sandboxed platforms (OpenHarmony, Android): the generated wasm loader preopens `/`, which those sandboxes deny, so the fallback failed to load on exactly the platforms that need it (see [this comment](#20276 (comment))). We patch `@napi-rs/cli`'s codegen templates via `pnpm patch` to retry with narrower preopens (`/` → cwd → none). On such platforms, scanning is limited to files under the current working directory. ## Test plan Added two integration tests: 1. Trick pnpm (via `supportedArchitectures`) into installing for a platform we explicitly don't support, and assert `@tailwindcss/oxide` loads the wasm binding and scans files from disk. 2. Simulate a sandbox that denies preopening `/`, and assert the wasm binding still loads and scans. [ci-all]
1 parent 05c3a87 commit d190343

6 files changed

Lines changed: 270 additions & 7 deletions

File tree

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
# `@tailwindcss/oxide-wasm32-wasi`
22

3-
This is the **wasm32-wasip1-threads** binary for `@tailwindcss/oxide`
3+
This is the **wasm32-wasip1-threads** build of `@tailwindcss/oxide`

crates/node/npm/wasm32-wasi/package.json

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
{
22
"name": "@tailwindcss/oxide-wasm32-wasi",
33
"version": "4.3.3",
4-
"cpu": [
5-
"wasm32"
6-
],
74
"main": "tailwindcss-oxide.wasi.cjs",
85
"files": [
96
"tailwindcss-oxide.wasm32-wasi.wasm",

integrations/oxide/wasm.test.ts

Lines changed: 185 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { css, js, json, test } from '../utils'
1+
import { css, js, json, test, yaml } from '../utils'
22

33
// This test runs the wasm build using the `node:wasi` runtime.
44
//
@@ -57,3 +57,187 @@ testFn(
5757
`)
5858
},
5959
)
60+
61+
testFn(
62+
'`@tailwindcss/oxide` falls back to the wasm build when no native binding is available',
63+
{
64+
fs: {
65+
'package.json': json`
66+
{
67+
"dependencies": {
68+
"@tailwindcss/oxide": "workspace:^"
69+
}
70+
}
71+
`,
72+
'pnpm-workspace.yaml': yaml`
73+
# Trick pnpm in only supporting an architecture that @tailwindcss/oxide
74+
# doesn't support, and therefore should fallback to the wasm version.
75+
supportedArchitectures:
76+
os:
77+
- openbsd
78+
cpu:
79+
- x64
80+
`,
81+
'src/index.js': js`
82+
const className = "content-['src/index.js']"
83+
module.exports = { className }
84+
`,
85+
'index.mjs': js`
86+
import { createRequire } from 'node:module'
87+
import { join } from 'node:path'
88+
89+
let require = createRequire(import.meta.url)
90+
let { Scanner } = require('@tailwindcss/oxide')
91+
92+
let loaded = Object.keys(require.cache)
93+
94+
let scanner = new Scanner({
95+
sources: [
96+
{
97+
base: join(process.cwd(), 'src'),
98+
pattern: '**/*',
99+
negated: false,
100+
},
101+
],
102+
})
103+
104+
console.log(
105+
JSON.stringify({
106+
native: loaded.filter((file) => file.endsWith('.node')),
107+
wasi: loaded.some((file) => file.endsWith('tailwindcss-oxide.wasi.cjs')),
108+
candidates: scanner.scan(),
109+
}),
110+
)
111+
process.exit()
112+
`,
113+
},
114+
},
115+
async ({ expect, exec }) => {
116+
// Since vitest runs under `pnpm run`, pnpm's bin shims export a NODE_PATH
117+
// that includes the repository's hidden hoist directory
118+
// (`node_modules/.pnpm/node_modules`), which links every workspace package,
119+
// including all native `@tailwindcss/oxide-*` bindings.
120+
//
121+
// Node uses `NODE_PATH` exactly when the local `node_modules` lookup fails,
122+
// which would defeat the simulated unsupported platform, so clear it.
123+
let output = await exec(`node index.mjs`, { env: { NODE_PATH: '' } })
124+
let { native, wasi, candidates } = JSON.parse(output)
125+
126+
// No native binding was installed or loaded, ...
127+
expect(native).toEqual([])
128+
129+
// ... the wasm32-wasi binding is what actually loaded, ...
130+
expect(wasi).toBe(true)
131+
132+
// ... and scanning real files on disk works through it.
133+
expect(candidates).toMatchInlineSnapshot(`
134+
[
135+
"className",
136+
"const",
137+
"content-['src/index.js']",
138+
"exports",
139+
]
140+
`)
141+
},
142+
)
143+
144+
testFn(
145+
'the wasm build loads even when preopening the filesystem root is denied',
146+
{
147+
fs: {
148+
'package.json': json`
149+
{
150+
"dependencies": {
151+
"@tailwindcss/oxide": "workspace:^"
152+
}
153+
}
154+
`,
155+
'pnpm-workspace.yaml': yaml`
156+
# Trick pnpm in only supporting an architecture that @tailwindcss/oxide
157+
# doesn't support, and therefore should fallback to the wasm version.
158+
supportedArchitectures:
159+
os:
160+
- openbsd
161+
cpu:
162+
- x64
163+
`,
164+
// The wasm bindings generated by `@napi-rs/cli` preopen the filesystem
165+
// root, which sandboxed platforms (e.g. OpenHarmony, Android) deny with
166+
// `UVWASI_EACCES`, making the wasm fallback fail to load on exactly the
167+
// platforms that need it.
168+
//
169+
// We patch `@napi-rs/cli`'s templates to retry with narrower preopens
170+
// (see `patches/@napi-rs__cli@3.7.4.patch`). Simulate such a sandbox by
171+
// denying `/` preopens.
172+
'preload.cjs': js`
173+
const wasi = require('node:wasi')
174+
const RealWASI = wasi.WASI
175+
176+
wasi.WASI = class WASI extends RealWASI {
177+
constructor(options) {
178+
if (options?.preopens?.['/'] !== undefined) {
179+
const error = new Error('UVWASI_EACCES, uvwasi_init')
180+
error.code = 'UVWASI_EACCES'
181+
error.syscall = 'uvwasi_init'
182+
throw error
183+
}
184+
super(options)
185+
}
186+
}
187+
`,
188+
'src/index.js': js`
189+
const className = "content-['src/index.js']"
190+
module.exports = { className }
191+
`,
192+
'index.mjs': js`
193+
import { createRequire } from 'node:module'
194+
import { join } from 'node:path'
195+
196+
let require = createRequire(import.meta.url)
197+
let { Scanner } = require('@tailwindcss/oxide')
198+
199+
let loaded = Object.keys(require.cache)
200+
201+
let scanner = new Scanner({
202+
sources: [
203+
{
204+
base: join(process.cwd(), 'src'),
205+
pattern: '**/*',
206+
negated: false,
207+
},
208+
],
209+
})
210+
211+
console.log(
212+
JSON.stringify({
213+
wasi: loaded.some((file) => file.endsWith('tailwindcss-oxide.wasi.cjs')),
214+
candidates: scanner.scan(),
215+
}),
216+
)
217+
process.exit()
218+
`,
219+
},
220+
},
221+
async ({ expect, exec }) => {
222+
// See the note about NODE_PATH in the test above.
223+
let output = await exec(`node --require ./preload.cjs index.mjs`, { env: { NODE_PATH: '' } })
224+
225+
// Only parse the first line, because Node prints an `ExperimentalWarning`
226+
// about WASI to stderr, which `exec` appends to the output.
227+
let { wasi, candidates } = JSON.parse(output.trim().split('\n')[0])
228+
229+
// The wasm32-wasi binding loaded despite `/` being denied, ...
230+
expect(wasi).toBe(true)
231+
232+
// ... and scanning files under the current working directory still works
233+
// through the narrower preopen.
234+
expect(candidates).toMatchInlineSnapshot(`
235+
[
236+
"className",
237+
"const",
238+
"content-['src/index.js']",
239+
"exports",
240+
]
241+
`)
242+
},
243+
)

patches/@napi-rs__cli@3.7.4.patch

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
diff --git a/dist/cli.js b/dist/cli.js
2+
index c4c2d568bc070c07dbf3a1f9f4a0c946466668cf..353bbca86e3261a2ba9a8fc56dc612c7c84dab6d 100755
3+
--- a/dist/cli.js
4+
+++ b/dist/cli.js
5+
@@ -1,4 +1,13 @@
6+
#!/usr/bin/env node
7+
+// PATCHED (see patches/@napi-rs__cli@3.7.4.patch): the embedded wasi loader
8+
+// and worker templates below retry `new WASI(...)` with narrower preopens,
9+
+// because preopening `/` throws `UVWASI_EACCES` on sandboxed platforms (e.g.
10+
+// OpenHarmony), which would make the generated wasm binding fail to load.
11+
+//
12+
+// The same templates also exist in `dist/index.js` and `dist/index.cjs` (the
13+
+// programmatic API). Those are intentionally NOT patched because we only
14+
+// build through the `napi` bin, which runs this file. If we ever start using
15+
+// the programmatic API, update the patch to cover those bundles too.
16+
import { createRequire } from "node:module";
17+
import { Cli, Command, Option } from "clipanion";
18+
import path, { basename, dirname, isAbsolute, join, parse, resolve } from "node:path";
19+
@@ -1021,13 +1030,25 @@ const {
20+
21+
const __rootDir = __nodePath.parse(process.cwd()).root
22+
23+
-const __wasi = new __nodeWASI({
24+
- version: 'preview1',
25+
- env: process.env,
26+
- preopens: {
27+
- [__rootDir]: __rootDir,
28+
+const __wasi = (() => {
29+
+ // Preopening '/' fails with UVWASI_EACCES in sandboxed environments (e.g.
30+
+ // OpenHarmony, Android), which would prevent the wasm binding from loading
31+
+ // at all. Retry with narrower preopens instead. Without any preopens the
32+
+ // binding still loads; only file system access is unavailable.
33+
+ let lastError = null
34+
+ for (const dir of [__rootDir, process.cwd(), null]) {
35+
+ try {
36+
+ return new __nodeWASI({
37+
+ version: 'preview1',
38+
+ env: process.env,
39+
+ preopens: dir === null ? {} : { [dir]: dir },
40+
+ })
41+
+ } catch (error) {
42+
+ lastError = error
43+
+ }
44+
}
45+
-})
46+
+ throw lastError
47+
+})()
48+
49+
const __emnapiContext = __emnapiGetDefaultContext()
50+
51+
@@ -1151,13 +1172,22 @@ const __rootDir = parse(process.cwd()).root;
52+
53+
const handler = new MessageHandler({
54+
onLoad({ wasmModule, wasmMemory }) {
55+
- const wasi = new WASI({
56+
- version: 'preview1',
57+
- env: process.env,
58+
- preopens: {
59+
- [__rootDir]: __rootDir,
60+
- },
61+
- });
62+
+ // Keep in sync with the preopen fallback in the main-thread loader.
63+
+ const wasi = (() => {
64+
+ let lastError = null;
65+
+ for (const dir of [__rootDir, process.cwd(), null]) {
66+
+ try {
67+
+ return new WASI({
68+
+ version: 'preview1',
69+
+ env: process.env,
70+
+ preopens: dir === null ? {} : { [dir]: dir },
71+
+ });
72+
+ } catch (error) {
73+
+ lastError = error;
74+
+ }
75+
+ }
76+
+ throw lastError;
77+
+ })();
78+
79+
return instantiateNapiModuleSync(wasmModule, {
80+
childThread: true,

pnpm-lock.yaml

Lines changed: 3 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pnpm-workspace.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ packages:
66
- 'integrations'
77

88
patchedDependencies:
9+
'@napi-rs/cli@3.7.4': patches/@napi-rs__cli@3.7.4.patch
910
'@parcel/watcher@2.6.0': patches/@parcel__watcher@2.6.0.patch
1011
lightningcss@1.33.0: patches/lightningcss@1.33.0.patch
1112

0 commit comments

Comments
 (0)