unwasm 0.1.0 → 0.3.0
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/README.md +128 -22
- package/dist/plugin.d.mts +7 -3
- package/dist/plugin.d.ts +7 -3
- package/dist/plugin.mjs +172 -25
- package/dist/tools.d.mts +25 -0
- package/dist/tools.d.ts +25 -0
- package/dist/tools.mjs +41 -0
- package/examples/rand.wasm +0 -0
- package/examples/sum.wasm +0 -0
- package/package.json +14 -3
- package/plugin.d.ts +3 -0
package/README.md
CHANGED
|
@@ -1,68 +1,173 @@
|
|
|
1
|
-
# 🇼 unwasm
|
|
2
|
-
|
|
3
1
|
[![npm version][npm-version-src]][npm-version-href]
|
|
4
2
|
[![npm downloads][npm-downloads-src]][npm-downloads-href]
|
|
5
3
|
[![Codecov][codecov-src]][codecov-href]
|
|
6
4
|
|
|
5
|
+
# unwasm
|
|
6
|
+
|
|
7
7
|
Universal [WebAssembly](https://webassembly.org/) tools for JavaScript.
|
|
8
8
|
|
|
9
9
|
## Goal
|
|
10
10
|
|
|
11
|
-
This project aims to make a common and future-proof solution for WebAssembly modules support suitable for various JavaScript runtimes,
|
|
11
|
+
This project aims to make a common and future-proof solution for WebAssembly modules support suitable for various JavaScript runtimes, frameworks, and build Tools following [WebAssembly/ES Module Integration](https://github.com/WebAssembly/esm-integration/tree/main/proposals/esm-integration) proposal from WebAssembly Community Group as much as possible while also trying to keep compatibility with current ecosystem libraries.
|
|
12
12
|
|
|
13
13
|
## Roadmap
|
|
14
14
|
|
|
15
15
|
The development will be split into multiple stages.
|
|
16
16
|
|
|
17
17
|
> [!IMPORTANT]
|
|
18
|
-
> This Project is under development!
|
|
18
|
+
> This Project is under development! See the linked discussions to be involved!
|
|
19
19
|
|
|
20
|
-
- [ ]
|
|
20
|
+
- [ ] Builder plugin powered by [unjs/unplugin](https://github.com/unjs/unplugin) ([unjs/unwasm#2](https://github.com/unjs/unwasm/issues/2))
|
|
21
21
|
- [x] Rollup
|
|
22
|
-
- [ ] Tools
|
|
23
|
-
- [
|
|
24
|
-
- [ ]
|
|
25
|
-
- [ ]
|
|
26
|
-
- [ ]
|
|
22
|
+
- [ ] Build Tools ([unjs/unwasm#3](https://github.com/unjs/unwasm/issues/3))
|
|
23
|
+
- [x] `parseWasm`
|
|
24
|
+
- [ ] Runtime Utils ([unjs/unwasm#4](https://github.com/unjs/unwasm/issues/4))
|
|
25
|
+
- [ ] ESM Loader ([unjs/unwasm#5](https://github.com/unjs/unwasm/issues/5))
|
|
26
|
+
- [ ] Integration with [Wasmer](https://github.com/wasmerio) ([unjs/unwasm#6](https://github.com/unjs/unwasm/issues/6))
|
|
27
|
+
- [ ] Convention for library authors exporting wasm modules ([unjs/unwasm#7](https://github.com/unjs/unwasm/issues/7))
|
|
28
|
+
|
|
29
|
+
## Bindings API
|
|
30
|
+
|
|
31
|
+
When importing a `.wasm` module, unwasm resolves, reads, and then parses the module during build process to get the information about imports and exports and generate appropriate code bindings.
|
|
32
|
+
|
|
33
|
+
If the target environment supports [top level `await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#top_level_await) and also the wasm module requires no imports object (auto-detected after parsing), unwasm generates bindings to allow importing wasm module like any other ESM import.
|
|
34
|
+
|
|
35
|
+
If the target environment lacks support for top level `await` or the wasm module requires imports object or `lazy` plugin option is set to `true`, unwasm will export a wrapped [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) object which can be called as a function to lazily evaluate the module with custom imports object. This way we still have a simple syntax as close as possible to ESM modules and also we can lazily initialize modules.
|
|
36
|
+
|
|
37
|
+
**Example:** Using static import
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
import { sum } from "unwasm/examples/sum.wasm";
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
**Example:** Using dynamic import
|
|
44
|
+
|
|
45
|
+
```js
|
|
46
|
+
const { sum } = await import("unwasm/examples/sum.wasm");
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
If your WebAssembly module requires an import object (which is likely!), the usage syntax would be slightly different as we need to initiate the module with an import object first.
|
|
50
|
+
|
|
51
|
+
**Example:** Using dynamic import with imports object
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
const { rand } = await import("unwasm/examples/rand.wasm").then((r) =>
|
|
55
|
+
r.default({
|
|
56
|
+
env: {
|
|
57
|
+
seed: () => () => Math.random() * Date.now(),
|
|
58
|
+
},
|
|
59
|
+
}),
|
|
60
|
+
);
|
|
61
|
+
```
|
|
27
62
|
|
|
28
|
-
|
|
63
|
+
**Example:** Using static import with imports object
|
|
29
64
|
|
|
30
|
-
|
|
65
|
+
```js
|
|
66
|
+
import initRand, { rand } from "unwasm/examples/rand.wasm";
|
|
67
|
+
|
|
68
|
+
await initRand({
|
|
69
|
+
env: {
|
|
70
|
+
seed: () => () => Math.random() * Date.now(),
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
> [!NOTE]
|
|
76
|
+
> When using **static import syntax**, and before initializing the module, the named exports will be wrapped into a function by proxy that waits for the module initialization and if called before init, will immediately try to call init without imports and return a Promise that calls a function after init.
|
|
77
|
+
|
|
78
|
+
## Integration
|
|
79
|
+
|
|
80
|
+
Unwasm needs to transform the `.wasm` imports to the compatible bindings. Currently, the only method is using a rollup plugin. In the future, more usage methods will be introduced.
|
|
81
|
+
|
|
82
|
+
### Install
|
|
83
|
+
|
|
84
|
+
First, install the [`unwasm`](https://www.npmjs.com/package/unwasm) npm package.
|
|
31
85
|
|
|
32
86
|
```sh
|
|
33
87
|
# npm
|
|
34
|
-
npm install unwasm
|
|
88
|
+
npm install --dev unwasm
|
|
35
89
|
|
|
36
90
|
# yarn
|
|
37
|
-
yarn add unwasm
|
|
91
|
+
yarn add -D unwasm
|
|
38
92
|
|
|
39
93
|
# pnpm
|
|
40
|
-
pnpm
|
|
94
|
+
pnpm i -D unwasm
|
|
41
95
|
|
|
42
96
|
# bun
|
|
43
|
-
bun
|
|
97
|
+
bun i -D unwasm
|
|
44
98
|
```
|
|
45
99
|
|
|
46
|
-
|
|
100
|
+
### Builder Plugins
|
|
47
101
|
|
|
48
102
|
###### Rollup
|
|
49
103
|
|
|
50
104
|
```js
|
|
51
|
-
|
|
105
|
+
// rollup.config.js
|
|
106
|
+
import { rollup as unwasm } from "unwasm/plugin";
|
|
52
107
|
|
|
53
108
|
export default {
|
|
54
109
|
plugins: [
|
|
55
|
-
|
|
110
|
+
unwasm({
|
|
56
111
|
/* options */
|
|
57
112
|
}),
|
|
58
113
|
],
|
|
59
114
|
};
|
|
60
115
|
```
|
|
61
116
|
|
|
62
|
-
### Options
|
|
117
|
+
### Plugin Options
|
|
118
|
+
|
|
119
|
+
- `esmImport`: Direct import the wasm file instead of bundling, required in Cloudflare Workers and works with environments that allow natively importing a `.wasm` module (default is `false`)
|
|
120
|
+
- `lazy`: Import `.wasm` files using a lazily evaluated proxy for compatibility with runtimes without top-level await support (default is `false`)
|
|
121
|
+
|
|
122
|
+
## Tools
|
|
63
123
|
|
|
64
|
-
|
|
65
|
-
|
|
124
|
+
unwasm provides useful build tools to operate on `.wasm` modules directly.
|
|
125
|
+
|
|
126
|
+
**Note:** `unwasm/tools` subpath export is **not** meant or optimized for production runtime. Only rely on it for development and build time.
|
|
127
|
+
|
|
128
|
+
### `parseWasm`
|
|
129
|
+
|
|
130
|
+
Parses `wasm` binary format with useful information using [webassemblyjs/wasm-parser](https://github.com/xtuc/webassemblyjs/tree/master/packages/wasm-parser).
|
|
131
|
+
|
|
132
|
+
```js
|
|
133
|
+
import { readFile } from "node:fs/promises";
|
|
134
|
+
import { parseWasm } from "unwasm/tools";
|
|
135
|
+
|
|
136
|
+
const source = await readFile(new URL("./examples/sum.wasm", import.meta.url));
|
|
137
|
+
const parsed = parseWasm(source);
|
|
138
|
+
console.log(JSON.stringify(parsed, undefined, 2));
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Example parsed result:
|
|
142
|
+
|
|
143
|
+
```json
|
|
144
|
+
{
|
|
145
|
+
"modules": [
|
|
146
|
+
{
|
|
147
|
+
"exports": [
|
|
148
|
+
{
|
|
149
|
+
"id": 5,
|
|
150
|
+
"name": "rand",
|
|
151
|
+
"type": "Func"
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
"id": 0,
|
|
155
|
+
"name": "memory",
|
|
156
|
+
"type": "Memory"
|
|
157
|
+
}
|
|
158
|
+
],
|
|
159
|
+
"imports": [
|
|
160
|
+
{
|
|
161
|
+
"module": "env",
|
|
162
|
+
"name": "seed",
|
|
163
|
+
"params": [],
|
|
164
|
+
"returnType": "f64"
|
|
165
|
+
}
|
|
166
|
+
]
|
|
167
|
+
}
|
|
168
|
+
]
|
|
169
|
+
}
|
|
170
|
+
```
|
|
66
171
|
|
|
67
172
|
## Development
|
|
68
173
|
|
|
@@ -71,6 +176,7 @@ export default {
|
|
|
71
176
|
- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable`
|
|
72
177
|
- Install dependencies using `pnpm install`
|
|
73
178
|
- Run interactive tests using `pnpm dev`
|
|
179
|
+
- Optionally install [es6-string-html](https://marketplace.visualstudio.com/items?itemName=Tobermory.es6-string-html) extension to make it easier to work with string templates.
|
|
74
180
|
|
|
75
181
|
## License
|
|
76
182
|
|
package/dist/plugin.d.mts
CHANGED
|
@@ -2,20 +2,24 @@ import { Plugin } from 'rollup';
|
|
|
2
2
|
|
|
3
3
|
interface UnwasmPluginOptions {
|
|
4
4
|
/**
|
|
5
|
-
*
|
|
5
|
+
* Directly import the `.wasm` files instead of bundling as base64 string.
|
|
6
6
|
*
|
|
7
7
|
* @default false
|
|
8
8
|
*/
|
|
9
9
|
esmImport?: boolean;
|
|
10
10
|
/**
|
|
11
|
-
*
|
|
11
|
+
* Avoid using top level await and always use a proxy.
|
|
12
|
+
*
|
|
13
|
+
* Useful for compatibility with environments that don't support top level await.
|
|
12
14
|
*
|
|
13
15
|
* @default false
|
|
14
16
|
*/
|
|
15
17
|
lazy?: boolean;
|
|
16
18
|
}
|
|
19
|
+
|
|
20
|
+
declare const rollup: (opts: UnwasmPluginOptions) => Plugin;
|
|
17
21
|
declare const _default: {
|
|
18
22
|
rollup: (opts: UnwasmPluginOptions) => Plugin<any>;
|
|
19
23
|
};
|
|
20
24
|
|
|
21
|
-
export {
|
|
25
|
+
export { _default as default, rollup };
|
package/dist/plugin.d.ts
CHANGED
|
@@ -2,20 +2,24 @@ import { Plugin } from 'rollup';
|
|
|
2
2
|
|
|
3
3
|
interface UnwasmPluginOptions {
|
|
4
4
|
/**
|
|
5
|
-
*
|
|
5
|
+
* Directly import the `.wasm` files instead of bundling as base64 string.
|
|
6
6
|
*
|
|
7
7
|
* @default false
|
|
8
8
|
*/
|
|
9
9
|
esmImport?: boolean;
|
|
10
10
|
/**
|
|
11
|
-
*
|
|
11
|
+
* Avoid using top level await and always use a proxy.
|
|
12
|
+
*
|
|
13
|
+
* Useful for compatibility with environments that don't support top level await.
|
|
12
14
|
*
|
|
13
15
|
* @default false
|
|
14
16
|
*/
|
|
15
17
|
lazy?: boolean;
|
|
16
18
|
}
|
|
19
|
+
|
|
20
|
+
declare const rollup: (opts: UnwasmPluginOptions) => Plugin;
|
|
17
21
|
declare const _default: {
|
|
18
22
|
rollup: (opts: UnwasmPluginOptions) => Plugin<any>;
|
|
19
23
|
};
|
|
20
24
|
|
|
21
|
-
export {
|
|
25
|
+
export { _default as default, rollup };
|
package/dist/plugin.mjs
CHANGED
|
@@ -3,19 +3,166 @@ import { basename } from 'pathe';
|
|
|
3
3
|
import MagicString from 'magic-string';
|
|
4
4
|
import { createUnplugin } from 'unplugin';
|
|
5
5
|
import { createHash } from 'node:crypto';
|
|
6
|
+
import { parseWasm } from './tools.mjs';
|
|
7
|
+
import '@webassemblyjs/wasm-parser';
|
|
6
8
|
|
|
9
|
+
const UNWASM_EXTERNAL_PREFIX = "\0unwasm:external:";
|
|
10
|
+
const UMWASM_HELPERS_ID = "\0unwasm:helpers";
|
|
7
11
|
function sha1(source) {
|
|
8
12
|
return createHash("sha1").update(source).digest("hex").slice(0, 16);
|
|
9
13
|
}
|
|
10
14
|
|
|
11
|
-
const
|
|
15
|
+
const js = String.raw;
|
|
16
|
+
function getWasmBinding(asset, opts) {
|
|
17
|
+
const envCode = opts.esmImport ? js`
|
|
18
|
+
async function _instantiate(imports) {
|
|
19
|
+
const _mod = await import("${UNWASM_EXTERNAL_PREFIX}${asset.id}").then(r => r.default || r);
|
|
20
|
+
return WebAssembly.instantiate(_mod, imports)
|
|
21
|
+
}
|
|
22
|
+
` : js`
|
|
23
|
+
import { base64ToUint8Array } from "${UMWASM_HELPERS_ID}";
|
|
24
|
+
|
|
25
|
+
function _instantiate(imports) {
|
|
26
|
+
const _data = base64ToUint8Array("${asset.source.toString("base64")}")
|
|
27
|
+
return WebAssembly.instantiate(_data, imports)
|
|
28
|
+
}
|
|
29
|
+
`;
|
|
30
|
+
const canTopAwait = opts.lazy !== true && Object.keys(asset.imports).length === 0;
|
|
31
|
+
if (canTopAwait) {
|
|
32
|
+
return js`
|
|
33
|
+
import { getExports } from "${UMWASM_HELPERS_ID}";
|
|
34
|
+
${envCode}
|
|
35
|
+
|
|
36
|
+
const $exports = getExports(await _instantiate());
|
|
37
|
+
|
|
38
|
+
${asset.exports.map((name) => `export const ${name} = $exports.${name};`).join("\n")}
|
|
39
|
+
|
|
40
|
+
export const $init = () => $exports;
|
|
41
|
+
|
|
42
|
+
export default $exports;
|
|
43
|
+
`;
|
|
44
|
+
} else {
|
|
45
|
+
return js`
|
|
46
|
+
import { createLazyWasmModule } from "${UMWASM_HELPERS_ID}";
|
|
47
|
+
${envCode}
|
|
48
|
+
|
|
49
|
+
const _mod = createLazyWasmModule(_instantiate);
|
|
50
|
+
|
|
51
|
+
${asset.exports.map((name) => `export const ${name} = _mod.${name};`).join("\n")}
|
|
52
|
+
|
|
53
|
+
export const $init = _mod.$init.bind(_mod);
|
|
54
|
+
|
|
55
|
+
export default _mod;
|
|
56
|
+
`;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function getPluginUtils() {
|
|
60
|
+
return js`
|
|
61
|
+
export function debug(...args) {
|
|
62
|
+
console.log('[wasm] [debug]', ...args);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function getExports(input) {
|
|
66
|
+
return input?.instance?.exports || input?.exports || input;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function base64ToUint8Array(str) {
|
|
70
|
+
const data = atob(str);
|
|
71
|
+
const size = data.length;
|
|
72
|
+
const bytes = new Uint8Array(size);
|
|
73
|
+
for (let i = 0; i < size; i++) {
|
|
74
|
+
bytes[i] = data.charCodeAt(i);
|
|
75
|
+
}
|
|
76
|
+
return bytes;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function createLazyWasmModule(_instantiator) {
|
|
80
|
+
const _exports = Object.create(null);
|
|
81
|
+
let _loaded;
|
|
82
|
+
let _promise;
|
|
83
|
+
|
|
84
|
+
const init = (imports) => {
|
|
85
|
+
if (_loaded) {
|
|
86
|
+
return Promise.resolve(exportsProxy);
|
|
87
|
+
}
|
|
88
|
+
if (_promise) {
|
|
89
|
+
return _promise;
|
|
90
|
+
}
|
|
91
|
+
return _promise = _instantiator(imports)
|
|
92
|
+
.then(r => {
|
|
93
|
+
Object.assign(_exports, getExports(r));
|
|
94
|
+
_loaded = true;
|
|
95
|
+
_promise = undefined;
|
|
96
|
+
return exportsProxy;
|
|
97
|
+
})
|
|
98
|
+
.catch(error => {
|
|
99
|
+
_promise = undefined;
|
|
100
|
+
console.error('[wasm] [error]', error);
|
|
101
|
+
throw error;
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const exportsProxy = new Proxy(_exports, {
|
|
106
|
+
get(_, prop) {
|
|
107
|
+
if (_loaded) {
|
|
108
|
+
return _exports[prop];
|
|
109
|
+
}
|
|
110
|
+
return (...args) => {
|
|
111
|
+
return _loaded
|
|
112
|
+
? _exports[prop]?.(...args)
|
|
113
|
+
: init().then(() => _exports[prop]?.(...args));
|
|
114
|
+
};
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
const lazyProxy = new Proxy(() => {}, {
|
|
120
|
+
get(_, prop) {
|
|
121
|
+
return exportsProxy[prop];
|
|
122
|
+
},
|
|
123
|
+
apply(_, __, args) {
|
|
124
|
+
return init(args[0])
|
|
125
|
+
},
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
return lazyProxy;
|
|
129
|
+
}
|
|
130
|
+
`;
|
|
131
|
+
}
|
|
132
|
+
|
|
12
133
|
const unplugin = createUnplugin((opts) => {
|
|
13
134
|
const assets = /* @__PURE__ */ Object.create(null);
|
|
135
|
+
const _parseCache = /* @__PURE__ */ Object.create(null);
|
|
136
|
+
function parse(name, source) {
|
|
137
|
+
if (_parseCache[name]) {
|
|
138
|
+
return _parseCache[name];
|
|
139
|
+
}
|
|
140
|
+
const parsed = parseWasm(source);
|
|
141
|
+
const imports = /* @__PURE__ */ Object.create(null);
|
|
142
|
+
const exports = [];
|
|
143
|
+
for (const mod of parsed.modules) {
|
|
144
|
+
exports.push(...mod.exports.map((e) => e.name));
|
|
145
|
+
for (const imp of mod.imports) {
|
|
146
|
+
if (!imports[imp.module]) {
|
|
147
|
+
imports[imp.module] = [];
|
|
148
|
+
}
|
|
149
|
+
imports[imp.module].push(imp.name);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
_parseCache[name] = {
|
|
153
|
+
imports,
|
|
154
|
+
exports
|
|
155
|
+
};
|
|
156
|
+
return _parseCache[name];
|
|
157
|
+
}
|
|
14
158
|
return {
|
|
15
159
|
name: "unwasm",
|
|
16
160
|
rollup: {
|
|
17
161
|
async resolveId(id, importer) {
|
|
18
|
-
if (id
|
|
162
|
+
if (id === UMWASM_HELPERS_ID) {
|
|
163
|
+
return id;
|
|
164
|
+
}
|
|
165
|
+
if (id.startsWith(UNWASM_EXTERNAL_PREFIX)) {
|
|
19
166
|
return {
|
|
20
167
|
id,
|
|
21
168
|
external: true
|
|
@@ -23,12 +170,11 @@ const unplugin = createUnplugin((opts) => {
|
|
|
23
170
|
}
|
|
24
171
|
if (id.endsWith(".wasm")) {
|
|
25
172
|
const r = await this.resolve(id, importer, { skipSelf: true });
|
|
26
|
-
if (r?.id && r
|
|
173
|
+
if (r?.id && r.id !== id) {
|
|
27
174
|
return {
|
|
28
175
|
id: r.id.startsWith("file://") ? r.id.slice(7) : r.id,
|
|
29
176
|
external: false,
|
|
30
|
-
moduleSideEffects: false
|
|
31
|
-
syntheticNamedExports: false
|
|
177
|
+
moduleSideEffects: false
|
|
32
178
|
};
|
|
33
179
|
}
|
|
34
180
|
}
|
|
@@ -46,13 +192,23 @@ const unplugin = createUnplugin((opts) => {
|
|
|
46
192
|
}
|
|
47
193
|
},
|
|
48
194
|
async load(id) {
|
|
195
|
+
if (id === UMWASM_HELPERS_ID) {
|
|
196
|
+
return getPluginUtils();
|
|
197
|
+
}
|
|
49
198
|
if (!id.endsWith(".wasm") || !existsSync(id)) {
|
|
50
199
|
return;
|
|
51
200
|
}
|
|
52
201
|
const source = await promises.readFile(id);
|
|
53
202
|
const name = `wasm/${basename(id, ".wasm")}-${sha1(source)}.wasm`;
|
|
54
|
-
|
|
55
|
-
|
|
203
|
+
const parsed = parse(name, source);
|
|
204
|
+
assets[id] = {
|
|
205
|
+
name,
|
|
206
|
+
id,
|
|
207
|
+
source,
|
|
208
|
+
imports: parsed.imports,
|
|
209
|
+
exports: parsed.exports
|
|
210
|
+
};
|
|
211
|
+
return `export default "UNWASM DUMMY EXPORT";`;
|
|
56
212
|
},
|
|
57
213
|
transform(_code, id) {
|
|
58
214
|
if (!id.endsWith(".wasm")) {
|
|
@@ -62,25 +218,16 @@ const unplugin = createUnplugin((opts) => {
|
|
|
62
218
|
if (!asset) {
|
|
63
219
|
return;
|
|
64
220
|
}
|
|
65
|
-
let _dataStr;
|
|
66
|
-
if (opts.esmImport) {
|
|
67
|
-
_dataStr = `await import("${WASM_EXTERNAL_ID}${id}").then(r => r?.default || r)`;
|
|
68
|
-
} else {
|
|
69
|
-
const base64Str = asset.source.toString("base64");
|
|
70
|
-
_dataStr = `(()=>{const d=atob("${base64Str}");const s=d.length;const b=new Uint8Array(s);for(let i=0;i<s;i++)b[i]=d.charCodeAt(i);return b})()`;
|
|
71
|
-
}
|
|
72
|
-
let _str = `await WebAssembly.instantiate(${_dataStr}, { env: { "Math.random": () => Math.random, "Math.floor": () => Math.floor } }).then(r => r?.exports||r?.instance?.exports || r);`;
|
|
73
|
-
if (opts.lazy) {
|
|
74
|
-
_str = `(()=>{const e=async()=>{return ${_str}};let _p;const p=()=>{if(!_p)_p=e();return _p;};return {then:cb=>p().then(cb),catch:cb=>p().catch(cb)}})()`;
|
|
75
|
-
}
|
|
76
221
|
return {
|
|
77
|
-
code:
|
|
78
|
-
map: { mappings: "" }
|
|
79
|
-
syntheticNamedExports: true
|
|
222
|
+
code: getWasmBinding(asset, opts),
|
|
223
|
+
map: { mappings: "" }
|
|
80
224
|
};
|
|
81
225
|
},
|
|
82
226
|
renderChunk(code, chunk) {
|
|
83
|
-
if (!
|
|
227
|
+
if (!opts.esmImport) {
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (!(chunk.moduleIds.some((id) => id.endsWith(".wasm")) || chunk.imports.some((id) => id.endsWith(".wasm"))) || !code.includes(UNWASM_EXTERNAL_PREFIX)) {
|
|
84
231
|
return;
|
|
85
232
|
}
|
|
86
233
|
const s = new MagicString(code);
|
|
@@ -99,7 +246,7 @@ const unplugin = createUnplugin((opts) => {
|
|
|
99
246
|
asset
|
|
100
247
|
};
|
|
101
248
|
};
|
|
102
|
-
const ReplaceRE = new RegExp(`${
|
|
249
|
+
const ReplaceRE = new RegExp(`${UNWASM_EXTERNAL_PREFIX}([^"']+)`, "g");
|
|
103
250
|
for (const match of code.matchAll(ReplaceRE)) {
|
|
104
251
|
const resolved = resolveImport(match[1]);
|
|
105
252
|
const index = match.index;
|
|
@@ -122,8 +269,8 @@ const unplugin = createUnplugin((opts) => {
|
|
|
122
269
|
};
|
|
123
270
|
});
|
|
124
271
|
const rollup = unplugin.rollup;
|
|
125
|
-
const
|
|
272
|
+
const index = {
|
|
126
273
|
rollup
|
|
127
274
|
};
|
|
128
275
|
|
|
129
|
-
export {
|
|
276
|
+
export { index as default, rollup };
|
package/dist/tools.d.mts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
type ParsedWasmModule = {
|
|
2
|
+
id?: string;
|
|
3
|
+
imports: ModuleImport[];
|
|
4
|
+
exports: ModuleExport[];
|
|
5
|
+
};
|
|
6
|
+
type ModuleImport = {
|
|
7
|
+
module: string;
|
|
8
|
+
name: string;
|
|
9
|
+
returnType?: string;
|
|
10
|
+
params?: {
|
|
11
|
+
id?: string;
|
|
12
|
+
type: string;
|
|
13
|
+
}[];
|
|
14
|
+
};
|
|
15
|
+
type ModuleExport = {
|
|
16
|
+
name: string;
|
|
17
|
+
id: string | number;
|
|
18
|
+
type: "Func" | "Memory";
|
|
19
|
+
};
|
|
20
|
+
type ParseResult = {
|
|
21
|
+
modules: ParsedWasmModule[];
|
|
22
|
+
};
|
|
23
|
+
declare function parseWasm(source: Buffer | ArrayBuffer): ParseResult;
|
|
24
|
+
|
|
25
|
+
export { type ModuleExport, type ModuleImport, type ParseResult, type ParsedWasmModule, parseWasm };
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
type ParsedWasmModule = {
|
|
2
|
+
id?: string;
|
|
3
|
+
imports: ModuleImport[];
|
|
4
|
+
exports: ModuleExport[];
|
|
5
|
+
};
|
|
6
|
+
type ModuleImport = {
|
|
7
|
+
module: string;
|
|
8
|
+
name: string;
|
|
9
|
+
returnType?: string;
|
|
10
|
+
params?: {
|
|
11
|
+
id?: string;
|
|
12
|
+
type: string;
|
|
13
|
+
}[];
|
|
14
|
+
};
|
|
15
|
+
type ModuleExport = {
|
|
16
|
+
name: string;
|
|
17
|
+
id: string | number;
|
|
18
|
+
type: "Func" | "Memory";
|
|
19
|
+
};
|
|
20
|
+
type ParseResult = {
|
|
21
|
+
modules: ParsedWasmModule[];
|
|
22
|
+
};
|
|
23
|
+
declare function parseWasm(source: Buffer | ArrayBuffer): ParseResult;
|
|
24
|
+
|
|
25
|
+
export { type ModuleExport, type ModuleImport, type ParseResult, type ParsedWasmModule, parseWasm };
|
package/dist/tools.mjs
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { decode } from '@webassemblyjs/wasm-parser';
|
|
2
|
+
|
|
3
|
+
function parseWasm(source) {
|
|
4
|
+
const ast = decode(source);
|
|
5
|
+
const modules = [];
|
|
6
|
+
for (const body of ast.body) {
|
|
7
|
+
if (body.type === "Module") {
|
|
8
|
+
const module = {
|
|
9
|
+
imports: [],
|
|
10
|
+
exports: []
|
|
11
|
+
};
|
|
12
|
+
modules.push(module);
|
|
13
|
+
for (const field of body.fields) {
|
|
14
|
+
if (field.type === "ModuleImport") {
|
|
15
|
+
module.imports.push({
|
|
16
|
+
module: field.module,
|
|
17
|
+
name: field.name,
|
|
18
|
+
returnType: field.descr?.signature?.results?.[0],
|
|
19
|
+
params: field.descr.signature.params?.map(
|
|
20
|
+
(p) => ({
|
|
21
|
+
id: p.id,
|
|
22
|
+
type: p.valtype
|
|
23
|
+
})
|
|
24
|
+
)
|
|
25
|
+
});
|
|
26
|
+
} else if (field.type === "ModuleExport") {
|
|
27
|
+
module.exports.push({
|
|
28
|
+
name: field.name,
|
|
29
|
+
id: field.descr.id.value,
|
|
30
|
+
type: field.descr.exportType
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
modules
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export { parseWasm };
|
|
Binary file
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,22 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "unwasm",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "WebAssembly tools for JavaScript",
|
|
5
5
|
"repository": "unjs/unwasm",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"sideEffects": false,
|
|
8
8
|
"type": "module",
|
|
9
9
|
"exports": {
|
|
10
|
+
"./examples/*": "./examples/*",
|
|
10
11
|
"./plugin": {
|
|
11
12
|
"types": "./dist/plugin.d.mts",
|
|
12
13
|
"import": "./dist/plugin.mjs"
|
|
14
|
+
},
|
|
15
|
+
"./tools": {
|
|
16
|
+
"types": "./dist/tools.d.mts",
|
|
17
|
+
"import": "./dist/tools.mjs"
|
|
13
18
|
}
|
|
14
19
|
},
|
|
15
20
|
"files": [
|
|
16
|
-
"dist"
|
|
21
|
+
"dist",
|
|
22
|
+
"*.d.ts",
|
|
23
|
+
"examples/*.wasm"
|
|
17
24
|
],
|
|
18
25
|
"scripts": {
|
|
19
|
-
"build": "unbuild",
|
|
26
|
+
"build": "unbuild && pnpm build:examples",
|
|
27
|
+
"build:examples": "node ./examples/build.mjs",
|
|
20
28
|
"dev": "vitest dev",
|
|
21
29
|
"lint": "eslint --cache --ext .ts,.js,.mjs,.cjs . && prettier -c src test",
|
|
22
30
|
"lint:fix": "eslint --cache --ext .ts,.js,.mjs,.cjs . --fix && prettier -c src test -w",
|
|
@@ -26,6 +34,7 @@
|
|
|
26
34
|
"test:types": "tsc --noEmit --skipLibCheck"
|
|
27
35
|
},
|
|
28
36
|
"dependencies": {
|
|
37
|
+
"@webassemblyjs/wasm-parser": "^1.11.6",
|
|
29
38
|
"magic-string": "^0.30.5",
|
|
30
39
|
"mlly": "^1.4.2",
|
|
31
40
|
"pathe": "^1.1.1",
|
|
@@ -35,10 +44,12 @@
|
|
|
35
44
|
"@rollup/plugin-node-resolve": "^15.2.3",
|
|
36
45
|
"@types/node": "^20.10.5",
|
|
37
46
|
"@vitest/coverage-v8": "^1.1.0",
|
|
47
|
+
"assemblyscript": "^0.27.22",
|
|
38
48
|
"changelogen": "^0.5.5",
|
|
39
49
|
"eslint": "^8.56.0",
|
|
40
50
|
"eslint-config-unjs": "^0.2.1",
|
|
41
51
|
"jiti": "^1.21.0",
|
|
52
|
+
"miniflare": "^3.20231030.4",
|
|
42
53
|
"prettier": "^3.1.1",
|
|
43
54
|
"rollup": "^4.9.1",
|
|
44
55
|
"typescript": "^5.3.3",
|
package/plugin.d.ts
ADDED