Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: generate safe imports code using knitwork #24

Merged
merged 2 commits into from Mar 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -48,6 +48,7 @@
"test:types": "tsc --noEmit --skipLibCheck"
},
"dependencies": {
"knitwork": "^1.0.0",
"magic-string": "^0.30.8",
"mlly": "^1.6.1",
"pathe": "^1.1.2",
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

33 changes: 22 additions & 11 deletions src/plugin/runtime.ts
@@ -1,4 +1,10 @@
import { readPackageJSON } from "pkg-types";
import {
genSafeVariableName,
genObjectFromRaw,
genString,
genImport,
} from "knitwork";
import {
UMWASM_HELPERS_ID,
UNWASM_EXTERNAL_PREFIX,
Expand Down Expand Up @@ -186,30 +192,35 @@ export async function getWasmImports(
// Try to resolve from nearest package.json
const pkgJSON = await readPackageJSON(asset.id);

let code = "const _imports = {";

let resolved = true;

const imports: string[] = [];
const importsObject: Record<string, Record<string, string>> = {};

for (const moduleName of importNames) {
const importNames = asset.imports[moduleName];
const pkgImport =
pkgJSON.imports?.[moduleName] || pkgJSON.imports?.[`#${moduleName}`];

const importName = "_imports_" + genSafeVariableName(moduleName);

if (pkgImport) {
code = `import * as _imports_${moduleName} from "${pkgImport}";\n${code}`;
imports.push(genImport(pkgImport, { name: "*", as: importName }));
} else {
resolved = false;
}
code += `\n ${moduleName}: {`;
for (const name of importNames) {
code += pkgImport
? `\n ${name}: _imports_${moduleName}.${name},\n`
: `\n ${name}: () => { throw new Error("\`${moduleName}.${name}\` is not provided!")},\n`;
}
code += " },\n";

importsObject[moduleName] = Object.fromEntries(
importNames.map((name) => [
name,
pkgImport
? `${importName}[${genString(name)}]`
: `() => { throw new Error(${genString(moduleName + "." + importName)} + " is not provided!")}`,
]),
);
}

code += "};\n";
const code = `${imports.join("\n")}\n\nconst _imports = ${genObjectFromRaw(importsObject)}`;

return {
code,
Expand Down