From a79f39296a7cdfb51e28cb9aa9e5f2261808cf66 Mon Sep 17 00:00:00 2001 From: magic-akari Date: Sat, 20 Jan 2024 21:44:41 +0800 Subject: [PATCH] fix: improve CJS Interoperability (#50) --- package.json | 1 + src/wasm-parser.ts | 63 +++++++++++++++++++++++++++++++++------------- 2 files changed, 46 insertions(+), 18 deletions(-) diff --git a/package.json b/package.json index d44dbbe..6345381 100644 --- a/package.json +++ b/package.json @@ -33,6 +33,7 @@ "format": "prettier --write '**/*.{mjs,cjs,js,mts,cts,ts}'", "pretest": "yarn --cwd e2e && playwright install firefox" }, + "packageManager": "yarn@1.22.21", "devDependencies": { "@babel/core": "^7.23.5", "@babel/preset-env": "^7.23.5", diff --git a/src/wasm-parser.ts b/src/wasm-parser.ts index 947885b..113cedd 100644 --- a/src/wasm-parser.ts +++ b/src/wasm-parser.ts @@ -35,22 +35,49 @@ export async function generateGlueCode( names: { initWasm: string; wasmUrl: string } ): Promise { const { imports, exports } = await parseWasm(wasmFilePath); - return ` -${imports - .map( - ({ from, names }, i) => - `import { ${names.map((name, j) => `${name} as __vite__wasmImport_${i}_${j}`).join(", ")} } from ${JSON.stringify( - from - )};` - ) - .join("\n")} -const __vite__wasmModule = await ${names.initWasm}({ ${imports - .map( - ({ from, names }, i) => - `${JSON.stringify(from)}: { ${names.map((name, j) => `${name}: __vite__wasmImport_${i}_${j}`).join(", ")} }` - ) - .join(", ")} }, ${names.wasmUrl}); -${exports - .map(name => `export ${name === "default" ? "default" : `const ${name} =`} __vite__wasmModule.${name};`) - .join("\n")}`; + + const importStatements = imports.map(({ from }, i) => { + return `import * as __vite__wasmImport_${i} from ${JSON.stringify(from)};`; + }); + + const importObject = imports.map(({ from, names }, i) => { + return { + key: JSON.stringify(from), + value: names.map(name => { + return { + key: JSON.stringify(name), + value: `__vite__wasmImport_${i}[${JSON.stringify(name)}]` + }; + }) + }; + }); + + const initCode = `const __vite__wasmModule = await ${names.initWasm}(${codegenSimpleObject(importObject)}, ${ + names.wasmUrl + });`; + + const exportsStatements = exports.map(name => { + return `export ${name === "default" ? "default" : `const ${name} =`} __vite__wasmModule.${name};`; + }); + + return [...importStatements, initCode, ...exportsStatements].join("\n"); +} + +type SimpleObject = SimpleObjectKeyValue[]; + +interface SimpleObjectKeyValue { + key: string; + value: string | SimpleObject; +} + +function codegenSimpleObject(obj: SimpleObject): string { + return `{ ${codegenSimpleObjectKeyValue(obj)} }`; +} + +function codegenSimpleObjectKeyValue(obj: SimpleObject): string { + return obj + .map(({ key, value }) => { + return `${key}: ${typeof value === "string" ? value : codegenSimpleObject(value)}`; + }) + .join(",\n"); }