Skip to content

Commit e20e043

Browse files
committed
test: fix async work browser test
1 parent 1fa537e commit e20e043

6 files changed

Lines changed: 167 additions & 27 deletions

File tree

.vscode/settings.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,5 +21,9 @@
2121
"livePreview.httpHeaders": {
2222
"Cross-Origin-Embedder-Policy": "require-corp",
2323
"Cross-Origin-Opener-Policy": "same-origin"
24+
},
25+
"liveServer.settings.headers": {
26+
"Cross-Origin-Embedder-Policy": "require-corp",
27+
"Cross-Origin-Opener-Policy": "same-origin"
2428
}
2529
}

packages/core/rollup.config.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,12 @@ export default [
3939
}
4040
]
4141
}),
42+
...defineConfig({
43+
outputFile: 'emnapi-core.full',
44+
defines: {
45+
__VERSION__: JSON.stringify(pkg.version)
46+
},
47+
}),
4248
...plugins.flatMap(([_, name, outputName]) => defineConfig({
4349
outputName,
4450
outputFile: `plugins/${name}`,

packages/test/CMakeLists.txt

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ elseif(IS_WASI_THREADS)
106106
set(COMMON_LINK_OPTIONS
107107
# "-v"
108108
"-mexec-model=reactor"
109-
"-Wl,-zstack-size=1048576,--initial-memory=16777216,--max-memory=2147483648,--import-memory,--export-dynamic,--export=malloc,--export=free,--export=emnapi_create_env,--export=emnapi_delete_env,--export=emnapi_thread_crashed,--import-undefined,--export-table,--growable-table"
109+
"-Wl,-zstack-size=1048576,--initial-memory=16777216,--max-memory=2147483648,--import-memory,--export-dynamic,--export=malloc,--export=free,--export=emnapi_create_env,--export=emnapi_delete_env,--export-if-defined=emnapi_thread_crashed,--import-undefined,--export-table,--growable-table"
110110
)
111111
set(COMMON_EXPORTS_NAPI
112112
"-Wl,--export=napi_register_wasm_v1,--export-if-defined=node_api_module_get_api_version_v1"
@@ -194,12 +194,12 @@ function(add_test NAME SOURCE_LIST PTHREAD)
194194
target_link_libraries(${NAME} PRIVATE "emnapi-basic")
195195
endif()
196196
else()
197-
if(IS_WASI_THREADS)
198-
target_link_libraries(${NAME} PRIVATE "emnapi-basic-mt")
199-
target_link_options(${NAME} PRIVATE "-Wl,--import-memory,--shared-memory,--export=emnapi_async_worker_create,--export=emnapi_async_worker_init")
200-
else()
197+
# if(IS_WASI_THREADS)
198+
# target_link_libraries(${NAME} PRIVATE "emnapi-basic-mt")
199+
# target_link_options(${NAME} PRIVATE "-Wl,--import-memory,--shared-memory,--export=emnapi_async_worker_create,--export=emnapi_async_worker_init")
200+
# else()
201201
target_link_libraries(${NAME} PRIVATE "emnapi-mt")
202-
endif()
202+
# endif()
203203
target_compile_options(${NAME} PRIVATE "-pthread")
204204
target_link_options(${NAME} PRIVATE "-pthread")
205205
endif()
@@ -255,12 +255,12 @@ function(add_naa_test NAME SOURCE_LIST DEFINES ENABLE_EXCEPTION)
255255
target_link_libraries(${NAME} PRIVATE "emnapi-basic")
256256
endif()
257257
else()
258-
if(IS_WASI_THREADS)
259-
target_link_libraries(${NAME} PRIVATE "emnapi-basic-mt")
260-
target_link_options(${NAME} PRIVATE "-Wl,--import-memory,--shared-memory,--export=emnapi_async_worker_create,--export=emnapi_async_worker_init")
261-
else()
258+
# if(IS_WASI_THREADS)
259+
# target_link_libraries(${NAME} PRIVATE "emnapi-basic-mt")
260+
# target_link_options(${NAME} PRIVATE "-Wl,--import-memory,--shared-memory,--export=emnapi_async_worker_create,--export=emnapi_async_worker_init")
261+
# else()
262262
target_link_libraries(${NAME} PRIVATE "emnapi-mt")
263-
endif()
263+
# endif()
264264
target_compile_options(${NAME} PRIVATE "-pthread")
265265
target_link_options(${NAME} PRIVATE "-pthread")
266266
endif()

packages/test/async/async-wasi.html

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,18 @@
77
<title>async</title>
88
</head>
99
<body>
10-
<script src="../../../node_modules/@tybys/wasm-util/dist/wasm-util.min.js"></script>
11-
<script src="../../core/dist/emnapi-core.js"></script>
12-
<script src="../../runtime/dist/emnapi.js"></script>
13-
<script>
10+
<script type="module">
1411
(async function main () {
15-
new Worker('./async-wasi.js')
12+
const worker = new Worker('./async-wasi.js', { type: 'module' })
13+
worker.onmessage = (e) => {
14+
if (e.data === 'done') {
15+
console.log('subworker done')
16+
import('./async-wasi.js')
17+
}
18+
}
19+
worker.onerror = (e) => {
20+
console.error('test failed in subworker', e)
21+
}
1622
})()
1723
</script>
1824
</body>

packages/test/async/async-wasi.js

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
11
/* eslint-disable no-undef */
22
/* eslint-disable camelcase */
3-
if (typeof self !== 'undefined') {
4-
importScripts('../../../node_modules/@tybys/wasm-util/dist/wasm-util.min.js')
5-
importScripts('../../core/dist/emnapi-core.js')
6-
importScripts('../../runtime/dist/emnapi.js')
7-
}
83

94
;(async function main () {
10-
const init = function () {
11-
const { WASI } = wasmUtil
12-
const { createNapiModule, loadNapiModule } = emnapiCore
13-
const { getDefaultContext } = emnapi
5+
const init = async function () {
6+
const { WASI } = await import('../../../node_modules/@tybys/wasm-util/dist/wasm-util.esm.js')
7+
const { createNapiModule, loadNapiModule } = await import('../../core/dist/emnapi-core.full.js')
8+
const { getDefaultContext } = await import('../../runtime/dist/emnapi.js')
149
const wasi = new WASI()
1510
const napiModule = createNapiModule({
1611
context: getDefaultContext(),
12+
reuseWorker: {
13+
size: 4
14+
},
15+
waitThreadStart: typeof window === 'undefined' ? 1000 : false,
1716
onCreateWorker () {
18-
return new Worker('../worker.js')
19-
}
17+
return new Worker('../worker.js', { type: 'module' })
18+
},
2019
})
2120
const wasmMemory = new WebAssembly.Memory({
2221
initial: 16777216 / 65536,
@@ -80,4 +79,8 @@ if (typeof self !== 'undefined') {
8079
await new Promise((resolve) => {
8180
setTimeout(resolve, 3000)
8281
})
82+
83+
if (typeof postMessage === 'function') {
84+
postMessage('done')
85+
}
8386
})()

packages/test/worker.js

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
/* eslint-disable no-eval */
2+
/* eslint-disable no-undef */
3+
import * as emnapiCore from '../../node_modules/@emnapi/core/dist/emnapi-core.full.js'
4+
import { v8, asyncWork, tsfn } from '../../node_modules/@emnapi/core/dist/plugins/index.js'
5+
// import * as emnapi from '../runtime/dist/emnapi.js'
6+
7+
(function () {
8+
// const log = (...args) => {
9+
// const str = require('util').format(...args)
10+
// require('fs').writeSync(1, str + '\n')
11+
// }
12+
// const error = (...args) => {
13+
// const str = require('util').format(...args)
14+
// require('fs').writeSync(2, str + '\n')
15+
// }
16+
let require, fs, WASI, ready
17+
18+
const ENVIRONMENT_IS_NODE =
19+
typeof process === 'object' && process !== null &&
20+
typeof process.versions === 'object' && process.versions !== null &&
21+
typeof process.versions.node === 'string'
22+
23+
if (ENVIRONMENT_IS_NODE) {
24+
ready = (async function () {
25+
let parentPort
26+
Object.assign(globalThis, {
27+
self: globalThis,
28+
importScripts: function (f) {
29+
(0, eval)(fs.readFileSync(f, 'utf8') + '//# sourceURL=' + f)
30+
},
31+
postMessage: function (msg) {
32+
parentPort?.postMessage(msg)
33+
}
34+
})
35+
36+
const { createRequire } = await import('node:module')
37+
require = createRequire(import.meta.url)
38+
const nodeWorkerThreads = require('worker_threads')
39+
40+
parentPort = nodeWorkerThreads.parentPort
41+
42+
parentPort.on('message', (data) => {
43+
globalThis.onmessage({ data })
44+
})
45+
46+
fs = require('fs')
47+
48+
Object.assign(globalThis, {
49+
require,
50+
Worker: nodeWorkerThreads.Worker
51+
})
52+
53+
WASI = require('node:wasi').WASI
54+
})()
55+
} else {
56+
ready = (async function () {
57+
const { Buffer } = await import('https://esm.sh/buffer@6.0.3')
58+
globalThis.Buffer = Buffer
59+
const memfs = await import('../../node_modules/memfs-browser/dist/memfs.esm.js')
60+
const wasmUtil = await import('../../node_modules/@tybys/wasm-util/dist/wasm-util.esm.js')
61+
const { Volume, createFsFromVolume } = memfs
62+
fs = createFsFromVolume(Volume.fromJSON({
63+
'/': null
64+
}))
65+
WASI = wasmUtil.WASI
66+
})()
67+
}
68+
69+
const { instantiateNapiModule, MessageHandler } = emnapiCore
70+
71+
const handler = new MessageHandler({
72+
async onLoad ({ wasmModule, wasmMemory }) {
73+
await ready
74+
const wasi = new WASI({
75+
fs,
76+
version: 'preview1',
77+
print: ENVIRONMENT_IS_NODE
78+
? (...args) => {
79+
const str = require('util').format(...args)
80+
fs.writeSync(1, str + '\n')
81+
}
82+
: function () { console.log.apply(console, arguments) }
83+
})
84+
85+
const UTF8ToString = (ptr) => {
86+
ptr >>>= 0
87+
if (!ptr) return ''
88+
const HEAPU8 = new Uint8Array(wasmMemory.buffer)
89+
let end
90+
for (end = ptr; HEAPU8[end];) ++end
91+
const shared = (typeof SharedArrayBuffer === 'function') && (wasmMemory.buffer instanceof SharedArrayBuffer)
92+
return new TextDecoder().decode(shared ? HEAPU8.slice(ptr, end) : HEAPU8.subarray(ptr, end))
93+
}
94+
95+
return instantiateNapiModule(wasmModule, {
96+
childThread: true,
97+
wasi,
98+
overwriteImports (importObject) {
99+
importObject.env.memory = wasmMemory
100+
importObject.env.console_log = function (fmt, ...args) {
101+
const fmtString = UTF8ToString(fmt)
102+
console.log(fmtString, ...args)
103+
return 0
104+
}
105+
importObject.env.sleep = function (n) {
106+
const end = Date.now() + n * 1000
107+
while (Date.now() < end) {
108+
// ignore
109+
}
110+
}
111+
},
112+
plugins: [v8, asyncWork, tsfn]
113+
})
114+
}
115+
})
116+
117+
globalThis.onmessage = function (e) {
118+
handler.handle(e)
119+
// handle other messages
120+
}
121+
})()

0 commit comments

Comments
 (0)