Skip to content

A fast, helpful, and open-source document parser

make wasm work in the browser

Logan Markewich15c957a4e9ae
diff --git a/.github/workflows/ci-wasm.yml b/.github/workflows/ci-wasm.yml
index 2b3657d..dd5544a 100644
--- a/.github/workflows/ci-wasm.yml
+++ b/.github/workflows/ci-wasm.yml
@@ -25,6 +25,10 @@ jobs:
steps:
- uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
diff --git a/.github/workflows/release-wasm.yml b/.github/workflows/release-wasm.yml
index 1bff6b0..2305728 100644
--- a/.github/workflows/release-wasm.yml
+++ b/.github/workflows/release-wasm.yml
@@ -41,6 +41,10 @@ jobs:
steps:
- uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
diff --git a/crates/liteparse-wasm/src/lib.rs b/crates/liteparse-wasm/src/lib.rs
index a134e11..76f3478 100644
--- a/crates/liteparse-wasm/src/lib.rs
+++ b/crates/liteparse-wasm/src/lib.rs
@@ -5,6 +5,8 @@
//! - `LiteParse` class with `new(config)`, `parse(Uint8Array)`
//! - JS-side OCR callback bridge (any object with an async `recognize` method)
+mod wasi_stubs;
+
use std::pin::Pin;
use js_sys::{Function, Reflect, Uint8Array};
diff --git a/crates/liteparse-wasm/src/wasi_stubs.rs b/crates/liteparse-wasm/src/wasi_stubs.rs
new file mode 100644
index 0000000..41c3612
--- /dev/null
+++ b/crates/liteparse-wasm/src/wasi_stubs.rs
@@ -0,0 +1,87 @@
+//! Stub implementations of libc functions that pdfium's statically-linked
+//! wasi-libc expects at runtime under the "env" module namespace.
+//!
+//! WASI preview1 syscalls (wasi_snapshot_preview1::*) cannot be stubbed from
+//! Rust because they live in a different WASM import module namespace. Those
+//! are provided in JavaScript — see packages/wasm/scripts/patch-wasi-imports.js.
+
+// ---------------------------------------------------------------------------
+// env:: stubs (libc / pthreads)
+// ---------------------------------------------------------------------------
+
+#[unsafe(no_mangle)]
+pub extern "C" fn getpid() -> i32 {
+ 1
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn pthread_mutex_init(_mutex: *mut u8, _attr: *const u8) -> i32 {
+ 0
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn pthread_mutex_lock(_mutex: *mut u8) -> i32 {
+ 0
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn pthread_mutex_unlock(_mutex: *mut u8) -> i32 {
+ 0
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn pthread_mutex_destroy(_mutex: *mut u8) -> i32 {
+ 0
+}
+
+// ---------------------------------------------------------------------------
+// setjmp / longjmp support (new WASM exception handling SjLj model)
+//
+// Chromium's clang uses the new WASM SjLj lowering where:
+// - __c_longjmp is a WebAssembly.Tag with 1 param (env: i32)
+// - __wasm_setjmp(env, label, table) — 3 params
+// - __wasm_setjmp_test(table, env) -> label — 2 params
+//
+// The table is a flat array of (env, label) pairs on the stack, zero-terminated.
+// ---------------------------------------------------------------------------
+
+#[unsafe(no_mangle)]
+pub extern "C" fn __wasm_setjmp(env: u32, label: u32, table: *mut u32) {
+ unsafe {
+ let mut i = 0;
+ loop {
+ if *table.add(i) == 0 {
+ *table.add(i) = env;
+ *table.add(i + 1) = label;
+ *table.add(i + 2) = 0; // sentinel
+ return;
+ }
+ i += 2;
+ }
+ }
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn __wasm_setjmp_test(table: *const u32, env: u32) -> u32 {
+ unsafe {
+ let mut i = 0;
+ loop {
+ let stored_env = *table.add(i);
+ if stored_env == 0 {
+ return 0;
+ }
+ if stored_env == env {
+ return *table.add(i + 1);
+ }
+ i += 2;
+ }
+ }
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn __wasm_longjmp(_env: *mut u8, _val: i32) {
+ // longjmp throws the __c_longjmp WASM exception tag, which we can't do
+ // from Rust. Trap instead — in practice, FreeType's setjmp error recovery
+ // rarely triggers during normal PDF parsing.
+ core::arch::wasm32::unreachable();
+}
diff --git a/crates/pdfium-sys/build.rs b/crates/pdfium-sys/build.rs
index ff1e19a..f2b56ce 100644
--- a/crates/pdfium-sys/build.rs
+++ b/crates/pdfium-sys/build.rs
@@ -3,7 +3,7 @@ use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
-const PDFIUM_RELEASE_TAG: &str = "chromium/7841";
+const PDFIUM_RELEASE_TAG: &str = "chromium/7846";
const PDFIUM_RELEASE_URL: &str = "https://github.com/run-llama/pdfium-binaries/releases/download";
fn main() {
@@ -31,7 +31,17 @@ fn main() {
// For wasm targets, pdfium is shipped as a static archive (libpdfium.a)
// and linked statically into the final .wasm module. There is no
// dynamic loading and no need to copy any shared library.
+ //
+ // The WASI sysroot libraries (libc, libc++, libc++abi, etc.) must also
+ // be linked so that all C/C++ runtime symbols are resolved. Without
+ // them, those symbols appear as unresolved "env::" imports in the
+ // browser, making the .wasm unusable.
println!("cargo:rustc-link-lib=static=pdfium");
+ println!("cargo:rustc-link-lib=static=c");
+ println!("cargo:rustc-link-lib=static=c++");
+ println!("cargo:rustc-link-lib=static=c++abi");
+ println!("cargo:rustc-link-lib=static=wasi-emulated-mman");
+ println!("cargo:rustc-link-lib=static=wasi-emulated-signal");
println!("cargo:lib_path={}", lib_dir.display());
} else {
// On Windows MSVC the import library is named `pdfium.dll.lib`, so
@@ -137,7 +147,7 @@ fn pdfium_asset_stem() -> &'static str {
"x86_64-pc-windows-msvc" | "x86_64-pc-windows-gnu" => "pdfium-win-x64",
"aarch64-pc-windows-msvc" => "pdfium-win-arm64",
"i686-pc-windows-msvc" | "i686-pc-windows-gnu" => "pdfium-win-x86",
- "wasm32-unknown-unknown" | "wasm32-wasip1" => "pdfium-wasm",
+ "wasm32-unknown-unknown" | "wasm32-wasip1" => "pdfium-wasi-wasm",
other => panic!("unsupported target for pdfium auto-download: {other}"),
}
}
diff --git a/packages/wasm/package.json b/packages/wasm/package.json
index df07ec2..5a46e19 100644
--- a/packages/wasm/package.json
+++ b/packages/wasm/package.json
@@ -19,9 +19,9 @@
"LICENSE"
],
"scripts": {
- "build": "wasm-pack build ../../crates/liteparse-wasm --release --target web --out-dir ../../packages/wasm/pkg --out-name liteparse_wasm",
- "build:bundler": "wasm-pack build ../../crates/liteparse-wasm --release --target bundler --out-dir ../../packages/wasm/pkg --out-name liteparse_wasm",
- "build:nodejs": "wasm-pack build ../../crates/liteparse-wasm --release --target nodejs --out-dir ../../packages/wasm/pkg --out-name liteparse_wasm",
+ "build": "wasm-pack build ../../crates/liteparse-wasm --release --target web --out-dir ../../packages/wasm/pkg --out-name liteparse_wasm && node scripts/patch-wasi-imports.js",
+ "build:bundler": "wasm-pack build ../../crates/liteparse-wasm --release --target bundler --out-dir ../../packages/wasm/pkg --out-name liteparse_wasm && node scripts/patch-wasi-imports.js",
+ "build:nodejs": "wasm-pack build ../../crates/liteparse-wasm --release --target nodejs --out-dir ../../packages/wasm/pkg --out-name liteparse_wasm && node scripts/patch-wasi-imports.js",
"clean": "rm -rf pkg",
"prepublishOnly": "npm run build"
},
diff --git a/packages/wasm/scripts/patch-wasi-imports.js b/packages/wasm/scripts/patch-wasi-imports.js
new file mode 100644
index 0000000..e5057b4
--- /dev/null
+++ b/packages/wasm/scripts/patch-wasi-imports.js
@@ -0,0 +1,121 @@
+#!/usr/bin/env node
+/**
+ * Post-build script that patches the wasm-bindgen generated JS glue to
+ * provide stub implementations of WASI preview1 syscalls and any remaining
+ * "env" imports.
+ *
+ * The WASI syscalls (wasi_snapshot_preview1::*) are baked into the WASM binary
+ * by wasi-libc and cannot be resolved at Rust link time. Instead we inject
+ * no-op / error-returning stubs at the JS level so the WASM module can
+ * instantiate in the browser.
+ */
+
+import { readFileSync, writeFileSync } from "fs";
+import { join, dirname } from "path";
+import { fileURLToPath } from "url";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const GLUE_PATH = join(__dirname, "..", "pkg", "liteparse_wasm.js");
+
+let source = readFileSync(GLUE_PATH, "utf-8");
+
+// WASI errno constants
+const ERRNO_SUCCESS = 0;
+const ERRNO_BADF = 8;
+const ERRNO_NOENT = 44;
+const ERRNO_NOSYS = 52;
+
+// The stubs object we'll inject into the JS source
+const STUBS_CODE = `
+// --- WASI / env stubs (injected by patch-wasi-imports.js) ---
+const __wasi_stubs = {
+ // wasi_snapshot_preview1
+ environ_sizes_get(count, buf_size) {
+ const view = new DataView(wasm.memory.buffer);
+ view.setUint32(count, 0, true);
+ view.setUint32(buf_size, 0, true);
+ return ${ERRNO_SUCCESS};
+ },
+ environ_get() { return ${ERRNO_SUCCESS}; },
+ clock_time_get(clock_id, precision, time) {
+ const view = new DataView(wasm.memory.buffer);
+ view.setBigUint64(time, BigInt(0), true);
+ return ${ERRNO_SUCCESS};
+ },
+ fd_close(fd) { return fd <= 2 ? ${ERRNO_SUCCESS} : ${ERRNO_BADF}; },
+ fd_fdstat_get(fd, stat) {
+ if (fd > 2) return ${ERRNO_BADF};
+ // Report stdio fds as character devices (filetype=2, no special flags)
+ const view = new DataView(wasm.memory.buffer);
+ view.setUint8(stat, 2); // filetype = CHARACTER_DEVICE
+ view.setUint16(stat + 2, 0, true); // fdflags = 0
+ view.setBigUint64(stat + 8, BigInt(0), true); // rights_base
+ view.setBigUint64(stat + 16, BigInt(0), true); // rights_inheriting
+ return ${ERRNO_SUCCESS};
+ },
+ fd_fdstat_set_flags() { return ${ERRNO_NOSYS}; },
+ fd_filestat_get() { return ${ERRNO_BADF}; },
+ fd_filestat_set_size() { return ${ERRNO_BADF}; },
+ fd_prestat_get() { return ${ERRNO_BADF}; },
+ fd_prestat_dir_name() { return ${ERRNO_BADF}; },
+ fd_read() { return ${ERRNO_BADF}; },
+ fd_readdir() { return ${ERRNO_BADF}; },
+ fd_seek() { return ${ERRNO_NOSYS}; },
+ fd_sync() { return ${ERRNO_NOSYS}; },
+ fd_write(fd, iovs, iovs_len, nwritten) {
+ // Support stdout (1) and stderr (2) — compute total bytes and discard
+ if (fd !== 1 && fd !== 2) return ${ERRNO_BADF};
+ const view = new DataView(wasm.memory.buffer);
+ const mem = new Uint8Array(wasm.memory.buffer);
+ let total = 0;
+ for (let i = 0; i < iovs_len; i++) {
+ const ptr = view.getUint32(iovs + i * 8, true);
+ const len = view.getUint32(iovs + i * 8 + 4, true);
+ // Optionally log stderr to console
+ if (fd === 2 && len > 0) {
+ try {
+ const text = new TextDecoder().decode(mem.subarray(ptr, ptr + len));
+ console.warn("[pdfium]", text);
+ } catch (_) {}
+ }
+ total += len;
+ }
+ view.setUint32(nwritten, total, true);
+ return ${ERRNO_SUCCESS};
+ },
+ path_filestat_get() { return ${ERRNO_NOENT}; },
+ path_open() { return ${ERRNO_NOENT}; },
+ path_remove_directory() { return ${ERRNO_NOSYS}; },
+ path_unlink_file() { return ${ERRNO_NOSYS}; },
+ proc_exit(code) { throw new Error("WASI proc_exit called with code " + code); },
+};
+
+const __env_stubs = {
+ // __c_longjmp is a WASM exception handling tag used for setjmp/longjmp.
+ // It must be a WebAssembly.Tag, not a function.
+ __c_longjmp: new WebAssembly.Tag({ parameters: ["i32"] }),
+};
+// --- end stubs ---
+`;
+
+// 1. Remove the top-level `import ... from "env"` and `import ... from "wasi_snapshot_preview1"`
+// These are ES module imports that can't resolve in a browser.
+source = source.replace(/^import \* as import\d+ from "(?:env|wasi_snapshot_preview1)";?\n/gm, "");
+
+// 2. Inject stubs before the __wbg_get_imports function
+source = source.replace(
+ "function __wbg_get_imports() {",
+ STUBS_CODE + "\nfunction __wbg_get_imports() {"
+);
+
+// 3. In the return object of __wbg_get_imports, replace the env/wasi entries
+// with our stubs objects.
+// The generated code has duplicate "wasi_snapshot_preview1" keys and an "env" key.
+// We replace all of them with single entries pointing to our stubs.
+source = source.replace(
+ /("env": import\d+,\n(?:\s+"wasi_snapshot_preview1": import\d+,?\n)+)/,
+ `"env": __env_stubs,\n "wasi_snapshot_preview1": __wasi_stubs,\n`
+);
+
+writeFileSync(GLUE_PATH, source, "utf-8");
+console.log("Patched WASI/env stubs into", GLUE_PATH);