Skip to content

fix(cli): harden wasm runtime registry lookup - #3193

Merged
Brooooooklyn merged 3 commits into
napi-rs:mainfrom
trivikr:fetch-res-ok
Apr 8, 2026
Merged

Brooooooklyn merged 3 commits into
napi-rs:mainfrom
trivikr:fetch-res-ok

Conversation

@trivikr

@trivikr trivikr commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This hardens the WASM runtime version lookup used by create-npm-dirs.

Previously, the CLI fetched https://registry.npmjs.org/@napi-rs/wasm-runtime inline and immediately parsed the response body without checking res.ok. That made offline and registry-failure cases noisier and harder to diagnose.

Changes

  • move the WASM runtime lookup into a dedicated helper
  • check response.ok before parsing registry metadata
  • return clearer errors for:
    • network failures / offline environments
    • non-2xx npm registry responses
    • malformed registry metadata missing dist-tags.latest
  • compute the WASM runtime version once when WASM targets are present

Summary by CodeRabbit

  • Improvements
    • Enhanced WebAssembly runtime dependency resolution: validates registry metadata, caches the resolved runtime version once per run, and surfaces clearer errors—leading to more reliable and efficient wasm-targeted builds.
  • Tests
    • Added tests using a local registry simulator to cover metadata resolution, error conditions, registry precedence, and improved test determinism and cleanup.

@coderabbitai

coderabbitai Bot commented Apr 6, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Added getLatestWasmRuntimeVersion() to fetch and validate @napi-rs/wasm-runtime metadata from the npm registry and refactored createNpmDirs to compute that version once when any target is wasm32, replacing per-iteration fetches.

Changes

Cohort / File(s) Summary
Wasm runtime resolution
cli/src/api/create-npm-dirs.ts
Added getLatestWasmRuntimeVersion() and WASM_RUNTIME_PACKAGE_NAME; modified createNpmDirs to precompute and reuse the resolved @napi-rs/wasm-runtime latest version for wasm32 targets instead of fetching per-iteration.
Tests — registry server & wasm resolution
cli/src/api/__tests__/create-npm-dirs.spec.ts
Added test registry server helpers and new test.serial cases that verify: empty dist-tags.latest is rejected; npm_config_registry is used (ignoring publishConfig.registry) when resolving wasm runtime metadata; and the exact request paths are exercised. Wrapped registry-backed tests with try/finally to ensure server shutdown and manage npm_config_registry env state.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I hopped to the registry, nose in the air,

Searched for the runtime with meticulous care,
One fetch, one version, no looping to see —
A tidy small change, and a faster me! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(cli): harden wasm runtime registry lookup' is specific and directly aligned with the main changes: improving error handling and validation in WASM runtime version resolution from the npm registry.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@cli/src/api/create-npm-dirs.ts`:
- Around line 28-35: The code currently hardcodes WASM_RUNTIME_REGISTRY_URL and
always queries the public host; update getLatestWasmRuntimeVersion to derive the
registry base dynamically from the active npm configuration (first check
process.env.NPM_CONFIG_REGISTRY, then fall back to running `npm config get
registry` or equivalent programmatic lookup), construct the package registry URL
for `@napi-rs/wasm-runtime` from that registry base, and only use
'https://registry.npmjs.org/@napi-rs/wasm-runtime' as a last-resort fallback;
keep the existing fetch logic and error handling in getLatestWasmRuntimeVersion
but replace references to the hardcoded WASM_RUNTIME_REGISTRY_URL with the
computed registry-derived URL.
- Around line 60-65: The check for latestVersion is too permissive—inspect
packageMeta['dist-tags']?.latest and ensure it is a non-empty string (e.g.,
typeof latestVersion === 'string' && latestVersion.trim().length > 0); if not,
throw the Error that currently references WASM_RUNTIME_REGISTRY_URL so
downstream code (using latestVersion as a dependency spec) never receives
malformed values. Locate the code around latestVersion and the existing throw
and replace the truthiness check with this explicit string validation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 16a8f2a2-9c98-4c8f-9521-d27bff051db5

📥 Commits

