From 57463554e9113e62798478d6429b053b5145239c Mon Sep 17 00:00:00 2001 From: LongYinan Date: Wed, 3 Jan 2024 18:53:09 +0800 Subject: [PATCH] fix(cli): wasi fallback package load logic (#1887) --- cli/package.json | 1 + cli/src/api/create-npm-dirs.ts | 20 ++++++++++++++++++++ cli/src/api/templates/js-binding.ts | 7 +++++++ yarn.lock | 1 + 4 files changed, 29 insertions(+) diff --git a/cli/package.json b/cli/package.json index ef3ad2ee..f95a9942 100644 --- a/cli/package.json +++ b/cli/package.json @@ -77,6 +77,7 @@ "inquirer": "^9.2.12", "js-yaml": "^4.1.0", "lodash-es": "^4.17.21", + "semver": "^7.5.4", "toml": "^3.0.0", "typanion": "^3.14.0" }, diff --git a/cli/src/api/create-npm-dirs.ts b/cli/src/api/create-npm-dirs.ts index 9cfa6706..7e33cd7f 100644 --- a/cli/src/api/create-npm-dirs.ts +++ b/cli/src/api/create-npm-dirs.ts @@ -1,5 +1,7 @@ import { join, resolve } from 'node:path' +import { parse } from 'semver' + import { applyDefaultCreateNpmDirsOptions, CreateNpmDirsOptions, @@ -88,6 +90,24 @@ export async function createNpmDirs(userOptions: CreateNpmDirsOptions) { const entry = `${binaryName}.wasi.cjs` scopedPackageJson.files.push(entry, `wasi-worker.mjs`) scopedPackageJson.main = entry + let needRestrictNodeVersion = true + if (scopedPackageJson.engines?.node) { + try { + const { major } = parse(scopedPackageJson.engines.node) ?? { + major: 0, + } + if (major >= 14) { + needRestrictNodeVersion = false + } + } catch { + // ignore + } + } + if (needRestrictNodeVersion) { + scopedPackageJson.engines = { + node: '>=14.0.0', + } + } const emnapiCore = await fetch( `https://registry.npmjs.org/@emnapi/core`, ).then((res) => res.json() as Promise) diff --git a/cli/src/api/templates/js-binding.ts b/cli/src/api/templates/js-binding.ts index 659e5fc8..80e3f06f 100644 --- a/cli/src/api/templates/js-binding.ts +++ b/cli/src/api/templates/js-binding.ts @@ -317,6 +317,13 @@ if (!nativeBinding || process.env.NAPI_RS_FORCE_WASI) { } catch { // ignore } + if (!nativeBinding) { + try { + nativeBinding = require('${pkgName}-wasm32-wasi') + } catch (err) { + console.error(err) + } + } } if (!nativeBinding) { diff --git a/yarn.lock b/yarn.lock index 1d0f69f8..c1bdd87a 100644 --- a/yarn.lock +++ b/yarn.lock @@ -594,6 +594,7 @@ __metadata: js-yaml: "npm:^4.1.0" lodash-es: "npm:^4.17.21" prettier: "npm:^3.1.0" + semver: "npm:^7.5.4" toml: "npm:^3.0.0" ts-node: "npm:^10.9.1" tslib: "npm:^2.6.2"