Skip to content

Report the real package version in the user agent (hscn/<version>)#65

Open
JonoPrest wants to merge 1 commit into
mainfrom
set-user-agent
Open

Report the real package version in the user agent (hscn/<version>)#65
JonoPrest wants to merge 1 commit into
mainfrom
set-user-agent

Conversation

@JonoPrest

@JonoPrest JonoPrest commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

The client already tags requests with hscn/<version>, but the version came from CARGO_PKG_VERSION — and napi keeps the Cargo package version pinned at 0.0.0, so every request actually went out as hscn/0.0.0.

This makes build.rs read the version from package.json and inject it as NPM_PKG_VERSION, which the client now uses → hscn/<package-version> (e.g. hscn/1.4.0).

Why the release gets the right version

build.rs reads package.json directly, not via any build-time env var the pipeline may or may not set. The publish workflow (publish_to_npm.yaml) builds each platform with checkoutyarn installyarn build, so the artifact is compiled from a checkout whose package.json holds the release version (kept in sync by napi version). It falls back to CARGO_PKG_VERSION only if package.json can't be read.

Matches the Rust (hscr/) and Python (hscp/, separate PR) clients. Verified with cargo check (the env!("NPM_PKG_VERSION") would fail to compile if build.rs didn't set it; the version parses to 1.4.0).

Summary by CodeRabbit

  • Chores
    • Updated the build process to extract and synchronize the npm package version with Rust at build time
    • Modified API client initialization to use the npm package version
    • Configured package.json as a build dependency tracker to ensure version consistency across platforms

The user agent was hscn/{CARGO_PKG_VERSION}, but napi keeps the Cargo package
version at 0.0.0, so it always sent hscn/0.0.0. build.rs now reads the version
from package.json and injects it as NPM_PKG_VERSION, and the client uses that
(hscn/<package-version>).

build.rs reads package.json directly rather than relying on a build-env var, so
the published artifacts get the correct version: the publish workflow builds each
target with 'yarn build' from a checkout whose package.json holds the release
version. Falls back to CARGO_PKG_VERSION if package.json can't be read.
@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds build-time npm package version injection. A build script reads package.json, extracts the version field, and exports it as a Rust environment variable with fallback to cargo version. The HypersyncClient constructor now uses this injected npm version instead of the cargo version for its default user-agent string.

Changes

NPM Version Build Injection

Layer / File(s) Summary
Build-time npm version injection and client integration
build.rs, src/lib.rs
Build script adds logic to read and parse package.json version, emit the NPM_PKG_VERSION cargo environment variable, and register rerun triggers. HypersyncClient::new constructor updates its default user-agent to use the injected npm version instead of cargo version.

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main change: updating the user agent to report the actual npm package version instead of the pinned Cargo version.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@build.rs`:
- Around line 12-25: The current manual line-based parsing in build.rs that
computes the local variable version is brittle; instead add serde_json = "1.0"
to [build-dependencies] in Cargo.toml and replace the manual
read/line/strip_prefix logic with a robust JSON parse using serde_json::from_str
to extract the "version" field (falling back to
env!("CARGO_PKG_VERSION").to_string() if parsing or key extraction fails).
Locate the code that defines version in build.rs (and the use of
env!("CARGO_PKG_VERSION")) and update it to read package.json, parse it with
serde_json::Value (or a small struct with a version field), and use that value
as the version.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1592ab44-7012-4a2c-8e38-443fa2e13429

📥 Commits

Reviewing files that changed from the base of the PR and between 8cf5b7d and 2b490c5.

📒 Files selected for processing (2)
  • build.rs
  • src/lib.rs

Comment thread build.rs
Comment on lines +12 to +25
let version = std::fs::read_to_string("package.json")
.ok()
.and_then(|pkg| {
pkg.lines().find_map(|line| {
line.trim()
.strip_prefix("\"version\":")
.map(|rest| {
rest.trim()
.trim_matches(|c| c == ',' || c == '"' || c == ' ')
.to_string()
})
})
})
.unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fragile JSON parsing could break on valid formatting variations.

The manual line-by-line string matching requires "version": with no space before the colon. This will fail on valid JSON formatted as "version" : "1.4.0" or if formatting tools reflow the file. When parsing fails, the fallback to CARGO_PKG_VERSION (0.0.0) defeats the purpose of this PR.

🔧 Proposed fix using serde_json for robust parsing

Add serde_json to [build-dependencies] in Cargo.toml:

[build-dependencies]
napi-build = "..."
serde_json = "1.0"

Then replace the manual parsing with:

-    let version = std::fs::read_to_string("package.json")
-        .ok()
-        .and_then(|pkg| {
-            pkg.lines().find_map(|line| {
-                line.trim()
-                    .strip_prefix("\"version\":")
-                    .map(|rest| {
-                        rest.trim()
-                            .trim_matches(|c| c == ',' || c == '"' || c == ' ')
-                            .to_string()
-                    })
-            })
-        })
-        .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());
+    let version = std::fs::read_to_string("package.json")
+        .ok()
+        .and_then(|pkg| {
+            serde_json::from_str::<serde_json::Value>(&pkg)
+                .ok()?
+                .get("version")?
+                .as_str()
+                .map(|s| s.to_string())
+        })
+        .unwrap_or_else(|| env!("CARGO_PKG_VERSION").to_string());

This handles all valid JSON formats and is more maintainable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@build.rs` around lines 12 - 25, The current manual line-based parsing in
build.rs that computes the local variable version is brittle; instead add
serde_json = "1.0" to [build-dependencies] in Cargo.toml and replace the manual
read/line/strip_prefix logic with a robust JSON parse using serde_json::from_str
to extract the "version" field (falling back to
env!("CARGO_PKG_VERSION").to_string() if parsing or key extraction fails).
Locate the code that defines version in build.rs (and the use of
env!("CARGO_PKG_VERSION")) and update it to read package.json, parse it with
serde_json::Value (or a small struct with a version field), and use that value
as the version.

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.

1 participant