vite-plugin-wat2wasm 2.1.2 → 2.2.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 +13 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.js +135 -10
- package/dist/index.js.map +1 -1
- package/dist/types-next.d.ts +7 -0
- package/dist/types.d.ts +3 -2
- package/package.json +3 -1
package/README.md
CHANGED
|
@@ -46,6 +46,8 @@ or include it in your `tsconfig.json` file
|
|
|
46
46
|
}
|
|
47
47
|
```
|
|
48
48
|
|
|
49
|
+
If you wish to use the `compileOptions` parameter supported on later browser versions by native WebAssembly instantiation functions, you can use `"vite-plugin-wat2wasm/types-next"` instead of `"vite-plugin-wat2wasm/types"` for your types.
|
|
50
|
+
|
|
49
51
|
### Using it in your application/library
|
|
50
52
|
|
|
51
53
|
``` ts
|
|
@@ -106,6 +108,8 @@ The configuration settings for `vite-plugin-wat2wasm`.
|
|
|
106
108
|
- `parser?:` [`WasmParserOptions`](#wasmparseroptions) `= {}` - Configures WebAssembly features you wish to enable for `vite-plugin-wat2wasm`.
|
|
107
109
|
- `generator?:` [`WasmGeneratorOptions`](#wasmgeneratoroptions) `= {}` - Configures how `vite-plugin-wat2wasm` to generate WebAssembly output.
|
|
108
110
|
|
|
111
|
+
- `enableCompileOptions?`: [`EnableCompileOptionsValue`](#enablecompileoptionsvalue) - Determine whether the `compileOptions` parameter will be used when instantiating WebAssembly modules and how will it be resolved if there is no support.
|
|
112
|
+
|
|
109
113
|
- `fetchTargets?:` [`FetchTarget`](#fetchtarget) `|` [`FetchTarget`](#fetchtarget)`[]` `= ["browser" | "node"]` - Determines the runtimes that can be targeted when the WebAssembly modules are fetched. Does not affect anything if `inlineAssemblies` is set to `true`.
|
|
110
114
|
|
|
111
115
|
- `utilDirPath?:` `string` - The directory path where utility functions used by JavaScript files to retrieve and interact with WebAssembly modules will be stored.
|
|
@@ -118,11 +122,18 @@ See [`wabt.WasmFeatures`](https://github.com/AssemblyScript/wabt.js/blob/main/RE
|
|
|
118
122
|
|
|
119
123
|
See [`wabt.ToBinaryOptions`](https://github.com/AssemblyScript/wabt.js/blob/main/README.md) for more info.
|
|
120
124
|
|
|
125
|
+
### `EnableCompileOptionsValue`
|
|
126
|
+
|
|
127
|
+
The values supported by the `enableCompileOptions` setting in the plugin configuration object.
|
|
128
|
+
|
|
129
|
+
- `boolean` - Force to enable or disable the `compileOptions` parameter.
|
|
130
|
+
|
|
131
|
+
- `"auto"` - Automatically use the `compileOptions` parameter if it is supported and provided, else it warns the user and instanatiates WebAssembly modules without it.
|
|
132
|
+
- `"polyfill"` - Polyfills features based on the `compileOptions` argument if it is not supported natively.
|
|
133
|
+
|
|
121
134
|
### `FetchTarget`
|
|
122
135
|
|
|
123
136
|
The runtimes supported as targets when fetching WebAssembly modules.
|
|
124
137
|
|
|
125
|
-
#### List of Values
|
|
126
|
-
|
|
127
138
|
- `"browser"` - Enable support for browser-based runtimes.
|
|
128
139
|
- `"node"` - Enable support for Node-based runtimes.
|
package/dist/index.d.ts
CHANGED
|
@@ -15,11 +15,15 @@ interface Wat2WasmOptions {
|
|
|
15
15
|
parser?: WasmParserOptions;
|
|
16
16
|
/** Configures how `vite-plugin-wat2wasm` to generate WebAssembly output. @default {} @see {@link WasmGeneratorOptions|`WasmGeneratorOptions`} */
|
|
17
17
|
generator?: WasmGeneratorOptions;
|
|
18
|
+
/** Determine whether the `compileOptions` parameter will be used when instantiating WebAssembly modules and how will it be resolved if there is no support. */
|
|
19
|
+
enableCompileOptions?: EnableCompileOptionsValue;
|
|
18
20
|
/** Determines the runtimes that can be targeted when the WebAssembly modules are fetched. Does not affect anything if `inlineAssemblies` is set to `true`. */
|
|
19
21
|
fetchTargets?: FetchTarget | FetchTarget[];
|
|
20
22
|
/** The directory path where utility functions used by JavaScript files to retrieve and interact with WebAssembly modules will be stored. */
|
|
21
23
|
utilDirPath?: string;
|
|
22
24
|
}
|
|
25
|
+
/** The values supported by the `enableCompileOptions` setting in the plugin configuration object. */
|
|
26
|
+
type EnableCompileOptionsValue = boolean | "auto" | "polyfill";
|
|
23
27
|
/** The runtimes supported as targets when fetching WebAssembly modules. */
|
|
24
28
|
type FetchTarget = "browser" | "node";
|
|
25
29
|
/** Enables compilation of `.wat` files and generation of WebAssembly, with modifiable settings.
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,136 @@
|
|
|
1
|
-
import e from"fs/promises";import t from"path";import n from"crypto";import r from"wabt";const i=await r();var a=(r={})=>{let{inlineAssemblies:a=!1,parser:o={},generator:s={},fetchTargets:
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import e from"fs/promises";import t from"path";import n from"crypto";import r from"wabt";const i=await r();var a=(r={})=>{let{inlineAssemblies:a=!1,parser:o={},generator:s={},enableCompileOptions:c=`auto`,fetchTargets:l=[`browser`,`node`],utilDirPath:u=`./__wasm-utils`}=r,d=`wat2wasm`,f=d+`:`+n.randomBytes(4).toString(`hex`),p=d+`:`+n.randomBytes(4).toString(`hex`),m=t.join(u,`fetchWasm.js`),h=t.join(u,`generateNextArguments.js`),g,_,v,y=l.includes(`browser`),b=l.includes(`node`),x={},S=!1,C=`import { generateNextArguments } from "${p}";
|
|
2
|
+
|
|
3
|
+
export async function fetchWasm(filename, parentPath, imports, compileOptions) {
|
|
4
|
+
`+(y?` if (typeof window !== "undefined" && typeof document !== "undefined") return WebAssembly.instantiateStreaming(fetch(new URL(filename, parentPath)), ...await generateNextArguments(imports, compileOptions));`:``)+`
|
|
5
|
+
`+(b?` if (typeof process !== "undefined" && "versions" in process && "node" in process.versions) return WebAssembly.instantiate(await (await import("fs/promises").then(({ readFile }) => readFile))(filename), ...await generateNextArguments(imports, compileOptions));`:``)+`
|
|
4
6
|
|
|
5
7
|
throw new Error("The runtime used to import this WebAssembly module is not supported. If this is a mistake, adjust your fetchTargets to fit the specific runtime.");
|
|
6
8
|
}
|
|
7
|
-
`,
|
|
8
|
-
|
|
9
|
+
`,w=`export async function generateNextArguments(imports, compileOptions) {
|
|
10
|
+
if (typeof compileOptions !== "object" || compileOptions === null) return [imports];
|
|
11
|
+
`+(typeof c==`boolean`?c?` return [imports, compileOptions];`:` return [imports];`:`
|
|
12
|
+
const supportsCompileOptions = await (async () => {
|
|
13
|
+
try {
|
|
14
|
+
await WebAssembly.compile(new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]), { builtins: [], importedStringConstants: null });
|
|
15
|
+
return true;
|
|
16
|
+
} catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
})();
|
|
20
|
+
|
|
21
|
+
if (supportsCompileOptions) return [imports, compileOptions];
|
|
22
|
+
|
|
23
|
+
`+(c===`auto`?` console.warn("This runtime does not support compileOptions for WebAssembly instantiation. If this is a mistake, make sure that the enableCompileOptions setting has been set appropriately in your configuration.");`:` if ("builtins" in compileOptions) {
|
|
24
|
+
const builtins = compileOptions.builtins;
|
|
25
|
+
|
|
26
|
+
if (builtins.includes("js-string")) {
|
|
27
|
+
const jsString = {
|
|
28
|
+
cast(obj) {
|
|
29
|
+
if (obj === null || typeof obj !== "string") throw WebAssembly.RuntimeError("externref obj passed into wasm:js-string.cast is not castable as a string.");
|
|
30
|
+
return obj;
|
|
31
|
+
},
|
|
32
|
+
|
|
33
|
+
compare($a, $b) {
|
|
34
|
+
const a = this.cast($a);
|
|
35
|
+
const b = this.cast($b);
|
|
36
|
+
|
|
37
|
+
if (a === b) return 0;
|
|
38
|
+
return a < b ? -1 : 1;
|
|
39
|
+
},
|
|
40
|
+
|
|
41
|
+
concat($a, $b) {
|
|
42
|
+
const a = this.cast($a);
|
|
43
|
+
const b = this.cast($b);
|
|
44
|
+
|
|
45
|
+
return a.concat(b);
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
charCodeAt($str, i) {
|
|
49
|
+
const str = this.cast($str);
|
|
50
|
+
return str.charCodeAt(i >>> 0);
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
codePointAt($str, i) {
|
|
54
|
+
const str = this.cast($str);
|
|
55
|
+
|
|
56
|
+
i >>>= 0;
|
|
57
|
+
if (i > str.length) throw new WebAssembly.RuntimeError("index exceeds passed string length.");
|
|
58
|
+
|
|
59
|
+
return str.codePointAt(i);
|
|
60
|
+
},
|
|
61
|
+
|
|
62
|
+
equals(a, b) {
|
|
63
|
+
if (
|
|
64
|
+
(a !== null && typeof a !== "string") ||
|
|
65
|
+
(b !== null && typeof b !== "string")
|
|
66
|
+
) throw new WebAssembly.RuntimeError("externref obj is not a string or a null reference.");
|
|
67
|
+
|
|
68
|
+
return a === b ? 1 : 0;
|
|
69
|
+
},
|
|
70
|
+
|
|
71
|
+
fromCharCode(code) {
|
|
72
|
+
return String.fromCharCode(code >>> 0);
|
|
73
|
+
},
|
|
74
|
+
|
|
75
|
+
fromCodePoint(point) {
|
|
76
|
+
point >>>= 0;
|
|
77
|
+
if (point > 0x0010_ffff) throw new WebAssembly.RuntimeError("passed code point is not a valid Unicode code point.");
|
|
78
|
+
|
|
79
|
+
return String.fromCodePoint(point);
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
length($str) {
|
|
83
|
+
const str = this.cast($str);
|
|
84
|
+
return str.length;
|
|
85
|
+
},
|
|
86
|
+
|
|
87
|
+
substring($str, iStart, iEnd) {
|
|
88
|
+
const str = this.cast($str);
|
|
89
|
+
|
|
90
|
+
iStart >>>= 0;
|
|
91
|
+
iEnd >>>= 0;
|
|
92
|
+
|
|
93
|
+
if (iStart > iEnd || iStart > str.length) return "";
|
|
94
|
+
return str.substring(iStart, iEnd);
|
|
95
|
+
},
|
|
96
|
+
|
|
97
|
+
test(obj) {
|
|
98
|
+
return typeof obj === "string" ? 1 : 0;
|
|
99
|
+
},
|
|
100
|
+
|
|
101
|
+
fromCharCodeArray(_arr, _iStart, _iEnd) {
|
|
102
|
+
throw new WebAssembly.RuntimeError("wasm:js-string.fromCharCodeArray cannot be polyfilled as it requires WASM GC arrays, which cannot be accessed or mutated in JavaScript. It is recommended that you implement the function yourself using wasm:js-string.fromCharCode instead.");
|
|
103
|
+
},
|
|
104
|
+
|
|
105
|
+
intoCharCodeArray(_str, _arr, _iStart) {
|
|
106
|
+
throw new WebAssembly.RuntimeError("wasm:js-string.intoCharCodeArray cannot be polyfilled as it requires WASM GC arrays, which cannot be accessed or mutated in JavaScript. It is recommended that you implement the function yourself using wasm:js-string.charCodeAt instead.");
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
imports = { ...imports, ["wasm:js-string"]: jsString };
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if ("importedStringConstants" in compileOptions) {
|
|
115
|
+
const strModuleName = compileOptions.importedStringConstants;
|
|
116
|
+
|
|
117
|
+
const wasmModule = await WebAssembly.compile(bfr);
|
|
118
|
+
const importDescriptors = WebAssembly.Module.imports(wasmModule);
|
|
119
|
+
|
|
120
|
+
const strModule = {};
|
|
121
|
+
|
|
122
|
+
const strConstants = importDescriptors.filter((desc) => desc.module === strModuleName && desc.kind === "global").map((desc) => desc.name);
|
|
123
|
+
for (const str of strConstants) strModule[str] = str;
|
|
124
|
+
|
|
125
|
+
imports = { ...imports, [strModuleName]: strModule };
|
|
126
|
+
}`)+`
|
|
127
|
+
|
|
128
|
+
return [imports];`)+`
|
|
129
|
+
}
|
|
130
|
+
`,T=(e,t)=>a||v?`
|
|
131
|
+
import { generateNextArguments } from "${p}";
|
|
132
|
+
|
|
133
|
+
export default async (imports = {}, compileOptions = null) => {
|
|
9
134
|
const data = atob("${btoa(String.fromCharCode(...e))}");
|
|
10
135
|
|
|
11
136
|
const len = data.length;
|
|
@@ -13,11 +138,11 @@ import e from"fs/promises";import t from"path";import n from"crypto";import r fr
|
|
|
13
138
|
const bfr = new Uint8Array(len);
|
|
14
139
|
for (let i = 0; i < len; i++) bfr[i] = data.charCodeAt(i);
|
|
15
140
|
|
|
16
|
-
return WebAssembly.instantiate(bfr).then((src) => src.instance.exports);
|
|
141
|
+
return WebAssembly.instantiate(bfr, ... await generateNextArguments(imports, compileOptions)).then((src) => src.instance.exports);
|
|
17
142
|
};
|
|
18
143
|
`:`
|
|
19
|
-
import { fetchWasm } from "${
|
|
20
|
-
export default (imports = {}) => fetchWasm("${t.startsWith(`.`)?t:`./`+t}", import.meta.url, imports).then((src) => src.instance.exports);
|
|
21
|
-
`;return{name:`wat2wasm`,enforce:`pre`,transform(e,n){if(!n.endsWith(`.wat`))return null;n=n.replaceAll(`\\`,`/`);let r=t.relative(
|
|
22
|
-
\x1B[39m`+c.log);let l=c.buffer;return
|
|
144
|
+
import { fetchWasm } from "${f}";
|
|
145
|
+
export default (imports = {}, compileOptions = null) => fetchWasm("${t.startsWith(`.`)?t:`./`+t}", import.meta.url, imports, compileOptions).then((src) => src.instance.exports);
|
|
146
|
+
`;return{name:`wat2wasm`,enforce:`pre`,transform(e,n){if(!n.endsWith(`.wat`))return null;n=n.replaceAll(`\\`,`/`);let r=t.relative(g,n),a=t.basename(n,`.wat`),c=i.parseWat(a+`.wat`,e,o).toBinary(s);s.log&&console.log(`\x1B[1;35m[plugin-wat2wasm]\x1B[0;39m \x1B[36mLog Output\x1B[39m - \x1B[92m`+r+`
|
|
147
|
+
\x1B[39m`+c.log);let l=c.buffer;return x[n]=l,T(l,a+`.wasm`)},generateBundle(e,n){if(!a)for(let[e,r]of Object.entries(n)){if(r.type===`asset`)continue;e=e.replaceAll(`\\`,`/`);let n=t.join(e,`../`),i=r.moduleIds;for(let e of i){if(e=e.replaceAll(`\\`,`/`),!(e in x))continue;let r=t.basename(e,`.wat`)+`.wasm`,i=t.join(n,r),a=x[e];this.emitFile({type:`asset`,source:a,fileName:i})}let a=t.relative(n,m).replaceAll(`\\`,`/`),o=t.relative(n,h).replaceAll(`\\`,`/`);r.code=r.code.replaceAll(f,a.startsWith(`.`)?a:`./`+a).replaceAll(p,o.startsWith(`.`)?o:`./`+o)}},buildStart(){if(`data`in this){let e=this.data;g=(e.outputOptions.preserveModules?e.outputOptions.preserveModulesRoot:t.join(e.outputOptions.dir,`../`)).replaceAll(`\\`,`/`),_=e.outputOptions.dir.replaceAll(`\\`,`/`),v=!1}S=!(a||v)},resolveId(e){return e===f?`\0`+f:e===p?`\0`+p:null},load(e){return e.startsWith(`\0`)?e.endsWith(f)?C:e.endsWith(p)?w:null:null},async closeBundle(){if(S){let n=t.join(_,m).replaceAll(`\\`,`/`),r=t.join(n,`../`).replaceAll(`\\`,`/`),i=t.basename(h);await e.mkdir(r,{recursive:!0}),await e.writeFile(n,C.replaceAll(p,`./`+i),`utf-8`)}let n=t.join(_,h).replaceAll(`\\`,`/`),r=t.join(n,`../`).replaceAll(`\\`,`/`);await e.mkdir(r,{recursive:!0}),await e.writeFile(n,w,`utf-8`)},configResolved(e){g=e.root.replaceAll(`\\`,`/`),_=t.join(g,e.build.outDir).replaceAll(`\\`,`/`),v=e.command===`serve`}}};export{a as default};
|
|
23
148
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["root: string","rootDist: string","isServing: boolean","filesToEmit: Record<string, Uint8Array>","fetchWasmEmit: boolean","fetchWasmFunc: string"],"sources":["../src/index.ts"],"sourcesContent":["import fs from \"fs/promises\";\r\nimport path from \"path\";\r\n\r\nimport crypto from \"crypto\";\r\n\r\nimport type { Plugin } from \"vite\";\r\nimport initWabt from \"wabt\";\r\n\r\nconst wabt = await initWabt();\r\n\r\ntype WabtParserFunc = Awaited<ReturnType<typeof initWabt>>[\"parseWat\"];\r\n\r\n/** See @see {@link https://github.com/AssemblyScript/wabt.js/blob/main/README.md|`wabt.WasmFeatures`} for more info. @see WasmParserOptions */\r\ntype WasmParserOptions = Parameters<WabtParserFunc>[2];\r\n\r\n/** See @see {@link https://github.com/AssemblyScript/wabt.js/blob/main/README.md|`wabt.ToBinaryOptions`} for more info. @see WasmGeneratorOptions */\r\ntype WasmGeneratorOptions = Parameters<ReturnType<WabtParserFunc>[\"toBinary\"]>[0];\r\n\r\n/** The configuration settings for `vite-plugin-wat2wasm`. @see Wat2WasmOptions */\r\ninterface Wat2WasmOptions {\r\n /** Whether to inline generated WebAssembly output within JavaScript files when transforming `.wat` files. */\r\n inlineAssemblies?: boolean;\r\n\r\n /** Configures WebAssembly features you wish to enable for `vite-plugin-wat2wasm`. @default {} @see {@link WasmParserOptions|`WasmParserOptions`} */\r\n parser?: WasmParserOptions;\r\n\r\n /** Configures how `vite-plugin-wat2wasm` to generate WebAssembly output. @default {} @see {@link WasmGeneratorOptions|`WasmGeneratorOptions`} */\r\n generator?: WasmGeneratorOptions;\r\n\r\n /** Determines the runtimes that can be targeted when the WebAssembly modules are fetched. Does not affect anything if `inlineAssemblies` is set to `true`. */\r\n fetchTargets?: FetchTarget | FetchTarget[];\r\n\r\n /** The directory path where utility functions used by JavaScript files to retrieve and interact with WebAssembly modules will be stored. */\r\n utilDirPath?: string;\r\n}\r\n\r\n/** The runtimes supported as targets when fetching WebAssembly modules. */\r\ntype FetchTarget = \"browser\" | \"node\";\r\n\r\n/** Enables compilation of `.wat` files and generation of WebAssembly, with modifiable settings.\r\n *\r\n * @param options - the configuration options for `vite-plugin-wat2wasm`. @see {@link Wat2WasmOptions|`Wat2WasmOptions`}\r\n * @returns a Vite plugin object that allows for compilation of `.wat` files. @see {@link https://vite.dev/guide/api-plugin|`Plugin`}\r\n */\r\nconst wat2WasmPlugin = (options: Wat2WasmOptions = {}): Plugin => {\r\n const {\r\n inlineAssemblies = false,\r\n\r\n parser: parserOptions = {},\r\n generator: generatorOptions = {},\r\n\r\n fetchTargets = [\"browser\", \"node\"],\r\n utilDirPath = \"./__wasm-utils\"\r\n } = options;\r\n\r\n const PLUGIN_ID: string = \"wat2wasm\";\r\n const FETCH_WASM_ID = PLUGIN_ID + \":\" + crypto.randomBytes(4).toString(\"hex\");\r\n\r\n const FETCH_WASM_PATH = path.join(utilDirPath, \"fetchWasm.js\");\r\n\r\n let root: string;\r\n let rootDist: string;\r\n\r\n let isServing: boolean;\r\n\r\n const targetsBrowser = fetchTargets.includes(\"browser\");\r\n const targetsNode = fetchTargets.includes(\"node\" );\r\n\r\n const filesToEmit: Record<string, Uint8Array> = {};\r\n\r\n let fetchWasmEmit: boolean = false;\r\n const fetchWasmFunc: string =\r\n `export async function fetchWasm(filename, parentPath, imports) {` + \"\\n\" +\r\n (targetsBrowser ? ` if (typeof window !== \"undefined\" && typeof document !== \"undefined\") return WebAssembly.instantiateStreaming(fetch(new URL(filename, parentPath)), imports);` : \"\") + \"\\n\" +\r\n (targetsNode ? ` if (typeof process !== \"undefined\" && \"versions\" in process && \"node\" in process.versions) return WebAssembly.instantiate(await (await import(\"fs/promises\").then(({ readFile }) => readFile))(filename), imports);` : \"\") + \"\\n\" +\r\n \"\\n\" +\r\n ` throw new Error(\"The runtime used to import this WebAssembly module is not supported. If this is a mistake, adjust your fetchTargets to fit the specific runtime.\");` + \"\\n\" +\r\n `}` + \"\\n\";\r\n\r\n const transformWasm = (bfr: Uint8Array, filename: string) => inlineAssemblies || isServing\r\n ?\r\n `\r\n export default async (imports = {}) => {\r\n const data = atob(\"${btoa(String.fromCharCode(...bfr))}\");\r\n\r\n const len = data.length;\r\n\r\n const bfr = new Uint8Array(len);\r\n for (let i = 0; i < len; i++) bfr[i] = data.charCodeAt(i);\r\n\r\n return WebAssembly.instantiate(bfr).then((src) => src.instance.exports);\r\n };\r\n `\r\n :\r\n `\r\n import { fetchWasm } from \"${FETCH_WASM_ID}\";\r\n export default (imports = {}) => fetchWasm(\"${filename.startsWith(\".\") ? filename : \"./\" + filename}\", import.meta.url, imports).then((src) => src.instance.exports);\r\n `;\r\n\r\n return {\r\n name: \"wat2wasm\",\r\n enforce: \"pre\",\r\n\r\n transform(code: string, pathId: string) {\r\n if (!pathId.endsWith(\".wat\")) return null;\r\n\r\n pathId = pathId.replaceAll(\"\\\\\", \"/\");\r\n\r\n const pathRel = path.relative(root, pathId);\r\n const basename = path.basename(pathId, \".wat\");\r\n\r\n const module = wabt.parseWat(basename + \".wat\", code, parserOptions);\r\n\r\n const output = module.toBinary(generatorOptions);\r\n if (generatorOptions.log) console.log(\"\\x1b[1;35m[plugin-wat2wasm]\\x1b[0;39m \\x1b[36mLog Output\\x1b[39m - \\x1b[92m\" + pathRel + \"\\n\" + \"\\x1b[39m\" + output.log);\r\n\r\n const bfr = output.buffer;\r\n\r\n filesToEmit[pathId] = bfr;\r\n\r\n return transformWasm(bfr, basename + \".wasm\");\r\n },\r\n\r\n generateBundle(_options, bundles) {\r\n if (inlineAssemblies) return;\r\n\r\n for (let [pathBundle, bundle] of Object.entries(bundles)) {\r\n if (bundle.type === \"asset\") continue;\r\n\r\n pathBundle = pathBundle.replaceAll(\"\\\\\", \"/\");\r\n\r\n const pathParent = path.join(pathBundle, \"../\");\r\n\r\n const modules = bundle.moduleIds;\r\n for (let pathModule of modules) {\r\n pathModule = pathModule.replaceAll(\"\\\\\", \"/\");\r\n if (!(pathModule in filesToEmit)) continue;\r\n\r\n const filename = path.basename(pathModule, \".wat\") + \".wasm\";\r\n const pathEmittedFile = path.join(pathParent, filename);\r\n\r\n const bfr = filesToEmit[pathModule]!;\r\n\r\n this.emitFile({\r\n type: \"asset\",\r\n\r\n source: bfr,\r\n fileName: pathEmittedFile\r\n });\r\n }\r\n\r\n const fetchWasmPathRel = path.relative(pathParent, FETCH_WASM_PATH).replaceAll(\"\\\\\", \"/\");\r\n\r\n bundle.code = bundle.code.replaceAll(FETCH_WASM_ID, fetchWasmPathRel.startsWith(\".\") ? fetchWasmPathRel : \"./\" + fetchWasmPathRel);\r\n }\r\n },\r\n\r\n buildStart() {\r\n if (\"data\" in this) {\r\n const data = this.data as any;\r\n\r\n root = (data.outputOptions.preserveModules ? data.outputOptions.preserveModulesRoot : path.join(data.outputOptions.dir, \"../\")).replaceAll(\"\\\\\", \"/\");\r\n rootDist = data.outputOptions.dir.replaceAll(\"\\\\\", \"/\");\r\n\r\n isServing = false;\r\n }\r\n\r\n fetchWasmEmit = !(inlineAssemblies || isServing);\r\n },\r\n\r\n async closeBundle() {\r\n if (fetchWasmEmit) {\r\n const fetchWasmPath = path.join(rootDist, FETCH_WASM_PATH).replaceAll(\"\\\\\", \"/\");\r\n const fetchWasmParent = path.join(fetchWasmPath, \"../\").replaceAll(\"\\\\\", \"/\");\r\n\r\n await fs.mkdir(fetchWasmParent, { recursive: true });\r\n await fs.writeFile(fetchWasmPath, fetchWasmFunc, \"utf-8\");\r\n }\r\n },\r\n\r\n configResolved(config) {\r\n root = config.root.replaceAll(\"\\\\\", \"/\");\r\n rootDist = path.join(root, config.build.outDir).replaceAll(\"\\\\\", \"/\");\r\n\r\n isServing = config.command === \"serve\";\r\n }\r\n };\r\n};\r\n\r\nexport default wat2WasmPlugin;\r\nexport type { Wat2WasmOptions, WasmParserOptions, WasmGeneratorOptions, FetchTarget };\r\n"],"mappings":"yFAQA,MAAM,EAAO,MAAM,GAAU,CAqL7B,IAAA,GAjJwB,EAA2B,EAAE,GAAa,CAC9D,GAAM,CACF,mBAAmB,GAEnB,OAAQ,EAAgB,EAAE,CAC1B,UAAW,EAAmB,EAAE,CAEhC,eAAe,CAAC,UAAW,OAAO,CAClC,cAAc,kBACd,EAGE,EAAkB,YAAkB,EAAO,YAAY,EAAE,CAAC,SAAS,MAAM,CAEzE,EAAkB,EAAK,KAAK,EAAa,eAAe,CAE1DA,EACAC,EAEAC,EAEE,EAAiB,EAAa,SAAS,UAAU,CACjD,EAAiB,EAAa,SAAS,OAAU,CAEjDC,EAA0C,EAAE,CAE9CC,EAAyB,GACvBC,EACF;GACC,EAAiB,oKAAsK,IAAM;GAC7L,EAAiB,0NAA4N,IAAM;;;;EAKlP,GAAiB,EAAiB,IAAqB,GAAoB,EAE7E;;iCAEyB,KAAK,OAAO,aAAa,GAAG,EAAI,CAAC,CAAC;;;;;;;;;UAW3D;qCAC6B,EAAc;sDACG,EAAS,WAAW,IAAI,CAAG,EAAW,KAAO,EAAS;UAGxG,MAAO,CACH,KAAM,W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M,IAAI,CACrJ,EAAW,EAAK,cAAc,IAAI,WAAW,KAAM,IAAI,CAEvD,EAAY,GAGhB,EAAgB,EAAE,GAAoB,IAG1C,MAAM,aAAc,CAChB,GAAI,EAAe,CACf,IAAM,EAAgB,EAAK,KAAK,EAAU,EAAgB,CAAC,WAAW,KAAM,IAAI,CAC1E,EAAkB,EAAK,KAAK,EAAe,MAAM,CAAC,WAAW,KAAM,IAAI,CAE7E,MAAM,EAAG,MAAM,EAAiB,CAAE,UAAW,GAAM,CAAC,CACpD,MAAM,EAAG,UAAU,EAAe,EAAe,QAAQ,GAIjE,eAAe,EAAQ,CACnB,EAAO,EAAO,KAAK,WAAW,KAAM,IAAI,CACxC,EAAW,EAAK,KAAK,EAAM,EAAO,MAAM,OAAO,CAAC,WAAW,KAAM,IAAI,CAErE,EAAY,EAAO,UAAY,SAEtC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["PLUGIN_ID: string","root: string","rootDist: string","isServing: boolean","filesToEmit: Record<string, Uint8Array>","fetchWasmEmit: boolean"],"sources":["../src/index.ts"],"sourcesContent":["import fs from \"fs/promises\";\r\nimport path from \"path\";\r\n\r\nimport crypto from \"crypto\";\r\n\r\nimport type { Plugin } from \"vite\";\r\nimport initWabt from \"wabt\";\r\n\r\nconst wabt = await initWabt();\r\n\r\ntype WabtParserFunc = Awaited<ReturnType<typeof initWabt>>[\"parseWat\"];\r\n\r\n/** See @see {@link https://github.com/AssemblyScript/wabt.js/blob/main/README.md|`wabt.WasmFeatures`} for more info. @see WasmParserOptions */\r\ntype WasmParserOptions = Parameters<WabtParserFunc>[2];\r\n\r\n/** See @see {@link https://github.com/AssemblyScript/wabt.js/blob/main/README.md|`wabt.ToBinaryOptions`} for more info. @see WasmGeneratorOptions */\r\ntype WasmGeneratorOptions = Parameters<ReturnType<WabtParserFunc>[\"toBinary\"]>[0];\r\n\r\n/** The configuration settings for `vite-plugin-wat2wasm`. @see Wat2WasmOptions */\r\ninterface Wat2WasmOptions {\r\n /** Whether to inline generated WebAssembly output within JavaScript files when transforming `.wat` files. */\r\n inlineAssemblies?: boolean;\r\n\r\n /** Configures WebAssembly features you wish to enable for `vite-plugin-wat2wasm`. @default {} @see {@link WasmParserOptions|`WasmParserOptions`} */\r\n parser?: WasmParserOptions;\r\n\r\n /** Configures how `vite-plugin-wat2wasm` to generate WebAssembly output. @default {} @see {@link WasmGeneratorOptions|`WasmGeneratorOptions`} */\r\n generator?: WasmGeneratorOptions;\r\n\r\n /** Determine whether the `compileOptions` parameter will be used when instantiating WebAssembly modules and how will it be resolved if there is no support. */\r\n enableCompileOptions?: EnableCompileOptionsValue;\r\n\r\n /** Determines the runtimes that can be targeted when the WebAssembly modules are fetched. Does not affect anything if `inlineAssemblies` is set to `true`. */\r\n fetchTargets?: FetchTarget | FetchTarget[];\r\n\r\n /** The directory path where utility functions used by JavaScript files to retrieve and interact with WebAssembly modules will be stored. */\r\n utilDirPath?: string;\r\n}\r\n\r\n/** The values supported by the `enableCompileOptions` setting in the plugin configuration object. */\r\ntype EnableCompileOptionsValue = boolean | \"auto\" | \"polyfill\";\r\n\r\n/** The runtimes supported as targets when fetching WebAssembly modules. */\r\ntype FetchTarget = \"browser\" | \"node\";\r\n\r\n/** Enables compilation of `.wat` files and generation of WebAssembly, with modifiable settings.\r\n *\r\n * @param options - the configuration options for `vite-plugin-wat2wasm`. @see {@link Wat2WasmOptions|`Wat2WasmOptions`}\r\n * @returns a Vite plugin object that allows for compilation of `.wat` files. @see {@link https://vite.dev/guide/api-plugin|`Plugin`}\r\n */\r\nconst wat2WasmPlugin = (options: Wat2WasmOptions = {}): Plugin => {\r\n const {\r\n inlineAssemblies = false,\r\n\r\n parser: parserOptions = {},\r\n generator: generatorOptions = {},\r\n\r\n enableCompileOptions = \"auto\",\r\n\r\n fetchTargets = [\"browser\", \"node\"],\r\n utilDirPath = \"./__wasm-utils\"\r\n } = options;\r\n\r\n const PLUGIN_ID: string = \"wat2wasm\";\r\n\r\n const FETCH_WASM_ID = PLUGIN_ID + \":\" + crypto.randomBytes(4).toString(\"hex\");\r\n const GENERATE_NEXT_ARGS_ID = PLUGIN_ID + \":\" + crypto.randomBytes(4).toString(\"hex\");\r\n\r\n const FETCH_WASM_PATH = path.join(utilDirPath, \"fetchWasm.js\");\r\n const GENERATE_NEXT_ARGS_PATH = path.join(utilDirPath, \"generateNextArguments.js\");\r\n\r\n let root: string;\r\n let rootDist: string;\r\n\r\n let isServing: boolean;\r\n\r\n const targetsBrowser = fetchTargets.includes(\"browser\");\r\n const targetsNode = fetchTargets.includes(\"node\" );\r\n\r\n const filesToEmit: Record<string, Uint8Array> = {};\r\n\r\n let fetchWasmEmit: boolean = false;\r\n\r\n const fetchWasmFunc =\r\n `import { generateNextArguments } from \"${GENERATE_NEXT_ARGS_ID}\";` + \"\\n\" +\r\n `` + \"\\n\" +\r\n `export async function fetchWasm(filename, parentPath, imports, compileOptions) {` + \"\\n\" +\r\n (targetsBrowser ? ` if (typeof window !== \"undefined\" && typeof document !== \"undefined\") return WebAssembly.instantiateStreaming(fetch(new URL(filename, parentPath)), ...await generateNextArguments(imports, compileOptions));` : \"\") + \"\\n\" +\r\n (targetsNode ? ` if (typeof process !== \"undefined\" && \"versions\" in process && \"node\" in process.versions) return WebAssembly.instantiate(await (await import(\"fs/promises\").then(({ readFile }) => readFile))(filename), ...await generateNextArguments(imports, compileOptions));` : \"\") + \"\\n\" +\r\n \"\\n\" +\r\n ` throw new Error(\"The runtime used to import this WebAssembly module is not supported. If this is a mistake, adjust your fetchTargets to fit the specific runtime.\");` + \"\\n\" +\r\n `}` + \"\\n\";\r\n\r\n const generateNextArgumentsFunc =\r\n `export async function generateNextArguments(imports, compileOptions) {` + \"\\n\" +\r\n ` if (typeof compileOptions !== \"object\" || compileOptions === null) return [imports];` + \"\\n\" +\r\n (\r\n typeof enableCompileOptions === \"boolean\"\r\n ? enableCompileOptions\r\n ? ` return [imports, compileOptions];`\r\n : ` return [imports];`\r\n :\r\n `` + \"\\n\" +\r\n ` const supportsCompileOptions = await (async () => {` + \"\\n\" +\r\n ` try {` + \"\\n\" +\r\n ` await WebAssembly.compile(new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]), { builtins: [], importedStringConstants: null });` + \"\\n\" +\r\n ` return true;` + \"\\n\" +\r\n ` } catch {` + \"\\n\" +\r\n ` return false;` + \"\\n\" +\r\n ` }` + \"\\n\" +\r\n ` })();` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` if (supportsCompileOptions) return [imports, compileOptions];` + \"\\n\" +\r\n `` + \"\\n\" +\r\n (\r\n enableCompileOptions === \"auto\"\r\n ?\r\n ` console.warn(\"This runtime does not support compileOptions for WebAssembly instantiation. If this is a mistake, make sure that the enableCompileOptions setting has been set appropriately in your configuration.\");`\r\n :\r\n ` if (\"builtins\" in compileOptions) {` + \"\\n\" +\r\n ` const builtins = compileOptions.builtins;` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` if (builtins.includes(\"js-string\")) {` + \"\\n\" +\r\n ` const jsString = {` + \"\\n\" +\r\n ` cast(obj) {` + \"\\n\" +\r\n ` if (obj === null || typeof obj !== \"string\") throw WebAssembly.RuntimeError(\"externref obj passed into wasm:js-string.cast is not castable as a string.\");` + \"\\n\" +\r\n ` return obj;` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` compare($a, $b) {` + \"\\n\" +\r\n ` const a = this.cast($a);` + \"\\n\" +\r\n ` const b = this.cast($b);` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` if (a === b) return 0;` + \"\\n\" +\r\n ` return a < b ? -1 : 1;` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` concat($a, $b) {` + \"\\n\" +\r\n ` const a = this.cast($a);` + \"\\n\" +\r\n ` const b = this.cast($b);` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` return a.concat(b);` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` charCodeAt($str, i) {` + \"\\n\" +\r\n ` const str = this.cast($str);` + \"\\n\" +\r\n ` return str.charCodeAt(i >>> 0);` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` codePointAt($str, i) {` + \"\\n\" +\r\n ` const str = this.cast($str);` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` i >>>= 0;` + \"\\n\" +\r\n ` if (i > str.length) throw new WebAssembly.RuntimeError(\"index exceeds passed string length.\");` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` return str.codePointAt(i);` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` equals(a, b) {` + \"\\n\" +\r\n ` if (` + \"\\n\" +\r\n ` (a !== null && typeof a !== \"string\") ||` + \"\\n\" +\r\n ` (b !== null && typeof b !== \"string\")` + \"\\n\" +\r\n ` ) throw new WebAssembly.RuntimeError(\"externref obj is not a string or a null reference.\");` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` return a === b ? 1 : 0;` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` fromCharCode(code) {` + \"\\n\" +\r\n ` return String.fromCharCode(code >>> 0);` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` fromCodePoint(point) {` + \"\\n\" +\r\n ` point >>>= 0;` + \"\\n\" +\r\n ` if (point > 0x0010_ffff) throw new WebAssembly.RuntimeError(\"passed code point is not a valid Unicode code point.\");` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` return String.fromCodePoint(point);` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` length($str) {` + \"\\n\" +\r\n ` const str = this.cast($str);` + \"\\n\" +\r\n ` return str.length;` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` substring($str, iStart, iEnd) {` + \"\\n\" +\r\n ` const str = this.cast($str);` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` iStart >>>= 0;` + \"\\n\" +\r\n ` iEnd >>>= 0;` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` if (iStart > iEnd || iStart > str.length) return \"\";` + \"\\n\" +\r\n ` return str.substring(iStart, iEnd);` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` test(obj) {` + \"\\n\" +\r\n ` return typeof obj === \"string\" ? 1 : 0;` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` fromCharCodeArray(_arr, _iStart, _iEnd) {` + \"\\n\" +\r\n ` throw new WebAssembly.RuntimeError(\"wasm:js-string.fromCharCodeArray cannot be polyfilled as it requires WASM GC arrays, which cannot be accessed or mutated in JavaScript. It is recommended that you implement the function yourself using wasm:js-string.fromCharCode instead.\");` + \"\\n\" +\r\n ` },` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` intoCharCodeArray(_str, _arr, _iStart) {` + \"\\n\" +\r\n ` throw new WebAssembly.RuntimeError(\"wasm:js-string.intoCharCodeArray cannot be polyfilled as it requires WASM GC arrays, which cannot be accessed or mutated in JavaScript. It is recommended that you implement the function yourself using wasm:js-string.charCodeAt instead.\");` + \"\\n\" +\r\n ` }` + \"\\n\" +\r\n ` };` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` imports = { ...imports, [\"wasm:js-string\"]: jsString };` + \"\\n\" +\r\n ` }` + \"\\n\" +\r\n ` }` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` if (\"importedStringConstants\" in compileOptions) {` + \"\\n\" +\r\n ` const strModuleName = compileOptions.importedStringConstants;` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` const wasmModule = await WebAssembly.compile(bfr);` + \"\\n\" +\r\n ` const importDescriptors = WebAssembly.Module.imports(wasmModule);` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` const strModule = {};` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` const strConstants = importDescriptors.filter((desc) => desc.module === strModuleName && desc.kind === \"global\").map((desc) => desc.name);` + \"\\n\" +\r\n ` for (const str of strConstants) strModule[str] = str;` + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` imports = { ...imports, [strModuleName]: strModule };` + \"\\n\" +\r\n ` }`\r\n ) + \"\\n\" +\r\n `` + \"\\n\" +\r\n ` return [imports];`\r\n ) + \"\\n\" +\r\n `}` + \"\\n\";\r\n\r\n const transformWasm = (bfr: Uint8Array, filename: string) => inlineAssemblies || isServing\r\n ?\r\n `\r\n import { generateNextArguments } from \"${GENERATE_NEXT_ARGS_ID}\";\r\n\r\n export default async (imports = {}, compileOptions = null) => {\r\n const data = atob(\"${btoa(String.fromCharCode(...bfr))}\");\r\n\r\n const len = data.length;\r\n\r\n const bfr = new Uint8Array(len);\r\n for (let i = 0; i < len; i++) bfr[i] = data.charCodeAt(i);\r\n\r\n return WebAssembly.instantiate(bfr, ... await generateNextArguments(imports, compileOptions)).then((src) => src.instance.exports);\r\n };\r\n `\r\n :\r\n `\r\n import { fetchWasm } from \"${FETCH_WASM_ID}\";\r\n export default (imports = {}, compileOptions = null) => fetchWasm(\"${filename.startsWith(\".\") ? filename : \"./\" + filename}\", import.meta.url, imports, compileOptions).then((src) => src.instance.exports);\r\n `;\r\n\r\n return {\r\n name: \"wat2wasm\",\r\n enforce: \"pre\",\r\n\r\n transform(code: string, pathId: string) {\r\n if (!pathId.endsWith(\".wat\")) return null;\r\n\r\n pathId = pathId.replaceAll(\"\\\\\", \"/\");\r\n\r\n const pathRel = path.relative(root, pathId);\r\n const basename = path.basename(pathId, \".wat\");\r\n\r\n const module = wabt.parseWat(basename + \".wat\", code, parserOptions);\r\n\r\n const output = module.toBinary(generatorOptions);\r\n if (generatorOptions.log) console.log(\"\\x1b[1;35m[plugin-wat2wasm]\\x1b[0;39m \\x1b[36mLog Output\\x1b[39m - \\x1b[92m\" + pathRel + \"\\n\" + \"\\x1b[39m\" + output.log);\r\n\r\n const bfr = output.buffer;\r\n\r\n filesToEmit[pathId] = bfr;\r\n\r\n return transformWasm(bfr, basename + \".wasm\");\r\n },\r\n\r\n generateBundle(_options, bundles) {\r\n if (inlineAssemblies) return;\r\n\r\n for (let [pathBundle, bundle] of Object.entries(bundles)) {\r\n if (bundle.type === \"asset\") continue;\r\n\r\n pathBundle = pathBundle.replaceAll(\"\\\\\", \"/\");\r\n\r\n const pathParent = path.join(pathBundle, \"../\");\r\n\r\n const modules = bundle.moduleIds;\r\n for (let pathModule of modules) {\r\n pathModule = pathModule.replaceAll(\"\\\\\", \"/\");\r\n if (!(pathModule in filesToEmit)) continue;\r\n\r\n const filename = path.basename(pathModule, \".wat\") + \".wasm\";\r\n const pathEmittedFile = path.join(pathParent, filename);\r\n\r\n const bfr = filesToEmit[pathModule]!;\r\n\r\n this.emitFile({\r\n type: \"asset\",\r\n\r\n source: bfr,\r\n fileName: pathEmittedFile\r\n });\r\n }\r\n\r\n const fetchWasmPathRel = path.relative(pathParent, FETCH_WASM_PATH).replaceAll(\"\\\\\", \"/\");\r\n const generateNextArgsPathRel = path.relative(pathParent, GENERATE_NEXT_ARGS_PATH).replaceAll(\"\\\\\", \"/\");\r\n\r\n bundle.code =\r\n bundle.code\r\n .replaceAll(FETCH_WASM_ID, fetchWasmPathRel.startsWith(\".\") ? fetchWasmPathRel : \"./\" + fetchWasmPathRel)\r\n .replaceAll(GENERATE_NEXT_ARGS_ID, generateNextArgsPathRel.startsWith(\".\") ? generateNextArgsPathRel : \"./\" + generateNextArgsPathRel);\r\n }\r\n },\r\n\r\n buildStart() {\r\n if (\"data\" in this) {\r\n const data = this.data as any;\r\n\r\n root = (data.outputOptions.preserveModules ? data.outputOptions.preserveModulesRoot : path.join(data.outputOptions.dir, \"../\")).replaceAll(\"\\\\\", \"/\");\r\n rootDist = data.outputOptions.dir.replaceAll(\"\\\\\", \"/\");\r\n\r\n isServing = false;\r\n }\r\n\r\n fetchWasmEmit = !(inlineAssemblies || isServing);\r\n },\r\n\r\n resolveId(id: string) {\r\n if (id === FETCH_WASM_ID) return \"\\0\" + FETCH_WASM_ID;\r\n if (id === GENERATE_NEXT_ARGS_ID) return \"\\0\" + GENERATE_NEXT_ARGS_ID;\r\n\r\n return null;\r\n },\r\n\r\n load(id: string) {\r\n if (!id.startsWith(\"\\0\")) return null;\r\n\r\n if (id.endsWith(FETCH_WASM_ID)) return fetchWasmFunc;\r\n if (id.endsWith(GENERATE_NEXT_ARGS_ID)) return generateNextArgumentsFunc;\r\n\r\n return null;\r\n },\r\n\r\n async closeBundle() {\r\n if (fetchWasmEmit) {\r\n const fetchWasmPath = path.join(rootDist, FETCH_WASM_PATH).replaceAll(\"\\\\\", \"/\");\r\n const fetchWasmParent = path.join(fetchWasmPath, \"../\").replaceAll(\"\\\\\", \"/\");\r\n\r\n const generateNextArgsFilename = path.basename(GENERATE_NEXT_ARGS_PATH);\r\n\r\n await fs.mkdir(fetchWasmParent, { recursive: true });\r\n await fs.writeFile(fetchWasmPath, fetchWasmFunc.replaceAll(GENERATE_NEXT_ARGS_ID, \"./\" + generateNextArgsFilename), \"utf-8\");\r\n }\r\n\r\n const generateNextArgsPath = path.join(rootDist, GENERATE_NEXT_ARGS_PATH).replaceAll(\"\\\\\", \"/\");\r\n const generateNextArgsParent = path.join(generateNextArgsPath, \"../\").replaceAll(\"\\\\\", \"/\");\r\n\r\n await fs.mkdir(generateNextArgsParent, { recursive: true });\r\n await fs.writeFile(generateNextArgsPath, generateNextArgumentsFunc, \"utf-8\");\r\n },\r\n\r\n configResolved(config) {\r\n root = config.root.replaceAll(\"\\\\\", \"/\");\r\n rootDist = path.join(root, config.build.outDir).replaceAll(\"\\\\\", \"/\");\r\n\r\n isServing = config.command === \"serve\";\r\n }\r\n };\r\n};\r\n\r\nexport default wat2WasmPlugin;\r\nexport type { Wat2WasmOptions, WasmParserOptions, WasmGeneratorOptions, FetchTarget };\r\n"],"mappings":"yFAQA,MAAM,EAAO,MAAM,GAAU,CAyW7B,IAAA,GA/TwB,EAA2B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,EAAY,GAGhB,EAAgB,EAAE,GAAoB,IAG1C,UAAU,EAAY,CAIlB,OAHI,IAAO,EAAsB,KAAO,EACpC,IAAO,EAA8B,KAAO,EAEzC,MAGX,KAAK,EAAY,CAMb,OALK,EAAG,WAAW,KAAK,CAEpB,EAAG,SAAS,EAAc,CAAS,EACnC,EAAG,SAAS,EAAsB,CAAS,EAExC,KAL0B,MAQrC,MAAM,aAAc,CAChB,GAAI,EAAe,CACf,IAAM,EAAgB,EAAK,KAAK,EAAU,EAAgB,CAAC,WAAW,KAAM,IAAI,CAC1E,EAAkB,EAAK,KAAK,EAAe,MAAM,CAAC,WAAW,KAAM,IAAI,CAEvE,EAA2B,EAAK,SAAS,EAAwB,CAEvE,MAAM,EAAG,MAAM,EAAiB,CAAE,UAAW,GAAM,CAAC,CACpD,MAAM,EAAG,UAAU,EAAe,EAAc,WAAW,EAAuB,KAAO,EAAyB,CAAE,QAAQ,CAGhI,IAAM,EAAuB,EAAK,KAAK,EAAU,EAAwB,CAAC,WAAW,KAAM,IAAI,CACzF,EAAyB,EAAK,KAAK,EAAsB,MAAM,CAAC,WAAW,KAAM,IAAI,CAE3F,MAAM,EAAG,MAAM,EAAwB,CAAE,UAAW,GAAM,CAAC,CAC3D,MAAM,EAAG,UAAU,EAAsB,EAA2B,QAAQ,EAGhF,eAAe,EAAQ,CACnB,EAAO,EAAO,KAAK,WAAW,KAAM,IAAI,CACxC,EAAW,EAAK,KAAK,EAAM,EAAO,MAAM,OAAO,CAAC,WAAW,KAAM,IAAI,CAErE,EAAY,EAAO,UAAY,SAEtC"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
declare module "*.wat" {
|
|
2
|
+
// @ts-ignore
|
|
3
|
+
type ModuleObject = Record<string, any>;
|
|
4
|
+
|
|
5
|
+
export default function init<T extends ModuleObject = ModuleObject >( ): Promise<T>;
|
|
6
|
+
export default function init<T extends ModuleObject = ModuleObject, I extends ModuleObject = {}>(imports: I, compileOptions?: WebAssembly.WebAssemblyCompileOptions): Promise<T>;
|
|
7
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
declare module "*.wat" {
|
|
2
|
+
// @ts-ignore
|
|
2
3
|
type ModuleObject = Record<string, any>;
|
|
3
4
|
|
|
4
|
-
export default function init<T extends ModuleObject = ModuleObject >(
|
|
5
|
-
export default function init<T extends ModuleObject = ModuleObject, I extends ModuleObject = {}>(imports
|
|
5
|
+
export default function init<T extends ModuleObject = ModuleObject >( ): Promise<T>;
|
|
6
|
+
export default function init<T extends ModuleObject = ModuleObject, I extends ModuleObject = {}>(imports: I): Promise<T>;
|
|
6
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-plugin-wat2wasm",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"description": "A simple Vite plugin that enables `.wat` (WebAssembly Text Format) compilation and allows usage of WebAssembly within your codebase/library",
|
|
5
5
|
|
|
6
6
|
"homepage": "https://github.com/osoclos/vite-plugin-wat2wasm",
|
|
@@ -34,7 +34,9 @@
|
|
|
34
34
|
"files": ["dist"],
|
|
35
35
|
"exports": {
|
|
36
36
|
".": "./dist/index.js",
|
|
37
|
+
|
|
37
38
|
"./types": "./dist/types.d.ts",
|
|
39
|
+
"./types-next": "./dist/types-next.d.ts",
|
|
38
40
|
|
|
39
41
|
"./package.json": "./package.json"
|
|
40
42
|
},
|