Reviewing files that changed from the base of the PR and between 778bd57 and 61c8f5f.

📒 Files selected for processing (1)
  • cli/src/api/create-npm-dirs.ts

Comment thread cli/src/api/create-npm-dirs.ts Resolved
Comment thread cli/src/api/create-npm-dirs.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
cli/src/api/__tests__/create-npm-dirs.spec.ts (1)

345-381: Potential resource leak if second server startup fails.

If startRegistryServer() succeeds on line 349 but fails on line 350, registryServer won't be closed. Consider nesting the server startups or using a cleanup array.

♻️ Suggested fix using nested try/finally
   const { tmpDir, packageJsonPath } = t.context
   const registryServer = await startRegistryServer()
-  const envRegistryServer = await startRegistryServer()
 
-  process.env.npm_config_registry = `${envRegistryServer.origin}/env`
+  try {
+    const envRegistryServer = await startRegistryServer()
 
-  const packageJson = {
-    name: 'test-wasm-publish-registry',
-    version: '1.0.0',
-    publishConfig: {
-      registry: `${registryServer.origin}/custom`,
-    },
-    napi: {
-      binaryName: 'test-wasm-publish-registry',
-      targets: ['wasm32-wasi-preview1-threads'],
-    },
-  }
+    process.env.npm_config_registry = `${envRegistryServer.origin}/env`
 
-  await writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2))
+    const packageJson = {
+      name: 'test-wasm-publish-registry',
+      version: '1.0.0',
+      publishConfig: {
+        registry: `${registryServer.origin}/custom`,
+      },
+      napi: {
+        binaryName: 'test-wasm-publish-registry',
+        targets: ['wasm32-wasi-preview1-threads'],
+      },
+    }
 
-  try {
-    await createNpmDirs({
-      cwd: tmpDir,
-      packageJsonPath: 'package.json',
-    })
+    await writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2))
 
-    t.deepEqual(registryServer.requests, [])
-    t.deepEqual(envRegistryServer.requests, ['/env/@napi-rs/wasm-runtime'])
+    try {
+      await createNpmDirs({
+        cwd: tmpDir,
+        packageJsonPath: 'package.json',
+      })
+
+      t.deepEqual(registryServer.requests, [])
+      t.deepEqual(envRegistryServer.requests, ['/env/@napi-rs/wasm-runtime'])
+    } finally {
+      await envRegistryServer.close()
+    }
   } finally {
     await registryServer.close()
-    await envRegistryServer.close()
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cli/src/api/__tests__/create-npm-dirs.spec.ts` around lines 345 - 381, The
test starts two servers with startRegistryServer() into registryServer and
envRegistryServer but if the second call throws the first server is never
closed; wrap the second start in a try/finally (or push servers into a cleanup
array) so that if startRegistryServer() for envRegistryServer fails you still
call await registryServer.close()—apply this change around the
startRegistryServer() calls in the test (references: startRegistryServer,
registryServer, envRegistryServer, the test callback) to guarantee both servers
are always closed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@cli/src/api/__tests__/create-npm-dirs.spec.ts`:
- Around line 345-381: The test starts two servers with startRegistryServer()
into registryServer and envRegistryServer but if the second call throws the
first server is never closed; wrap the second start in a try/finally (or push
servers into a cleanup array) so that if startRegistryServer() for
envRegistryServer fails you still call await registryServer.close()—apply this
change around the startRegistryServer() calls in the test (references:
startRegistryServer, registryServer, envRegistryServer, the test callback) to
guarantee both servers are always closed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 523a7216-febe-42fc-a205-d967b401e3df

📥 Commits

Reviewing files that changed from the base of the PR and between 61c8f5f and b1947a2.

📒 Files selected for processing (2)
  • cli/src/api/__tests__/create-npm-dirs.spec.ts
  • cli/src/api/create-npm-dirs.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • cli/src/api/create-npm-dirs.ts

@Brooooooklyn
Brooooooklyn merged commit a8b3f93 into napi-rs:main Apr 8, 2026
72 checks passed
@trivikr
trivikr deleted the fetch-res-ok branch April 8, 2026 12:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants