fix(wasm-runtime): avoid wasm-util from tree shaking by rollup (#2810)

* fix(wasm-runtime): avoid wasm-util from tree shaking by rollup

* fix filename
This commit is contained in:
LongYinan 2025-08-06 21:55:48 -07:00 committed by GitHub
parent ce4699025b
commit 1e30088198
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 88 additions and 30 deletions

View File

@ -970,6 +970,8 @@ Generated by [AVA](https://avajs.dev).
export declare function testSerdeRoundtrip(data: any): any␊
export declare function testWorkers(amount: number, completeCallback: ((err: Error | null, ) => void)): void␊
export declare function threadsafeFunctionBuildThrowErrorWithStatus(cb: (arg?: unknown) => unknown): void␊
export declare function threadsafeFunctionClosureCapture(defaultValue: Animal, func: (arg: Animal) => void): void␊

View File

@ -14,6 +14,7 @@ const {
tsfnReturnPromise,
tsfnReturnPromiseTimeout,
asyncTaskReadFile,
testWorkers,
}: typeof import('../index.cjs') = await import('../example.wasi-browser')
describe('NAPI-RS wasi browser test', function () {
@ -44,8 +45,7 @@ describe('NAPI-RS wasi browser test', function () {
return Promise.resolve(value + 2)
})
expect(value).toBe(5)
// eslint-disable-next-line @typescript-eslint/no-floating-promises
expect(
await expect(
tsfnReturnPromiseTimeout((err, value) => {
if (err) {
throw err
@ -66,4 +66,18 @@ describe('NAPI-RS wasi browser test', function () {
const value = await asyncTaskReadFile('/test.txt')
expect(value.toString('utf8')).toBe('hello world')
})
it('testWorkers should not throw', async () => {
const { resolve, reject, promise } = Promise.withResolvers()
expect(() =>
testWorkers(10, (err) => {
if (err) {
reject(err)
} else {
resolve()
}
}),
).not.toThrow()
await expect(promise).resolves.toBeUndefined()
})
})

View File

@ -335,6 +335,7 @@ export const testEscapedQuotesInComments = __napiModule.exports.testEscapedQuote
export const testSerdeBigNumberPrecision = __napiModule.exports.testSerdeBigNumberPrecision
export const testSerdeBufferBytes = __napiModule.exports.testSerdeBufferBytes
export const testSerdeRoundtrip = __napiModule.exports.testSerdeRoundtrip
export const testWorkers = __napiModule.exports.testWorkers
export const threadsafeFunctionBuildThrowErrorWithStatus = __napiModule.exports.threadsafeFunctionBuildThrowErrorWithStatus
export const threadsafeFunctionClosureCapture = __napiModule.exports.threadsafeFunctionClosureCapture
export const threadsafeFunctionFatalMode = __napiModule.exports.threadsafeFunctionFatalMode

View File

@ -380,6 +380,7 @@ module.exports.testEscapedQuotesInComments = __napiModule.exports.testEscapedQuo
module.exports.testSerdeBigNumberPrecision = __napiModule.exports.testSerdeBigNumberPrecision
module.exports.testSerdeBufferBytes = __napiModule.exports.testSerdeBufferBytes
module.exports.testSerdeRoundtrip = __napiModule.exports.testSerdeRoundtrip
module.exports.testWorkers = __napiModule.exports.testWorkers
module.exports.threadsafeFunctionBuildThrowErrorWithStatus = __napiModule.exports.threadsafeFunctionBuildThrowErrorWithStatus
module.exports.threadsafeFunctionClosureCapture = __napiModule.exports.threadsafeFunctionClosureCapture
module.exports.threadsafeFunctionFatalMode = __napiModule.exports.threadsafeFunctionFatalMode

View File

@ -780,6 +780,7 @@ module.exports.testEscapedQuotesInComments = nativeBinding.testEscapedQuotesInCo
module.exports.testSerdeBigNumberPrecision = nativeBinding.testSerdeBigNumberPrecision
module.exports.testSerdeBufferBytes = nativeBinding.testSerdeBufferBytes
module.exports.testSerdeRoundtrip = nativeBinding.testSerdeRoundtrip
module.exports.testWorkers = nativeBinding.testWorkers
module.exports.threadsafeFunctionBuildThrowErrorWithStatus = nativeBinding.threadsafeFunctionBuildThrowErrorWithStatus
module.exports.threadsafeFunctionClosureCapture = nativeBinding.threadsafeFunctionClosureCapture
module.exports.threadsafeFunctionFatalMode = nativeBinding.threadsafeFunctionFatalMode

View File

@ -931,6 +931,8 @@ export declare function testSerdeBufferBytes(obj: object): bigint
export declare function testSerdeRoundtrip(data: any): any
export declare function testWorkers(amount: number, completeCallback: ((err: Error | null, ) => void)): void
export declare function threadsafeFunctionBuildThrowErrorWithStatus(cb: (arg?: unknown) => unknown): void
export declare function threadsafeFunctionClosureCapture(defaultValue: Animal, func: (arg: Animal) => void): void

View File

@ -8,7 +8,7 @@
#[cfg(not(target_family = "wasm"))]
use napi::bindgen_prelude::create_custom_tokio_runtime;
use napi::bindgen_prelude::{JsObjectValue, Object, Result, Symbol};
// pub use napi_shared::*;
pub use napi_shared::*;
#[macro_use]
extern crate napi_derive;
@ -94,3 +94,4 @@ mod threadsafe_function;
mod transparent;
mod r#type;
mod typed_array;
mod wasm;

42
examples/napi/src/wasm.rs Normal file
View File

@ -0,0 +1,42 @@
use std::{thread, time::Duration};
use napi::{
threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode},
Error, Status,
};
pub fn worker(id: u32) {
println!("Worker {} started", id);
thread::sleep(Duration::from_millis(500));
thread::sleep(Duration::from_millis(200));
println!("Worker {} finished", id);
}
#[napi]
pub fn test_workers(amount: u32, complete_callback: ThreadsafeFunction<(), ()>) {
println!("Starting parallel workers...");
let mut handles = vec![];
for i in 0..amount {
let handle = thread::spawn(move || {
worker(i);
});
handles.push(handle);
}
thread::spawn(move || {
for handle in handles {
if let Err(e) = handle.join() {
complete_callback.call(
Err(Error::new(
Status::GenericFailure,
format!("Worker panicked {:?}", e),
)),
ThreadsafeFunctionCallMode::NonBlocking,
);
}
}
complete_callback.call(Ok(()), ThreadsafeFunctionCallMode::NonBlocking);
});
}

View File

@ -7,6 +7,7 @@ import {
tsfnReturnPromise,
__fs,
asyncTaskReadFile,
testWorkers,
} from './example.wasi-browser'
global.Buffer = Buffer
@ -33,3 +34,11 @@ asyncTaskReadFile('/test.txt')
.catch((err) => {
console.error(err)
})
testWorkers(4, (err) => {
if (err) {
console.error(err)
} else {
console.log('All workers completed')
}
})

View File

@ -186,7 +186,7 @@ const decodeValue = (memfs, payload, type) => {
* @returns {(e: { data: { __fs__: { sab: Int32Array, type: keyof import('memfs').IFs, payload: any[] } } }) => void}
*/
// oxlint-disable-next-line no-unused-vars -- fixed in an upcoming release
module.exports.createOnMessage = (fs) =>
export const createOnMessage = (fs) =>
function onMessage(e) {
if (e.data.__fs__) {
/**
@ -221,7 +221,7 @@ module.exports.createOnMessage = (fs) =>
/**
* @param {typeof import('memfs')} memfs
*/
module.exports.createFsProxy = (memfs) =>
export const createFsProxy = (memfs) =>
new Proxy(
{},
{

View File

@ -5,7 +5,7 @@ import { fileURLToPath } from 'node:url'
import * as memfs from 'memfs'
import { createFsProxy, createOnMessage } from './fs-proxy.cjs'
import { createFsProxy, createOnMessage } from './fs-proxy.js'
const __filename = fileURLToPath(import.meta.url)

View File

@ -19,7 +19,8 @@
},
"files": [
"runtime.cjs",
"fs-proxy.cjs",
"runtime.js",
"fs-proxy.js",
"dist/*.js"
],
"devDependencies": {
@ -50,7 +51,7 @@
},
"exports": {
".": {
"import": "./dist/runtime.js",
"import": "./runtime.js",
"require": "./runtime.cjs"
},
"./fs": {

View File

@ -46,26 +46,10 @@ export default defineConfig([
},
},
{
input: './runtime.js',
treeshake: true,
plugins: [
replace({
process: 'null',
'process.env.NODE_ENV': '"production"',
'process.env.NODE_DEBUG_NATIVE': false,
__webpack_public_path__: undefined,
preventAssignment: false,
}),
commonjs(),
nodeResolve({
preferBuiltins: false,
mainFields: ['browser', 'module', 'main'],
}),
],
input: './fs-proxy.js',
output: {
format: 'esm',
sourcemap: 'inline',
dir: './dist',
format: 'commonjs',
file: './dist/fs-proxy.cjs',
},
},
])

View File

@ -2,7 +2,7 @@ const { MessageHandler, instantiateNapiModuleSync, instantiateNapiModule } = req
const { getDefaultContext } = require('@emnapi/runtime')
const { WASI } = require('@tybys/wasm-util')
const { createFsProxy, createOnMessage } = require('./fs-proxy.cjs')
const { createFsProxy, createOnMessage } = require('./dist/fs-proxy.cjs')
module.exports = {
MessageHandler,

View File

@ -4,5 +4,5 @@ export {
MessageHandler,
} from '@emnapi/core'
export { getDefaultContext } from '@emnapi/runtime'
export { WASI } from '@tybys/wasm-util'
export { createOnMessage, createFsProxy } from './fs-proxy.cjs'
export * from '@tybys/wasm-util'
export { createOnMessage, createFsProxy } from './fs-proxy.js'