unwasm 0.0.0 → 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Pooya Parsa <pooya@pi0.io>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # 🇼 unwasm
2
+
3
+ [![npm version][npm-version-src]][npm-version-href]
4
+ [![npm downloads][npm-downloads-src]][npm-downloads-href]
5
+ [![Codecov][codecov-src]][codecov-href]
6
+
7
+ Universal [WebAssembly](https://webassembly.org/) tools for JavaScript.
8
+
9
+ ## Goal
10
+
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.
12
+
13
+ ## Roadmap
14
+
15
+ The development will be split into multiple stages.
16
+
17
+ > [!IMPORTANT]
18
+ > This Project is under development! Join the linked discussions to be involved!
19
+
20
+ - [ ] Universal builder plugins ([unjs/unwasm#2](https://github.com/unjs/unwasm/issues/2)) built with [unjs/unplugin](https://github.com/unjs/unplugin)
21
+ - [x] Rollup
22
+ - [ ] Tools to operate and inspect `.wasm` files ([unjs/unwasm#3](https://github.com/unjs/unwasm/issues/3))
23
+ - [ ] Runtime utils ([unjs/unwasm#4](https://github.com/unjs/unwasm/issues/4))
24
+ - [ ] ESM loader for Node.js and other JavaScript runtimes ([unjs/unwasm#5](https://github.com/unjs/unwasm/issues/5))
25
+ - [ ] Integration with [Wasmer](https://github.com/wasmerio) ([unjs/unwasm#6](https://github.com/unjs/unwasm/issues/6))
26
+ - [ ] Convention and tools for library authors exporting wasm modules ([unjs/unwasm#7](https://github.com/unjs/unwasm/issues/7))
27
+
28
+ ## Install
29
+
30
+ Install package from [npm](https://www.npmjs.com/package/unwasm):
31
+
32
+ ```sh
33
+ # npm
34
+ npm install unwasm
35
+
36
+ # yarn
37
+ yarn add unwasm
38
+
39
+ # pnpm
40
+ pnpm install unwasm
41
+
42
+ # bun
43
+ bun install unwasm
44
+ ```
45
+
46
+ ## Using build plugin
47
+
48
+ ###### Rollup
49
+
50
+ ```js
51
+ import unwasmPlugin from "unwasm/plugin";
52
+
53
+ export default {
54
+ plugins: [
55
+ unwasmPlugin.rollup({
56
+ /* options */
57
+ }),
58
+ ],
59
+ };
60
+ ```
61
+
62
+ ### Options
63
+
64
+ - `esmImport`: Direct import the wasm file instead of bundling, required in Cloudflare Workers (default is `false`)
65
+ - `lazy`: Import `.wasm` files using a lazily evaluated promise for compatibility with runtimes without top-level await support (default is `false`)
66
+
67
+ ## Development
68
+
69
+ - Clone this repository
70
+ - Install the latest LTS version of [Node.js](https://nodejs.org/en/)
71
+ - Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable`
72
+ - Install dependencies using `pnpm install`
73
+ - Run interactive tests using `pnpm dev`
74
+
75
+ ## License
76
+
77
+ Made with 💛
78
+
79
+ Published under [MIT License](./LICENSE).
80
+
81
+ <!-- Badges -->
82
+
83
+ [npm-version-src]: https://img.shields.io/npm/v/unwasm?style=flat&colorA=18181B&colorB=F0DB4F
84
+ [npm-version-href]: https://npmjs.com/package/unwasm
85
+ [npm-downloads-src]: https://img.shields.io/npm/dm/unwasm?style=flat&colorA=18181B&colorB=F0DB4F
86
+ [npm-downloads-href]: https://npmjs.com/package/unwasm
87
+ [codecov-src]: https://img.shields.io/codecov/c/gh/unjs/unwasm/main?style=flat&colorA=18181B&colorB=F0DB4F
88
+ [codecov-href]: https://codecov.io/gh/unjs/unwasm
@@ -0,0 +1,21 @@
1
+ import { Plugin } from 'rollup';
2
+
3
+ interface UnwasmPluginOptions {
4
+ /**
5
+ * Direct import the wasm file instead of bundling, required in Cloudflare Workers
6
+ *
7
+ * @default false
8
+ */
9
+ esmImport?: boolean;
10
+ /**
11
+ * Import `.wasm` files using a lazily evaluated promise for compatibility with runtimes without top-level await support
12
+ *
13
+ * @default false
14
+ */
15
+ lazy?: boolean;
16
+ }
17
+ declare const _default: {
18
+ rollup: (opts: UnwasmPluginOptions) => Plugin<any>;
19
+ };
20
+
21
+ export { type UnwasmPluginOptions, _default as default };
@@ -0,0 +1,21 @@
1
+ import { Plugin } from 'rollup';
2
+
3
+ interface UnwasmPluginOptions {
4
+ /**
5
+ * Direct import the wasm file instead of bundling, required in Cloudflare Workers
6
+ *
7
+ * @default false
8
+ */
9
+ esmImport?: boolean;
10
+ /**
11
+ * Import `.wasm` files using a lazily evaluated promise for compatibility with runtimes without top-level await support
12
+ *
13
+ * @default false
14
+ */
15
+ lazy?: boolean;
16
+ }
17
+ declare const _default: {
18
+ rollup: (opts: UnwasmPluginOptions) => Plugin<any>;
19
+ };
20
+
21
+ export { type UnwasmPluginOptions, _default as default };
@@ -0,0 +1,129 @@
1
+ import { existsSync, promises } from 'node:fs';
2
+ import { basename } from 'pathe';
3
+ import MagicString from 'magic-string';
4
+ import { createUnplugin } from 'unplugin';
5
+ import { createHash } from 'node:crypto';
6
+
7
+ function sha1(source) {
8
+ return createHash("sha1").update(source).digest("hex").slice(0, 16);
9
+ }
10
+
11
+ const WASM_EXTERNAL_ID = "\0unwasm:external:";
12
+ const unplugin = createUnplugin((opts) => {
13
+ const assets = /* @__PURE__ */ Object.create(null);
14
+ return {
15
+ name: "unwasm",
16
+ rollup: {
17
+ async resolveId(id, importer) {
18
+ if (id.startsWith(WASM_EXTERNAL_ID)) {
19
+ return {
20
+ id,
21
+ external: true
22
+ };
23
+ }
24
+ if (id.endsWith(".wasm")) {
25
+ const r = await this.resolve(id, importer, { skipSelf: true });
26
+ if (r?.id && r?.id !== id) {
27
+ return {
28
+ id: r.id.startsWith("file://") ? r.id.slice(7) : r.id,
29
+ external: false,
30
+ moduleSideEffects: false,
31
+ syntheticNamedExports: false
32
+ };
33
+ }
34
+ }
35
+ },
36
+ generateBundle() {
37
+ if (opts.esmImport) {
38
+ for (const asset of Object.values(assets)) {
39
+ this.emitFile({
40
+ type: "asset",
41
+ source: asset.source,
42
+ fileName: asset.name
43
+ });
44
+ }
45
+ }
46
+ }
47
+ },
48
+ async load(id) {
49
+ if (!id.endsWith(".wasm") || !existsSync(id)) {
50
+ return;
51
+ }
52
+ const source = await promises.readFile(id);
53
+ const name = `wasm/${basename(id, ".wasm")}-${sha1(source)}.wasm`;
54
+ assets[id] = { name, source };
55
+ return `export default "WASM";`;
56
+ },
57
+ transform(_code, id) {
58
+ if (!id.endsWith(".wasm")) {
59
+ return;
60
+ }
61
+ const asset = assets[id];
62
+ if (!asset) {
63
+ return;
64
+ }
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
+ return {
77
+ code: `export default ${_str};`,
78
+ map: { mappings: "" },
79
+ syntheticNamedExports: true
80
+ };
81
+ },
82
+ renderChunk(code, chunk) {
83
+ if (!chunk.moduleIds.some((id) => id.endsWith(".wasm")) || !code.includes(WASM_EXTERNAL_ID)) {
84
+ return;
85
+ }
86
+ const s = new MagicString(code);
87
+ const resolveImport = (id) => {
88
+ if (typeof id !== "string") {
89
+ return;
90
+ }
91
+ const asset = assets[id];
92
+ if (!asset) {
93
+ return;
94
+ }
95
+ const nestedLevel = chunk.fileName.split("/").length - 1;
96
+ const relativeId = (nestedLevel ? "../".repeat(nestedLevel) : "./") + asset.name;
97
+ return {
98
+ relativeId,
99
+ asset
100
+ };
101
+ };
102
+ const ReplaceRE = new RegExp(`${WASM_EXTERNAL_ID}([^"']+)`, "g");
103
+ for (const match of code.matchAll(ReplaceRE)) {
104
+ const resolved = resolveImport(match[1]);
105
+ const index = match.index;
106
+ const len = match[0].length;
107
+ if (!resolved || !index) {
108
+ console.warn(
109
+ `Failed to resolve WASM import: ${JSON.stringify(match[1])}`
110
+ );
111
+ continue;
112
+ }
113
+ s.overwrite(index, index + len, resolved.relativeId);
114
+ }
115
+ if (s.hasChanged()) {
116
+ return {
117
+ code: s.toString(),
118
+ map: s.generateMap({ includeContent: true })
119
+ };
120
+ }
121
+ }
122
+ };
123
+ });
124
+ const rollup = unplugin.rollup;
125
+ const plugin = {
126
+ rollup
127
+ };
128
+
129
+ export { plugin as default };
package/package.json CHANGED
@@ -1 +1,50 @@
1
- {"name":"unwasm","version":"0.0.0"}
1
+ {
2
+ "name": "unwasm",
3
+ "version": "0.0.1",
4
+ "description": "WebAssembly tools for JavaScript",
5
+ "repository": "unjs/unwasm",
6
+ "license": "MIT",
7
+ "sideEffects": false,
8
+ "type": "module",
9
+ "exports": {
10
+ "./plugin": {
11
+ "types": "./dist/plugin.d.mts",
12
+ "import": "./dist/plugin.mjs"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "unbuild",
20
+ "dev": "vitest dev",
21
+ "lint": "eslint --cache --ext .ts,.js,.mjs,.cjs . && prettier -c src test",
22
+ "lint:fix": "eslint --cache --ext .ts,.js,.mjs,.cjs . --fix && prettier -c src test -w",
23
+ "prepack": "pnpm build",
24
+ "release": "pnpm test && changelogen --release && npm publish && git push --follow-tags",
25
+ "test": "pnpm lint && pnpm test:types && vitest run --coverage",
26
+ "test:types": "tsc --noEmit --skipLibCheck"
27
+ },
28
+ "dependencies": {
29
+ "magic-string": "^0.30.5",
30
+ "mlly": "^1.4.2",
31
+ "pathe": "^1.1.1",
32
+ "unplugin": "^1.6.0"
33
+ },
34
+ "devDependencies": {
35
+ "@rollup/plugin-node-resolve": "^15.2.3",
36
+ "@types/node": "^20.10.5",
37
+ "@vitest/coverage-v8": "^1.1.0",
38
+ "changelogen": "^0.5.5",
39
+ "eslint": "^8.56.0",
40
+ "eslint-config-unjs": "^0.2.1",
41
+ "jiti": "^1.21.0",
42
+ "prettier": "^3.1.1",
43
+ "rollup": "^4.9.1",
44
+ "typescript": "^5.3.3",
45
+ "unbuild": "^2.0.0",
46
+ "vite": "^5.0.10",
47
+ "vitest": "^1.1.0"
48
+ },
49
+ "packageManager": "pnpm@8.12.1"
50
+ }