Repository navigation
feat(ENG-21327): Add HostedGitInfo for .git Tag.infer. - #24041
markovejnovic wants to merge 5 commits into
Conversation
|
Updated 7:44 PM PT - Oct 27th, 2025
❌ @autofix-ci[bot], your commit e2b697c has 2 failures in
🧪 To try this PR locally: bunx bun-pr 24041That installs a local version of the PR into your bun-24041 --bun |
WalkthroughAdds URL fragment inspection bindings; implements HostedGitInfo and npm-package-arg parsing with JS testing bindings; adds npm package-name validation; refactors dependency inference to use hosted_git_info; extends string/path/URL utilities and buffer-backed path helpers; adds many tests and removes one legacy test. Changes
Possibly related PRs
Suggested reviewers
Pre-merge checks✅ Passed checks (4 passed)
Comment |
npm-package-arg cutover.HostedGitInfo for .git Tag.infer.
163622a to
674796f
Compare
674796f to
1d9351b
Compare
| // Convert JSValue to string slice | ||
| const dependency_str = try arguments[0].toBunString(globalObject); | ||
| defer dependency_str.deref(); | ||
| var as_utf8 = dependency_str.toUTF8(bun.default_allocator); |
There was a problem hiding this comment.
| var as_utf8 = dependency_str.toUTF8(bun.default_allocator); | |
| var as_utf8 = dependency_str.toUTF8WithoutRef(bun.default_allocator); |
| sb.count(project); | ||
| if (committish) |c| sb.count(c); | ||
|
|
||
| sb.allocate(allocator) catch return error.OutOfMemory; |
There was a problem hiding this comment.
| sb.allocate(allocator) catch return error.OutOfMemory; | |
| try sb.allocate(allocator); |
There was a problem hiding this comment.
Actionable comments posted: 25
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/install/dependency.zig (1)
592-627: Add tarball detection to git+http block for parity with plain http handlerThe git+http(s) subprotocol handler (lines 592–627) has a parity gap with the plain http(s) handler (lines 642–678). When a git+http URL points to a tarball (e.g.,
git+https://example.com/package.tar.gz), it returns.git; but plain http with the same URL returns.tarball. Addif (isTarball(url)) return .tarball;before the finalreturn .git;at line 625 to match the http handler's behavior and correctly classify tarball URLs.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between afd125f and 39e9ad358e9d45521a796fb8e4ebf8c2c20f89a9.
⛔ Files ignored due to path filters (1)
test/cli/install/__snapshots__/bun-install-dep.test.ts.snapis excluded by!**/*.snap
📒 Files selected for processing (25)
src/bun.js/bindings/BunString.cpp(1 hunks)src/bun.js/bindings/URL.zig(1 hunks)src/comptime_string_map.zig(1 hunks)src/install/dependency.zig(10 hunks)src/install/hosted_git_info.zig(1 hunks)src/install/npm_package_arg.zig(1 hunks)src/install/validate_npm_package_name.zig(1 hunks)src/js/internal-for-testing.ts(1 hunks)src/paths/Path.zig(1 hunks)src/resolver/resolve_path.zig(1 hunks)src/semver/SemverQuery.zig(1 hunks)src/string/immutable.zig(10 hunks)src/string/immutable/paths.zig(0 hunks)src/url.zig(2 hunks)test/cli/install/bun-install-dep.test.ts(0 hunks)test/cli/install/hosted-git-info/cases.ts(1 hunks)test/cli/install/hosted-git-info/from-url.test.ts(1 hunks)test/cli/install/hosted-git-info/parse-url.test.ts(1 hunks)test/cli/install/npm-package-arg/cases.ts(1 hunks)test/cli/install/npm-package-arg/index.test.ts(1 hunks)test/cli/install/npm-package-arg/invalid-url.test.ts(1 hunks)test/cli/install/npm-package-arg/memory-safety.test.ts(1 hunks)test/cli/install/npm-package-arg/realize-package-specifier.test.ts(1 hunks)test/cli/install/validate-npm-package-name/cases.ts(1 hunks)test/cli/install/validate-npm-package-name/index.ts(1 hunks)
💤 Files with no reviewable changes (2)
- test/cli/install/bun-install-dep.test.ts
- src/string/immutable/paths.zig
🧰 Additional context used
📓 Path-based instructions (12)
test/**
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place all tests under the test/ directory
Files:
test/cli/install/hosted-git-info/parse-url.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/hosted-git-info/from-url.test.tstest/cli/install/hosted-git-info/cases.tstest/cli/install/npm-package-arg/cases.tstest/cli/install/validate-npm-package-name/cases.ts
test/cli/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Files:
test/cli/install/hosted-git-info/parse-url.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/hosted-git-info/from-url.test.tstest/cli/install/hosted-git-info/cases.tstest/cli/install/npm-package-arg/cases.tstest/cli/install/validate-npm-package-name/cases.ts
test/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable
Files:
test/cli/install/hosted-git-info/parse-url.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/hosted-git-info/from-url.test.tstest/cli/install/hosted-git-info/cases.tstest/cli/install/npm-package-arg/cases.tstest/cli/install/validate-npm-package-name/cases.ts
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}: Usebun:testfor files ending with*.test.{ts,js,jsx,tsx,mjs,cjs}
Prefer concurrent tests (test.concurrent/describe.concurrent) over sequential when feasible
Organize tests withdescribeblocks to group related tests
Use utilities likedescribe.each,toMatchSnapshot, and lifecycle hooks (beforeAll,beforeEach,afterEach) and track resources for cleanup
Files:
test/cli/install/hosted-git-info/parse-url.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/hosted-git-info/from-url.test.ts
test/**/*.{ts,tsx,js,jsx,mjs,cjs}
📄 CodeRabbit inference engine (test/CLAUDE.md)
For large/repetitive strings, use
Buffer.alloc(count, fill).toString()instead of"A".repeat(count)
Files:
test/cli/install/hosted-git-info/parse-url.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/hosted-git-info/from-url.test.tstest/cli/install/hosted-git-info/cases.tstest/cli/install/npm-package-arg/cases.tstest/cli/install/validate-npm-package-name/cases.ts
test/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
test/**/*.test.{ts,tsx}: Test files must be created under test/ and end with .test.ts or .test.tsx
In tests that open network ports, always use port: 0; do not hardcode port numbers or roll your own random port
Use normalizeBunSnapshot to normalize snapshot output instead of comparing raw stdout
Do not write tests that merely assert absence of strings like "panic" or "uncaught exception"
Use tempDir from "harness" to create temporary directories; do not use fs.mkdtempSync or tmpdirSync
When spawning processes in tests, assert output before asserting the exit code
Avoid shell commands in tests (e.g., find, grep); prefer Bun's Glob and built-in tools
Prefer snapshot tests over direct string equality assertions on stdout
Files:
test/cli/install/hosted-git-info/parse-url.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/hosted-git-info/from-url.test.ts
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/bun.js/bindings/URL.zigsrc/comptime_string_map.zigsrc/url.zigsrc/paths/Path.zigsrc/install/dependency.zigsrc/install/hosted_git_info.zigsrc/semver/SemverQuery.zigsrc/install/validate_npm_package_name.zigsrc/install/npm_package_arg.zigsrc/string/immutable.zigsrc/resolver/resolve_path.zig
src/bun.js/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/zig-javascriptcore-classes.mdc)
src/bun.js/**/*.zig: In Zig binding structs, expose generated bindings via pub const js = JSC.Codegen.JS and re-export toJS/fromJS/fromJSDirect
Constructors and prototype methods should return bun.JSError!JSC.JSValue to integrate Zig error handling with JS exceptions
Use parameter name globalObject (not ctx) and accept (*JSC.JSGlobalObject, *JSC.CallFrame) in binding methods/constructors
Implement getters as get(this, globalObject) returning JSC.JSValue and matching the .classes.ts interface
Provide deinit() for resource cleanup and finalize() that calls deinit(); use bun.destroy(this) or appropriate destroy pattern
Access JS call data via CallFrame (argument(i), argumentCount(), thisValue()) and throw errors with globalObject.throw(...)
For properties marked cache: true, use the generated Zig accessors (NameSetCached/GetCached) to work with GC-owned values
In finalize() for objects holding JS references, release them using .deref() before destroy
Files:
src/bun.js/bindings/URL.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
When adding debug logs in Zig, create a scoped logger and log via Bun APIs:
const log = bun.Output.scoped(.${SCOPE}, .hidden);thenlog("...", .{})
src/**/*.zig: Use private fields in Zig with the#prefix (e.g.,struct { #foo: u32 };)
Prefer decl literals in Zig (e.g.,const decl: Decl = .{ .binding = 0, .value = 0 };)
Prefer placing@importstatements at the bottom of the Zig file (formatter may reorder automatically)
Prefer@import("bun")rather than@import("root").bunor@import("../bun.zig")In Zig code, be careful with allocators and use defer for cleanup
Files:
src/bun.js/bindings/URL.zigsrc/comptime_string_map.zigsrc/url.zigsrc/paths/Path.zigsrc/install/dependency.zigsrc/install/hosted_git_info.zigsrc/semver/SemverQuery.zigsrc/install/validate_npm_package_name.zigsrc/install/npm_package_arg.zigsrc/string/immutable.zigsrc/resolver/resolve_path.zig
**/*.{cpp,h}
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.{cpp,h}: When exposing a JS class with public Constructor and Prototype, define three C++ types: class Foo : public JSC::DestructibleObject (if it has C++ fields), class FooPrototype : public JSC::JSNonFinalObject, and class FooConstructor : public JSC::InternalFunction
If the class has C++ data members, inherit from JSC::DestructibleObject and provide proper destruction; if it has no C++ fields (only JS properties), avoid a class and use JSC::constructEmptyObject(vm, structure) with putDirectOffset
Prefer placing the subspaceFor implementation in the .cpp file rather than the header when possible
Files:
src/bun.js/bindings/BunString.cpp
**/*.cpp
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.cpp: Include "root.h" at the top of C++ binding files to satisfy lints
Define prototype properties using a const HashTableValue array and declare accessors/functions with JSC_DECLARE_* macros
Prototype classes should subclass JSC::JSNonFinalObject, provide create/createStructure, DECLARE_INFO, finishCreation that reifies static properties, and set mayBePrototype on the Structure
Custom getters should use JSC_DEFINE_CUSTOM_GETTER, jsDynamicCast to validate this, and throwThisTypeError on mismatch
Custom setters should use JSC_DEFINE_CUSTOM_SETTER, validate this via jsDynamicCast, and store via WriteBarrier/set semantics
Prototype functions should use JSC_DEFINE_HOST_FUNCTION, validate this with jsDynamicCast, and return encoded JSValue
Constructors should subclass JSC::InternalFunction, return internalFunctionSpace in subspaceFor, set the prototype property as non-configurable/non-writable, and provide create/createStructure
Provide a setup function that builds the Prototype, Constructor, and Structure, and assigns them to the LazyClassStructure initializer
Use the cached Structure via globalObject->m_.get(globalObject) when constructing instances
Expose constructors to Zig via an extern "C" function that returns the constructor from the LazyClassStructure
Provide an extern "C" Bun____toJS function that creates an instance using the cached Structure and returns an EncodedJSValue
Files:
src/bun.js/bindings/BunString.cpp
src/bun.js/bindings/**/*.{cpp,h,hpp}
📄 CodeRabbit inference engine (CLAUDE.md)
src/bun.js/bindings/**/*.{cpp,h,hpp}: For JavaScript classes with a public constructor, implement three C++ classes: Foo (JSDestructibleObject if it has C++ fields), FooPrototype (JSNonFinalObject), and FooConstructor (InternalFunction)
Define class properties using HashTableValue arrays
Add iso subspaces for classes that have C++ fields
Cache class structures in ZigGlobalObject
Files:
src/bun.js/bindings/BunString.cpp
🧠 Learnings (4)
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/js/third_party/**/*.{js,ts} : Place third-party npm package tests under test/js/third_party/
Applied to files:
test/cli/install/validate-npm-package-name/index.ts
📚 Learning: 2025-10-19T02:44:46.354Z
Learnt from: theshadow27
PR: oven-sh/bun#23798
File: packages/bun-otel/context-propagation.test.ts:1-1
Timestamp: 2025-10-19T02:44:46.354Z
Learning: In the Bun repository, standalone packages under packages/ (e.g., bun-vscode, bun-inspector-protocol, bun-plugin-yaml, bun-plugin-svelte, bun-debug-adapter-protocol, bun-otel) co-locate their tests with package source code using *.test.ts files. This follows standard npm/monorepo patterns. The test/ directory hierarchy (test/js/bun/, test/cli/, test/js/node/) is reserved for testing Bun's core runtime APIs and built-in functionality, not standalone packages.
Applied to files:
test/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/realize-package-specifier.test.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/**/*.{js,ts} : Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Applied to files:
test/cli/install/validate-npm-package-name/index.ts
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
PR: oven-sh/bun#22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.
Applied to files:
src/paths/Path.zig
🧬 Code graph analysis (7)
test/cli/install/hosted-git-info/parse-url.test.ts (1)
src/js/internal-for-testing.ts (1)
hostedGitInfo(210-213)
test/cli/install/npm-package-arg/memory-safety.test.ts (1)
src/js/internal-for-testing.ts (1)
Npa(215-218)
test/cli/install/npm-package-arg/index.test.ts (1)
src/js/internal-for-testing.ts (1)
Npa(215-218)
test/cli/install/validate-npm-package-name/index.ts (1)
src/js/internal-for-testing.ts (1)
ValidateNpmPackageName(220-222)
test/cli/install/npm-package-arg/realize-package-specifier.test.ts (1)
src/js/internal-for-testing.ts (1)
Npa(215-218)
test/cli/install/npm-package-arg/invalid-url.test.ts (1)
src/js/internal-for-testing.ts (1)
Npa(215-218)
test/cli/install/hosted-git-info/from-url.test.ts (2)
test/cli/install/hosted-git-info/cases.ts (2)
validGitUrls(26-2407)invalidGitUrls(2409-2472)src/js/internal-for-testing.ts (1)
hostedGitInfo(210-213)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Format
🔇 Additional comments (8)
src/install/dependency.zig (1)
802-812: inferFromJS: good consolidationConverting once to UTF‑8 and reusing Tag.infer() is correct and reduces duplication. LGTM.
src/js/internal-for-testing.ts (1)
210-222: New testing bindings look correctExports align with Zig TestingAPIs names. LGTM.
src/bun.js/bindings/URL.zig (1)
19-32: URL hash/fragment externs and wrappers look correctConsistent with existing getters (markBinding + thin wrapper). No issues.
test/cli/install/validate-npm-package-name/cases.ts (1)
1-102: Fixtures look comprehensive and well-structuredGood coverage of valid/invalid names and messages.
test/cli/install/npm-package-arg/memory-safety.test.ts (1)
1-94: Solid negative-path coverage for memory-safetyAssertions focus on error paths and key fields. Looks good.
test/cli/install/npm-package-arg/cases.ts (1)
413-429: The review comment is based on an incorrect understanding of Node.jspath.joinbehavior.The Node.js verification shows that
path.join(os.homedir(), '/path/to/foo')correctly produces/home/jailuser/path/to/foo, not/path/to/foo. Using a leading slash in the second argument does not discard the first argument; path.join normalizes both variants identically. The current test fixture at lines 413–429 is correct as written.Likely an incorrect or invalid review comment.
src/install/npm_package_arg.zig (2)
971-1005: Spec classification heuristic matches npm, but risky edge: scoped names without specWhen raw_spec is a bare scoped name like “@scope/pkg”, you fall through to validate(); good. Ensure validate_npm_package_name accepts scoped names; otherwise we may misclassify to file/url. Covered by your validate module; just a heads-up to keep tests for this path.
176-186: Avoid transient allocation leak risk in escapedName -> toJSYou correctly free escapedName. Minor polish: assign to a const and reuse; current code is fine.
|
|
||
| /// Lookup the first-defined string key for a given value. | ||
| /// | ||
| /// Linear search. | ||
| pub fn getKey(value: V) ?[]const KeyType { | ||
| inline for (kvs) |kv| { | ||
| if (kv.value == value) return kv.key; | ||
| } | ||
|
|
||
| return null; | ||
| } |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Add test coverage for the new public API.
The implementation is correct and well-documented. However, this new public method lacks test coverage. Please add tests to verify the reverse lookup behavior, including:
- Finding a key for an existing value
- Returning null for a non-existent value
- Returning the first key when multiple keys map to the same value
Would you like me to generate test cases for this method?
| // Allocator necessary for slow paths. | ||
| var stackFallback = std.heap.stackFallback(1024, bun.default_allocator); | ||
| var allocator = stackFallback.get(); | ||
|
|
||
| switch (dependency[0]) { |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
DRY up hosted-git-info probe to one helper
The same “dupe → fromUrl → map provider → free” pattern repeats across branches. Extract a small helper to reduce duplication and future drift.
Example:
+fn classifyHosted(allocator: std.mem.Allocator, dep: []const u8) ?Version.Tag {
+ const copy = bun.handleOom(allocator.dupe(u8, dep));
+ defer allocator.free(copy);
+ const info = hosted_git_info.HostedGitInfo.fromUrl(allocator, copy) catch null orelse return null;
+ defer info.deinit();
+ return switch (info.host_provider) {
+ .github => .github,
+ .bitbucket, .gitlab, .gist, .sourcehut => .git,
+ };
+}Then replace the repeated blocks with:
- const dep_copy = bun.handleOom(allocator.dupe(u8, dependency));
- defer allocator.free(dep_copy);
- if (hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch null) |info| { ... }
+ if (classifyHosted(allocator, dependency)) |tag| return tag;Also applies to: 570-581, 573-584, 615-624, 666-674, 694-704, 736-742, 769-785
🤖 Prompt for AI Agents
In src/install/dependency.zig around lines 497-501 (and also update similar
blocks at 570-581, 573-584, 615-624, 666-674, 694-704, 736-742, 769-785), the
repeated pattern that duplicates a string, probes hosted-git-info via fromUrl,
maps provider, and frees the duplicate should be extracted into a small helper
function to remove duplication. Add a helper that accepts the allocator and the
dependency string (or slice), performs the duplicate, calls
hosted_git_info.fromUrl, maps the provider result to the desired value, frees
the duplicated string, and returns the mapped result (or an optional/error as
appropriate), then replace each repeated block with a call to this helper,
ensuring the existing stackFallback/allocator usage remains unchanged and error
handling/cleanup is preserved.
| // Generate save_spec (with committish) | ||
| const save_spec = try self.toString(allocator); | ||
| errdefer allocator.free(save_spec); | ||
|
|
||
| // For shortcuts, fetch_spec is null | ||
| if (self.default_representation == .shortcut) { | ||
| return .{ | ||
| .save_spec = save_spec, | ||
| .fetch_spec = null, | ||
| }; | ||
| } | ||
|
|
||
| // Generate fetch_spec (without committish) | ||
| const fetch_spec_with_prefix = switch (self.default_representation) { | ||
| .shortcut => unreachable, // handled above | ||
| .sshurl => try self.host_provider.formatSshUrl(allocator, self.user, self.project, null), | ||
| .ssh => try self.host_provider.formatSsh(allocator, self.user, self.project, null), | ||
| .https => try self.host_provider.formatHttps(allocator, null, self.user, self.project, null), | ||
| .git => blk: { | ||
| const git_formatter = HostProvider.configs.get(self.host_provider).format_git; | ||
| if (git_formatter) |formatter| { | ||
| break :blk try formatter(self.host_provider, allocator, null, self.user, self.project, null); | ||
| } | ||
| @panic("No git formatter for this provider. This is a bug in Bun."); | ||
| }, | ||
| .http => @panic("No http formatter exists. This is a bug in Bun."), | ||
| }; | ||
|
|
||
| // Strip git+ prefix if present | ||
| const has_git_plus = bun.strings.hasPrefixComptime(fetch_spec_with_prefix, "git+"); | ||
| if (has_git_plus) { | ||
| const stripped = fetch_spec_with_prefix[4..]; | ||
| const fetch_spec = try allocator.dupe(u8, stripped); | ||
| allocator.free(fetch_spec_with_prefix); | ||
| return .{ | ||
| .save_spec = save_spec, | ||
| .fetch_spec = fetch_spec, | ||
| }; | ||
| } | ||
|
|
||
| return .{ | ||
| .save_spec = save_spec, | ||
| .fetch_spec = fetch_spec_with_prefix, | ||
| }; | ||
| } |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
toStringBoth: free-on-error safety
You free fetch_spec_with_prefix only on the “git+” branch. If any later step throws (none do now), save_spec would leak. Current code is fine, but consider errdefer for fetch_spec too when allocated.
🤖 Prompt for AI Agents
In src/install/hosted_git_info.zig around lines 234 to 278,
fetch_spec_with_prefix is allocated but only freed in the "git+" branch, risking
leaks if a later error occurs; add an errdefer immediately after allocating
fetch_spec_with_prefix so it will be freed on any error path, then cancel that
errdefer (or free manually) before returning normally; when handling the "git+"
strip branch, ensure you free the original fetch_spec_with_prefix before
returning (or cancel the errdefer and free appropriately) so there are no
double-frees or leaks.
| // shortucts | ||
| // | ||
| // NOTE auth is accepted but ignored | ||
| "bitbucket:foo/bar": { ...defaults.bitbucket, default: "shortcut" }, | ||
| "bitbucket:foo/bar#branch": { ...defaults.bitbucket, default: "shortcut", committish: "branch" }, | ||
| "bitbucket:user@foo/bar": { ...defaults.bitbucket, default: "shortcut", auth: null }, | ||
| "bitbucket:user@foo/bar#branch": { ...defaults.bitbucket, default: "shortcut", auth: null, committish: "branch" }, | ||
| "bitbucket:user:password@foo/bar": { ...defaults.bitbucket, default: "shortcut", auth: null }, | ||
| "bitbucket:user:password@foo/bar#branch": { |
There was a problem hiding this comment.
Typos and explicit typing for invalidGitUrls
- Fix "shortucts" → "shortcuts" and "protocos" → "protocols".
- Add an explicit type for invalidGitUrls to reflect null/undefined entries.
- // shortucts
+ // shortcuts
@@
- // shortcuts (.git)
+ // shortcuts (.git)
@@
- // shortucts
+ // shortcuts
@@
- // invalid protocos
+ // invalid protocols
@@
-export const invalidGitUrls = {
+export const invalidGitUrls: { [K in Provider]: (string | null | undefined)[] } = {Also applies to: 356-365, 2358-2365, 2464-2471, 2409-2472
🤖 Prompt for AI Agents
In test/cli/install/hosted-git-info/cases.ts around lines 28-36 (and similarly
at 356-365, 2358-2365, 2464-2471, 2409-2472), fix the typos in the comments
("shortucts" → "shortcuts" and "protocos" → "protocols") and add an explicit
type annotation for invalidGitUrls to include null and undefined (e.g., make it
an array type that allows string | null | undefined) so the code accurately
reflects entries that can be null/undefined.
| // TODO(markovejnovic): Unskip these tests. | ||
| describe.skip("invalid urls", () => { | ||
| describe.each(Object.entries(invalidGitUrls))("%s", (_, urls: (string | null | undefined)[]) => { | ||
| it.each(urls)("does not permit %s", url => { | ||
| expect(() => { | ||
| hostedGitInfo.fromUrl(url); | ||
| }).toThrow(); | ||
| }); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Track the skipped invalid URL tests.
The invalid URL tests are currently skipped. This reduces test coverage for error handling paths.
Do you want me to open an issue to track enabling these tests, or are they blocked on specific functionality being implemented?
🤖 Prompt for AI Agents
In test/cli/install/hosted-git-info/from-url.test.ts around lines 21-30 the
invalid URL tests are skipped via describe.skip which hides error-path coverage;
remove the .skip to enable the suite, run the tests, and if they fail either (A)
update hostedGitInfo.fromUrl to correctly throw for the listed invalidGitUrls so
tests pass, or (B) if failures are due to intentional/known blockers, create a
short tracking issue that lists the test names, failing URL cases and the
current behavior, reference the PR number, and add an explicit TODO/issue link
comment above the describe to re-skip until the issue is resolved.
| result = npa("e@e/2", "test/a/b"); | ||
| expect(result.type).toBe("git"); // hosted package dependency is git | ||
| expect(result.hosted.type).toBe("github"); // github package dependency |
There was a problem hiding this comment.
Use a consistent absolute base path
Keep the base dir consistent with other cases ("/test/a/b") to avoid platform-dependent resolution differences.
- result = npa("e@e/2", "test/a/b");
+ result = npa("e@e/2", "/test/a/b");📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| result = npa("e@e/2", "test/a/b"); | |
| expect(result.type).toBe("git"); // hosted package dependency is git | |
| expect(result.hosted.type).toBe("github"); // github package dependency | |
| result = npa("e@e/2", "/test/a/b"); | |
| expect(result.type).toBe("git"); // hosted package dependency is git | |
| expect(result.hosted.type).toBe("github"); // github package dependency |
🤖 Prompt for AI Agents
In test/cli/install/npm-package-arg/realize-package-specifier.test.ts around
lines 49 to 51, the test calls npa with a relative base path "test/a/b" which
can resolve differently across platforms; change the base path to the consistent
absolute path "/test/a/b" to match other cases and avoid platform-dependent
resolution differences—update the test invocation and any related expectations
if necessary.
| /** | ||
| * Convert the expected object in validate-npm-package-name to match our output. | ||
| * | ||
| * In some ways, this is debt that needs to be addressed should we choose to expose this API publicly. | ||
| */ | ||
| function remapExpectedObject(expectedObject: any): object { | ||
| const newObj = { ...expectedObject }; | ||
|
|
||
| if (newObj.warnings) { | ||
| newObj.warnings = newObj.warnings.map( | ||
| (warning: string) => | ||
| warning.endsWith("is a core module name") ? "name conflicts a core module name" : | ||
| warning | ||
| ); | ||
| } | ||
|
|
||
| if (newObj.errors) { | ||
| newObj.errors = newObj.errors.map( | ||
| (error: string) => | ||
| error.endsWith("is not a valid package name") ? "name is not allowed" : | ||
| error | ||
| ); | ||
| } | ||
|
|
||
| return newObj; | ||
| } |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider addressing the message format debt.
The comment correctly identifies this remapping as debt. If this API is exposed publicly, the validation error/warning messages should match the standard validate-npm-package-name output exactly to avoid confusion and maintain compatibility.
Do you want me to open an issue to track aligning the internal validation messages with the standard npm package format?
🤖 Prompt for AI Agents
In test/cli/install/validate-npm-package-name/index.ts around lines 5–30, the
remapExpectedObject function is a known "message format debt" that alters
validate-npm-package-name output; create a tracking issue in the repo to align
our internal validation messages with the standard npm messages, then add a
brief TODO comment above remapExpectedObject referencing that issue (e.g.,
"TODO: remove remapping once issue #NNN is resolved") and keep the remapping
logic unchanged for now; ensure the TODO explains that the function is a
compatibility shim for tests and include the issue number so the debt is
tracked.
| } | ||
|
|
||
| // Extract user and project from pathname (from-url.js line 76-86) | ||
| var user_part: ?[]const u8 = null; |
There was a problem hiding this comment.
is it possible to prove user_part will never be null so we can change the type to []const u8? i think we should do this because most of the format functions have requireUser(user) that will panic if user is null
| if (self.#owned_buffer == null) { | ||
| @panic("Cannot move an empty Result. This is a bug in Bun. Please " ++ | ||
| "report this issue on GitHub."); | ||
| } |
There was a problem hiding this comment.
same here. is it possible to write this code in a way that proves owned_buffer will never be null so we can delete the panic?
39e9ad3 to
b578ca8
Compare
There was a problem hiding this comment.
Actionable comments posted: 10
♻️ Duplicate comments (6)
src/install/validate_npm_package_name.zig (3)
93-96: Acknowledge past review: Double-flagging spaces.This code segment was previously flagged for adding both
name_surrounded_with_spacesandname_contains_non_url_safe_characters, which may change error cardinality compared to npm.
105-107: Acknowledge past review: Guard builtin check for empty names.This critical safety issue was previously flagged. The extern function should not be called with a zero-length slice. Adding
name.len > 0 andbefore the builtin check is essential.
212-228: Acknowledge past review: Stabilize JS result shape.This was previously flagged as a nitpick to always include
errorsandwarningsarrays (even if empty) for a more predictable JS API shape. The conditional inclusion can complicate JavaScript consumers that expect consistent object structure.src/url.zig (1)
889-899: Avoid extra allocation; pre-reserve capacity before decoding.Decode directly from ZigString to the ArrayList writer and pre‑reserve capacity to reduce churn. Mirrors prior feedback.
- const pathname_str = url.pathname(); - defer pathname_str.deref(); - const pathname = pathname_str.toUTF8(allocator); - defer pathname.deinit(); - - var path_list = std.ArrayList(u8).init(allocator); + const pathname_str = url.pathname(); + defer pathname_str.deref(); + var path_list = std.ArrayList(u8).init(allocator); defer path_list.deinit(); - _ = decode( - @TypeOf(path_list.writer()), - path_list.writer(), - pathname.slice(), - ) catch return error.InvalidPath; + try path_list.ensureTotalCapacity(pathname_str.length()); + const writer = path_list.writer(); + _ = decode(@TypeOf(writer), writer, pathname_str.byteSlice()) catch |err| switch (err) { + error.DecodingError => return error.InvalidPath, + error.OutOfMemory => return error.OutOfMemory, + else => return err, + };src/install/hosted_git_info.zig (2)
269-324: toStringBoth: leak on error; add errdefer for fetch_spec_with_prefixIf
allocator.dupefails,fetch_spec_with_prefixleaks. Adderrdeferafter allocation. This was previously flagged.- const fetch_spec_with_prefix = switch (self.default_representation) { + const fetch_spec_with_prefix = switch (self.default_representation) { .shortcut => { return .{ .save_spec = save_spec, .fetch_spec = null, }; }, .sshurl => try self.host_provider.formatSshUrl( allocator, self.user, self.project, null, ), .ssh => try self.host_provider.formatSsh(allocator, self.user, self.project, null), .https => try self.host_provider.formatHttps( allocator, null, self.user, self.project, null, ), .git => blk: { const git_formatter = HostProvider.configs.get(self.host_provider).format_git; if (git_formatter) |formatter| { break :blk try formatter(self.host_provider, allocator, null, self.user, self.project, null); } @panic("No git formatter for this provider. This is a bug in Bun."); }, .http => @panic("No http formatter exists. This is a bug in Bun."), }; + errdefer allocator.free(fetch_spec_with_prefix);
326-334: fromUrl doc: ownership semantics are wrongComment says result is “valid only for as long as git_url is valid,” but both paths allocate and own memory. Update docs.
- /// Given a URL-like (including shortcuts) string, parses it into a HostedGitInfo structure. - /// The HostedGitInfo is valid only for as long as `git_url` is valid. + /// Given a URL-like (including shortcuts) string, parses it into a HostedGitInfo structure. + /// Ownership: the returned HostedGitInfo owns its internal buffers; caller must call `deinit`.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between 39e9ad358e9d45521a796fb8e4ebf8c2c20f89a9 and b578ca8.
📒 Files selected for processing (3)
src/install/hosted_git_info.zig(1 hunks)src/install/validate_npm_package_name.zig(1 hunks)src/url.zig(2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/install/validate_npm_package_name.zigsrc/url.zigsrc/install/hosted_git_info.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
When adding debug logs in Zig, create a scoped logger and log via Bun APIs:
const log = bun.Output.scoped(.${SCOPE}, .hidden);thenlog("...", .{})
src/**/*.zig: Use private fields in Zig with the#prefix (e.g.,struct { #foo: u32 };)
Prefer decl literals in Zig (e.g.,const decl: Decl = .{ .binding = 0, .value = 0 };)
Prefer placing@importstatements at the bottom of the Zig file (formatter may reorder automatically)
Prefer@import("bun")rather than@import("root").bunor@import("../bun.zig")In Zig code, be careful with allocators and use defer for cleanup
Files:
src/install/validate_npm_package_name.zigsrc/url.zigsrc/install/hosted_git_info.zig
🧠 Learnings (1)
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Applies to src/{**/js_*.zig,bun.js/api/**/*.zig} : Use bun.JSError!JSValue for proper error propagation in JS-exposed Zig functions
Applied to files:
src/install/validate_npm_package_name.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Format
🔇 Additional comments (8)
src/install/validate_npm_package_name.zig (7)
1-11: LGTM: Clear documentation and constants.The file header appropriately documents the module's purpose and deviations from the npm implementation. The
max_package_name_lengthconstant matches npm's specification.
13-53: LGTM: Well-structured error and warning enums.The enum definitions are clean with appropriate message methods. The use of
comptimePrintfor thename_too_longwarning correctly interpolates the constant at compile time.
55-71: LGTM: Solid ValidationResult design.The struct correctly uses
std.EnumSetfor efficient error/warning tracking. The distinction betweenvalidForNewPackages()(strict) andvalidForOldPackages()(lenient) aligns with npm's validation semantics.
79-103: LGTM: Initial validation checks are correct.The logic for checking empty names, leading dots/underscores, and exclusion list matches is sound. The case-insensitive exclusion check appropriately uses
eqlCaseInsensitiveASCII.
109-124: LGTM: Length, uppercase, and special character checks.The validation logic correctly handles:
- Length warnings against the 214-character limit
- Uppercase detection using
containsUppercaseAscii- Special character checks on the last segment (after '/') to handle scoped packages properly
177-192: LGTM: Proper resource management in jsValidate.The function correctly:
- Validates argument count
- Converts the JS string to UTF-8
- Uses
deferfor proper cleanup ofname_strandname_utf8This follows the Zig coding guideline about being careful with allocators.
234-237: LGTM: Imports follow coding guidelines.The imports are correctly placed at the bottom of the file and use
@import("bun")as specified in the coding guidelines.src/url.zig (1)
1-5: Docs clarity: LGTMAccurate warning and guidance to prefer bun.jsc.URL.
| _memory_buffer: []const u8, | ||
| _allocator: std.mem.Allocator, | ||
|
|
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Private fields style
Internal buffers/allocators are marked with _ prefixes. The house style prefers private fields with # prefix. Consider renaming (e.g., #memory_buffer, #allocator, #owned_buffer) in HostedGitInfo and extract.Result.
As per coding guidelines
Also applies to: 1148-1153
🤖 Prompt for AI Agents
In src/install/hosted_git_info.zig around lines 82-84 (and also lines
1148-1153), private struct fields use the `_` prefix; change these to the
project-preferred `#` prefix (e.g., rename `_memory_buffer` -> `#memory_buffer`,
`_allocator` -> `#allocator`, and where applicable `_owned_buffer` ->
`#owned_buffer`) and update every declaration and all references/usages
(constructor, field accesses, pattern matches, tests) accordingly so compilation
and visibility semantics remain the same.
| /// Initialize a HostedGitInfo from an extracted structure. | ||
| /// Takes ownership of the extracted structure. | ||
| fn moveFromextracted( | ||
| extracted: *HostProvider.Config.formatters.extract.Result, | ||
| host_provider: HostProvider, | ||
| default_representation: Representation, | ||
| ) Self { | ||
| const moved = extracted.move(); | ||
| return .{ | ||
| .committish = extracted.committish, | ||
| .project = extracted.project, | ||
| .user = extracted.user, | ||
| .host_provider = host_provider, | ||
| .default_representation = default_representation, | ||
| ._memory_buffer = moved.buffer, | ||
| ._allocator = moved.allocator, | ||
| }; | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Rename for clarity/consistency: moveFromextracted → moveFromExtracted
Improve API polish and align casing. Update call site.
- fn moveFromextracted(
+ fn moveFromExtracted(
extracted: *HostProvider.Config.formatters.extract.Result,
host_provider: HostProvider,
default_representation: Representation,
) Self {
@@
- return HostedGitInfo.moveFromextracted(
+ return HostedGitInfo.moveFromExtracted(
&extracted,
host_provider,
parsed.proto.defaultRepresentation(),
);Also applies to: 363-367
🤖 Prompt for AI Agents
In src/install/hosted_git_info.zig around lines 146 to 163 (and also update the
similar definition at lines 363 to 367), rename the function moveFromextracted
to moveFromExtracted to match casing and style; update its declaration and any
call sites to use moveFromExtracted, and ensure imports/uses and
documentation/comments reflect the new name so compilation and references remain
consistent.
| debug("fromUrl: parseUrl failed: {any}\n", .{err}); | ||
| return null; | ||
| }; |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Make scoped logger hidden by default; follow Bun logging guidance
Use .hidden and a generic name (log) to avoid noisy output in normal runs.
As per coding guidelines
- debug("fromUrl: parseUrl failed: {any}\n", .{err});
+ log("fromUrl: parseUrl failed: {any}\n", .{err});
@@
-const debug = bun.Output.scoped(.hosted_git_info, .visible);
+const log = bun.Output.scoped(.hosted_git_info, .hidden);Also applies to: 1801-1801
🤖 Prompt for AI Agents
In src/install/hosted_git_info.zig around lines 349-351 (and also apply the same
change at line 1801), the scoped logger is currently visible by default and is
noisy; change the scoped logger to be hidden and use a generic name like "log"
by creating it with the `.hidden` scope (e.g., use a hidden-scoped logger named
"log" instead of a visible/scoped one) so it doesn't produce output in normal
runs while preserving the ability to enable it when needed.
| /// Note that this may or may not allocate but it manages its own memory. | ||
| fn parseUrl(allocator: std.mem.Allocator, npa_str: []u8) error{InvalidGitUrl}!struct { | ||
| url: *jsc.URL, | ||
| proto: UrlProtocol, | ||
| } { | ||
| // Certain users can provide values like user:password@github.com:foo/bar and we want to | ||
| // "correct" the protocol to be git+ssh://user:password@github.com:foo/bar | ||
| const proto_pair = normalizeProtocol(npa_str); | ||
|
|
||
| // TODO(markovejnovic): We might be able to avoid this allocation if we rework how jsc.URL | ||
| // accepts strings. | ||
| const maybe_url = proto_pair.toUrl(allocator); | ||
| if (maybe_url) |url| return .{ .url = url, .proto = proto_pair.protocol }; | ||
|
|
||
| // Now that may fail, if the URL is not nicely formatted. In that case, we try to correct the | ||
| // URL and parse it. | ||
| const corrected = correctUrlMut(proto_pair); | ||
| const corrected_url = corrected.toUrl(allocator); | ||
| if (corrected_url) |url| return .{ .url = url, .proto = corrected.protocol }; | ||
|
|
||
| // Otherwise, we complain. | ||
| return error.InvalidGitUrl; | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
Error set naming consistency (InvalidGitUrl vs InvalidURL)
parseUrl returns error.InvalidGitUrl while other APIs use InvalidURL. Consider unifying to one error name for clarity (and update call sites).
Also applies to: 331-351
🏁 Script executed:
#!/bin/bash
# Find mixed error names across the repo to gauge blast radius.
rg -nP --type=zig -C1 '\bInvalidGitUrl\b|\bInvalidURL\b'Length of output: 8576
Unify error name from InvalidGitUrl to InvalidURL
parseUrl uses error{InvalidGitUrl} (lines 422, 442) while the codebase standardly uses InvalidURL. This includes parseUrlMut at line 331 and functions throughout hosted_git_info.zig and related files. Change parseUrl to use InvalidURL for consistency:
- Line 422: Update function signature from
error{InvalidGitUrl}toerror{InvalidURL} - Line 442: Update return statement from
error.InvalidGitUrltoerror.InvalidURL - Line 419: Update comment reference from
InvalidGitUrltoInvalidURL
🤖 Prompt for AI Agents
In src/install/hosted_git_info.zig around lines 421 to 443, the function
parseUrl declares error{InvalidGitUrl} and returns error.InvalidGitUrl while the
codebase standard is InvalidURL; update the function signature to
error{InvalidURL}, change the return at the end to error.InvalidURL, and update
the nearby comment on line ~419 to reference InvalidURL instead of InvalidGitUrl
so names are consistent with parseUrlMut and other functions.
| /// Look up a protocol from a string that includes the trailing colon (e.g., "https:"). | ||
| /// This method strips the colon before looking up in the strings map. | ||
| pub fn fromStringWithColon(protocol_with_colon: []const u8) ?Self { | ||
| return if (protocol_with_colon.len == 0) | ||
| return null | ||
| else | ||
| strings.get(bun.strings.trimSuffixComptime(protocol_with_colon, ":")); | ||
| } | ||
|
|
There was a problem hiding this comment.
Syntax error in fromStringWithColon: nested return inside return if
This won’t compile in Zig. Replace with straightforward conditionals.
- pub fn fromStringWithColon(protocol_with_colon: []const u8) ?Self {
- return if (protocol_with_colon.len == 0)
- return null
- else
- strings.get(bun.strings.trimSuffixComptime(protocol_with_colon, ":"));
- }
+ pub fn fromStringWithColon(protocol_with_colon: []const u8) ?Self {
+ if (protocol_with_colon.len == 0) return null;
+ return strings.get(bun.strings.trimSuffixComptime(protocol_with_colon, ":"));
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /// Look up a protocol from a string that includes the trailing colon (e.g., "https:"). | |
| /// This method strips the colon before looking up in the strings map. | |
| pub fn fromStringWithColon(protocol_with_colon: []const u8) ?Self { | |
| return if (protocol_with_colon.len == 0) | |
| return null | |
| else | |
| strings.get(bun.strings.trimSuffixComptime(protocol_with_colon, ":")); | |
| } | |
| /// Look up a protocol from a string that includes the trailing colon (e.g., "https:"). | |
| /// This method strips the colon before looking up in the strings map. | |
| pub fn fromStringWithColon(protocol_with_colon: []const u8) ?Self { | |
| if (protocol_with_colon.len == 0) return null; | |
| return strings.get(bun.strings.trimSuffixComptime(protocol_with_colon, ":")); | |
| } |
🤖 Prompt for AI Agents
In src/install/hosted_git_info.zig around lines 486 to 494, the function
fromStringWithColon uses a nested `return` inside `return if` which is a Zig
syntax error; change it to a simple conditional: if protocol_with_colon.len == 0
then return null; otherwise compute the trimmed key (e.g.,
bun.strings.trimSuffixComptime(protocol_with_colon, ":")) into a local variable
and then return strings.get(key). Ensure there is no nested `return` and the
function returns either null or the result of strings.get.
| // Implements doesNotEndWithSlash | ||
| const does_not_end_with_slash = | ||
| if (pound_idx) |pi| | ||
| npa_str[pi - 1] != '/' | ||
| else | ||
| npa_str.len >= 1 and npa_str[npa_str.len - 1] != '/'; | ||
|
|
There was a problem hiding this comment.
OOB risk when # is at index 0 in isGitHubShorthand
npa_str[pi - 1] underflows if pi == 0. Guard before indexing.
- const does_not_end_with_slash =
- if (pound_idx) |pi|
- npa_str[pi - 1] != '/'
- else
- npa_str.len >= 1 and npa_str[npa_str.len - 1] != '/';
+ const does_not_end_with_slash =
+ if (pound_idx) |pi|
+ if (pi == 0) false else npa_str[pi - 1] != '/'
+ else
+ npa_str[npa_str.len - 1] != '/';Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/install/hosted_git_info.zig around lines 628 to 634, the code indexes
npa_str[pi - 1] without guarding pi == 0 which underflows when '#' is at index
0; change the pound-branch to first check if pi == 0 and return true in that
case, otherwise evaluate npa_str[pi - 1] != '/'; keep the else branch unchanged.
| if (ScopedPackage.init(name)) |scoped| { | ||
| if (scoped.pkg.len > 0 and scoped.pkg[0] == '.') { | ||
| result.errors.insert(Error.name_starts_with_dot); | ||
| } | ||
|
|
||
| if (bun.strings.indexOfNeedsURLEncode(scoped.user) != null or | ||
| bun.strings.indexOfNeedsURLEncode(scoped.pkg) != null or | ||
| bun.strings.indexOfChar(scoped.user, ' ') != null or | ||
| bun.strings.indexOfChar(scoped.pkg, ' ') != null or | ||
| bun.strings.indexOfChar(scoped.user, ':') != null or | ||
| bun.strings.indexOfChar(scoped.pkg, ':') != null) | ||
| { | ||
| result.errors.insert(Error.name_contains_non_url_safe_characters); | ||
| } | ||
| } else { | ||
| if (bun.strings.indexOfChar(name, '/') != null) { | ||
| result.errors.insert(Error.name_contains_non_url_safe_characters); | ||
| } | ||
|
|
||
| if (bun.strings.indexOfNeedsURLEncode(name) != null or | ||
| bun.strings.indexOfChar(name, ' ') != null or | ||
| bun.strings.indexOfChar(name, ':') != null) | ||
| { | ||
| result.errors.insert(Error.name_contains_non_url_safe_characters); | ||
| } | ||
| } | ||
|
|
||
| return result; | ||
| } | ||
|
|
||
| const ScopedPackage = struct { | ||
| user: []const u8, | ||
| pkg: []const u8, | ||
|
|
||
| fn init(name: []const u8) ?ScopedPackage { | ||
| if (name.len < 4 or name[0] != '@') return null; | ||
|
|
||
| const slash_idx = bun.strings.indexOfChar(name, '/') orelse return null; | ||
| if (slash_idx == 1 or slash_idx >= name.len - 1) return null; | ||
|
|
||
| // Ensure there's only one slash | ||
| if (bun.strings.indexOfCharPos(name, '/', slash_idx + 1) != null) return null; | ||
|
|
||
| return .{ | ||
| .user = name[1..slash_idx], | ||
| .pkg = name[slash_idx + 1 ..], | ||
| }; | ||
| } | ||
| }; |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
LGTM: URL safety validation is correct.
The scoped/unscoped package distinction is properly handled:
- Scoped packages: validates both user and package parts separately
- Unscoped packages: rejects any '/' characters
- Both check for URL encoding needs, spaces, and colons
The ScopedPackage.init() helper correctly validates the @scope/package format with appropriate boundary checks.
Optional: Consider extracting URL safety checks to reduce duplication.
The URL safety validation pattern (checking indexOfNeedsURLEncode, spaces, and colons) appears in both branches. If this logic becomes more complex, consider extracting it to a helper function:
fn hasNonURLSafeChars(s: []const u8) bool {
return bun.strings.indexOfNeedsURLEncode(s) != null or
bun.strings.indexOfChar(s, ' ') != null or
bun.strings.indexOfChar(s, ':') != null;
}Then simplify lines 131-136 and 145-147 to use this helper.
🤖 Prompt for AI Agents
In src/install/validate_npm_package_name.zig around lines 126 to 174, the
URL-safety checks are duplicated for scoped and unscoped branches; extract those
checks into a helper function (e.g., fn hasNonURLSafeChars(s: []const u8) bool)
that returns true if bun.strings.indexOfNeedsURLEncode(s) != null or
bun.strings.indexOfChar(s, ' ') != null or bun.strings.indexOfChar(s, ':') !=
null, then replace the repeated condition blocks in both the scoped (lines
~131-136) and unscoped (lines ~145-147) branches with calls to that helper to
eliminate duplication while preserving behavior.
| go: *jsc.JSGlobalObject, | ||
| result: ValidationResult, | ||
| ) bun.JSError!jsc.JSValue { | ||
| const obj = jsc.JSValue.createEmptyObject(go, 4); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Minor: Capacity hint could be adjusted.
The createEmptyObject(go, 4) hint assumes all fields will be present, but errors and warnings are conditionally added. Consider using 2 as the capacity (for the two boolean fields) or adjusting if you adopt the suggestion to always include the arrays.
🤖 Prompt for AI Agents
In src/install/validate_npm_package_name.zig around line 198, the call
createEmptyObject(go, 4) over-allocates because errors and warnings are added
conditionally; change the capacity hint to 2 to match the two always-present
boolean fields (or alternatively ensure errors/warnings arrays are always
created and keep capacity 4 if you prefer to always include those fields).
Update the createEmptyObject call accordingly and adjust any subsequent logic if
you choose the always-include approach.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (10)
src/install/dependency.zig (2)
573-581: DRY the HostedGitInfo probe into one helper to reduce duplication and drift.The “dupe → fromUrl → map provider → free” pattern repeats across branches. Extract once and call it from each site.
Apply this refactor:
@@ pub const Tag = enum(u8) { @@ pub inline fn isNPM(this: Tag) bool { return @intFromEnum(this) < 3; } + + // Helper: classify hosted providers using HostedGitInfo + inline fn classifyHosted(allocator: std.mem.Allocator, dep: []const u8) ?Tag { + const dep_copy = bun.handleOom(allocator.dupe(u8, dep)); + defer allocator.free(dep_copy); + if (hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch null) |info| { + defer info.deinit(); + return switch (info.host_provider) { + .github => .github, + .bitbucket, .gitlab, .gist, .sourcehut => .git, + }; + } + return null; + } @@ - const copy = bun.handleOom(allocator.dupe(u8, dependency)); - defer allocator.free(copy); - if (hosted_git_info.HostedGitInfo.fromUrl(allocator, copy) catch null) |info| { - defer info.deinit(); - return switch (info.host_provider) { - .github => .github, - .bitbucket, .gitlab, .gist, .sourcehut => .git, - }; - } + if (classifyHosted(allocator, dependency)) |t| return t; @@ - const dep_copy = bun.handleOom(allocator.dupe(u8, dependency)); - defer allocator.free(dep_copy); - if (hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch null) |info| { - defer info.deinit(); - return switch (info.host_provider) { - .github => .github, - .bitbucket, .gitlab, .gist, .sourcehut => .git, - }; - } + if (classifyHosted(allocator, dependency)) |t| return t; @@ - const dep_copy = bun.handleOom(allocator.dupe(u8, dependency)); - defer allocator.free(dep_copy); - if (hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch null) |info| { - defer info.deinit(); - return switch (info.host_provider) { - .github => .github, - .bitbucket, .gitlab, .gist, .sourcehut => .git, - }; - } + if (classifyHosted(allocator, dependency)) |t| return t; return .tarball; @@ - const dep_copy = bun.handleOom(allocator.dupe(u8, dependency)); - defer allocator.free(dep_copy); - if (hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch null) |info| { - defer info.deinit(); - return switch (info.host_provider) { - .github => .github, - .bitbucket, .gitlab, .gist, .sourcehut => .git, - }; - } + if (classifyHosted(allocator, dependency)) |t| return t; return .git; @@ - if (isSCPLikePath(dependency)) { - const dep_copy = bun.handleOom(allocator.dupe(u8, dependency)); - defer allocator.free(dep_copy); - if (hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch null) |info| { - defer info.deinit(); - return switch (info.host_provider) { - .github => .github, - .bitbucket, .gitlab, .gist, .sourcehut => .git, - }; - } - return .git; - } + if (isSCPLikePath(dependency)) { + if (classifyHosted(allocator, dependency)) |t| return t; + return .git; + }Run to confirm no remaining duplicates of the probe pattern:
#!/bin/bash # Find repeated HostedGitInfo probe sites (fromUrl + host_provider mapping) rg -n -C2 -P '(dupe\([^)]*\)|fromUrl\(|host_provider\))' src/install/dependency.zigAlso applies to: 615-624, 666-674, 694-704, 769-785
802-810: Prefer toUTF8WithoutRef to avoid extra ref churn.Use the lighter conversion helper here; lifetime is managed by as_utf8.deinit() anyway.
Apply:
- var as_utf8 = dependency_str.toUTF8(bun.default_allocator); + var as_utf8 = dependency_str.toUTF8WithoutRef(bun.default_allocator); defer as_utf8.deinit();src/install/npm_package_arg.zig (8)
119-129: Deinit order: free arena last to avoid dangling slices in payloadsDeinitialize type payloads first, then free the arena. Current order is brittle if payloads ever hold arena-backed slices.
pub fn deinit(self: *Self) void { - if (self.#arena_buffer) |arena| { - self.#allocator.free(arena); - } - - switch (self.type) { + // Deinit payloads first (they may reference arena-backed slices) + switch (self.type) { .git => |*g| g.deinit(self.#allocator), .alias => |*a| a.deinit(self.#allocator), else => {}, } + if (self.#arena_buffer) |arena| { + self.#allocator.free(arena); + } }
222-226: Stabilize JS object shape: always set “registry”Always include the “registry” key to keep a stable shape across types.
- if (self.isRegistry()) { - object.put(go, "registry", .true); - } + object.put(go, "registry", if (self.isRegistry()) .true else .false);
293-333: SCP-style git+ssh: make saveSpec exclude the hash (npm parity)For git+ssh SCP form, saveSpec should be the href without “#…”. Today it mirrors raw_spec (including hash).
Please verify against npm-package-arg for inputs like:
- git+ssh://user@host:repo.git#branch
- git+ssh://user@host:repo#semver:%5E1.2.3
- var arena_size: usize = rawFieldLength(raw_arg, name, raw_spec); - arena_size += raw_spec.len + scp_result.fragment.len; + var arena_size: usize = rawFieldLength(raw_arg, name, raw_spec); + // raw_spec + fetch_spec (fragment) + "git+ssh://" for save_spec + arena_size += raw_spec.len + scp_result.fragment.len + "git+ssh://".len; if (name) |n| arena_size += n.len; @@ - const raw_spec_slice = arena.copyString(raw_spec); - const fetch_spec_slice = arena.copyString(scp_result.fragment); + const raw_spec_slice = arena.copyString(raw_spec); + const fetch_spec_slice = arena.copyString(scp_result.fragment); + const save_spec_temp = try std.fmt.allocPrint(allocator, "git+ssh://{s}", .{ + scp_result.fragment, + }); + defer allocator.free(save_spec_temp); @@ - .#fetch_spec_slice = fetch_spec_slice, - .save_spec = raw_spec_slice, + .#fetch_spec_slice = fetch_spec_slice, + .save_spec = arena.copyString(save_spec_temp),
408-415: git+file Windows drive-letter heuristic: avoid misclassifying single-letter hostsGate the drive-letter case on a following colon to avoid treating “a.example” as a drive.
- if (parts.host_lower.len == 1 and - std.ascii.isAlphabetic(parts.host_lower[0])) + if (parts.host_lower.len == 1 and + std.ascii.isAlphabetic(parts.host_lower[0]) and + (parts.pathname.len > 0 and parts.pathname[0] == ':')) {
662-664: Propagate OOM from cleanPathToFileUrl instead of mapping to InvalidPathcleanPathToFileUrl only fails on OOM; mapping to InvalidPath hides the real error. Use try to propagate OOM.
- var raw_spec_cleaned = PathToFileUrlUtils.cleanPathToFileUrl(temp, raw_spec) catch { - return error.InvalidPath; - }; + var raw_spec_cleaned = try PathToFileUrlUtils.cleanPathToFileUrl(temp, raw_spec);
838-849: Avoid magic substring; use decoded spec_path for absolute checkUse spec_path instead of substring(raw_spec, 5, …). Clearer and avoids magic offsets.
- } else if (!std.fs.path.isAbsolute(bun.strings.substring(raw_spec, 5, null))) { + } else if (!std.fs.path.isAbsolute(spec_path)) {
943-951: Normalize “path:” to a single leading slash to avoid “//subdir”Trim leading slashes from value before constructing subdir.
- res.subdir = try std.fmt.allocPrint(allocator, "/{s}", .{value}); + const trimmed = bun.strings.trimChar(value, '/'); + res.subdir = try std.fmt.allocPrint(allocator, "/{s}", .{trimmed});
1604-1697: Path helpers locationThese utilities look generally useful; consider moving to src/paths.zig per prior feedback.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between b578ca8 and b73a3db5a23e119082b3d3f746e1ba6caf8ca772.
📒 Files selected for processing (2)
src/install/dependency.zig(10 hunks)src/install/npm_package_arg.zig(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/install/dependency.zigsrc/install/npm_package_arg.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
When adding debug logs in Zig, create a scoped logger and log via Bun APIs:
const log = bun.Output.scoped(.${SCOPE}, .hidden);thenlog("...", .{})
src/**/*.zig: Use private fields in Zig with the#prefix (e.g.,struct { #foo: u32 };)
Prefer decl literals in Zig (e.g.,const decl: Decl = .{ .binding = 0, .value = 0 };)
Prefer placing@importstatements at the bottom of the Zig file (formatter may reorder automatically)
Prefer@import("bun")rather than@import("root").bunor@import("../bun.zig")In Zig code, be careful with allocators and use defer for cleanup
Files:
src/install/dependency.zigsrc/install/npm_package_arg.zig
🧠 Learnings (4)
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Applies to src/**/js_*.zig : Always implement proper cleanup in deinit() and finalize() for JS-exposed types
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-10-20T04:22:55.575Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-20T04:22:55.575Z
Learning: Applies to src/**/*.zig : In Zig code, be careful with allocators and use defer for cleanup
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Implement the core feature in Zig under its own directory within src/<feature>/
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-10-14T23:34:06.388Z
Learnt from: CR
PR: oven-sh/bun#0
File: src/CLAUDE.md:0-0
Timestamp: 2025-10-14T23:34:06.388Z
Learning: Applies to src/**/*.zig : Prefer `import("bun")` rather than `import("root").bun` or `import("../bun.zig")`
Applied to files:
src/install/npm_package_arg.zig
🔇 Additional comments (2)
src/install/dependency.zig (2)
497-500: Good allocator setup for slow paths.stackFallback + explicit frees and info.deinit() make the HostedGitInfo probes safe without leaking.
570-571: LGTM on the targeted GitHub guards and assert.Early isGitHubShorthand checks, tarball guard before shorthand, the added assert, and the new import are all correct and low‑risk.
Also applies to: 612-612, 632-632, 660-664, 735-736, 1100-1100, 1481-1481
|
|
||
| const rawSpecArg = callframe.argument(0); | ||
| const maybeWhereArg = callframe.argument(1); | ||
|
|
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
JS error messages: tighten phrasing
Minor: align messages with method names (consistent with Bun’s style). No behavior change.
- return go.throw("Npa.npa takes at least 1 argument", .{});
+ return go.throw("Npa.npa requires at least 1 argument", .{});
@@
- return go.throwError(err, "Unexpected error in Npa.npa");
+ return go.throwError(err, "Npa.npa failed");Also applies to: 1531-1537
🤖 Prompt for AI Agents
In src/install/npm_package_arg.zig around lines 1504-1507 (and similarly lines
1531-1537), tighten and rephrase the JS error messages so they consistently
reference the method name and follow Bun's concise style (e.g., use the exact
method identifier and short, direct wording). Update the two error strings to be
shorter, aligned with the method name/casing used elsewhere, and keep semantics
unchanged (only wording). Ensure both occurrences are updated to the same
phrasing.
b73a3db to
f516e14
Compare
There was a problem hiding this comment.
Actionable comments posted: 6
♻️ Duplicate comments (8)
src/install/npm_package_arg.zig (8)
119-129: Deinit order: deinit payloads before freeing the arena.Freeing the arena first risks UAF if payloads ever hold arena-backed slices. Swap the order.
pub fn deinit(self: *Self) void { - if (self._arena_buffer) |arena| { - self._allocator.free(arena); - } - - switch (self.type) { + switch (self.type) { .git => |*g| g.deinit(self._allocator), .alias => |*a| a.deinit(self._allocator), else => {}, } + if (self._arena_buffer) |arena| { + self._allocator.free(arena); + } }As per coding guidelines.
222-226: JS shape: always include “registry” key (true/false).Keep object shape stable for consumers by writing the key for all specs.
- if (self.isRegistry()) { - object.put(go, "registry", .true); - } + object.put(go, "registry", if (self.isRegistry()) .true else .false);
293-333: git+ssh SCP: saveSpec should drop the hash to mirror npm.Current code uses the raw input (with hash) as saveSpec; npm saves the input without the fragment.
const raw_spec_slice = arena.copyString(raw_spec); + const save_spec_slice = arena.copyString( + if (bun.strings.indexOfChar(raw_spec, '#')) |h| raw_spec[0..h] else raw_spec, + ); const fetch_spec_slice = arena.copyString(scp_result.fragment); @@ - ._fetch_spec_slice = fetch_spec_slice, - .save_spec = raw_spec_slice, + ._fetch_spec_slice = fetch_spec_slice, + .save_spec = save_spec_slice,Also applies to: 306-324
393-419: git+file Windows drive-letter heuristic: require a following ‘:’.Avoid misclassifying single-letter hosts like a.example as drive letters.
- if (parts.host_lower.len == 1 and - std.ascii.isAlphabetic(parts.host_lower[0])) + if (parts.host_lower.len == 1 and + std.ascii.isAlphabetic(parts.host_lower[0]) and + (parts.pathname.len > 0 and parts.pathname[0] == ':'))Also applies to: 408-415
811-861: Avoid magic “substring(raw_spec, 5, …)” in absolute-path check; use spec_path.Use the already-decoded pathname for clarity and correctness.
- } else if (!std.fs.path.isAbsolute(bun.strings.substring(raw_spec, 5, null))) { + } else if (!std.fs.path.isAbsolute(spec_path)) {Also applies to: 836-849
956-963: Normalize GitAttrs path to a single leading slash.Prevents “//subdir” for inputs like
path:/foo.- res.subdir = try std.fmt.allocPrint(allocator, "/{s}", .{value}); + const trimmed = bun.strings.trimChar(value, '/'); + res.subdir = try std.fmt.allocPrint(allocator, "/{s}", .{trimmed});
1519-1521: Tighten JS error messages (jsNpa).Align wording with Bun style and method names; no behavior change.
- if (callframe.argumentsCount() < 1) { - return go.throw("Npa.npa takes at least 1 argument", .{}); - } + if (callframe.argumentsCount() < 1) { + return go.throw("Npa.npa requires at least 1 argument", .{}); + } @@ - ) catch |err| { - return go.throwError(err, "Unexpected error in Npa.npa"); - }; + ) catch |err| { + return go.throwError(err, "Npa.npa failed"); + };Also applies to: 1551-1552
1562-1564: Tighten JS error messages (jsResolve).Same style consistency for resolve path.
- if (callframe.argumentsCount() < 1) { - return go.throw("Npa.prototype.resolve takes at least 1 argument", .{}); - } + if (callframe.argumentsCount() < 1) { + return go.throw("Npa.prototype.resolve requires at least 1 argument", .{}); + } @@ - )) catch |err| { - return go.throwError(err, "Unexpected error in Npa.prototype.resolve"); - }; + )) catch |err| { + return go.throwError(err, "Npa.prototype.resolve failed"); + };Also applies to: 1611-1612
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between b73a3db5a23e119082b3d3f746e1ba6caf8ca772 and f516e14.
📒 Files selected for processing (2)
src/bun.js/node/path.zig(1 hunks)src/install/npm_package_arg.zig(1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/bun.js/node/path.zigsrc/install/npm_package_arg.zig
src/bun.js/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/zig-javascriptcore-classes.mdc)
src/bun.js/**/*.zig: In Zig binding structs, expose generated bindings via pub const js = JSC.Codegen.JS and re-export toJS/fromJS/fromJSDirect
Constructors and prototype methods should return bun.JSError!JSC.JSValue to integrate Zig error handling with JS exceptions
Use parameter name globalObject (not ctx) and accept (*JSC.JSGlobalObject, *JSC.CallFrame) in binding methods/constructors
Implement getters as get(this, globalObject) returning JSC.JSValue and matching the .classes.ts interface
Provide deinit() for resource cleanup and finalize() that calls deinit(); use bun.destroy(this) or appropriate destroy pattern
Access JS call data via CallFrame (argument(i), argumentCount(), thisValue()) and throw errors with globalObject.throw(...)
For properties marked cache: true, use the generated Zig accessors (NameSetCached/GetCached) to work with GC-owned values
In finalize() for objects holding JS references, release them using .deref() before destroy
Files:
src/bun.js/node/path.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
When adding debug logs in Zig, create a scoped logger and log via Bun APIs:
const log = bun.Output.scoped(.${SCOPE}, .hidden);thenlog("...", .{})
src/**/*.zig: Use private fields in Zig with the#prefix (e.g.,struct { #foo: u32 };)
Prefer decl literals in Zig (e.g.,const decl: Decl = .{ .binding = 0, .value = 0 };)
Prefer placing@importstatements at the bottom of the Zig file (formatter may reorder automatically)
Prefer@import("bun")rather than@import("root").bunor@import("../bun.zig")In Zig code, be careful with allocators and use defer for cleanup
Files:
src/bun.js/node/path.zigsrc/install/npm_package_arg.zig
🧠 Learnings (5)
📚 Learning: 2025-10-08T13:56:00.875Z
Learnt from: Jarred-Sumner
PR: oven-sh/bun#23373
File: src/bun.js/api/BunObject.zig:2514-2521
Timestamp: 2025-10-08T13:56:00.875Z
Learning: For Bun codebase: prefer using `bun.path` utilities (e.g., `bun.path.joinAbsStringBuf`, `bun.path.join`) over `std.fs.path` functions for path operations.
Applied to files:
src/bun.js/node/path.zig
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Applies to src/**/js_*.zig : Always implement proper cleanup in deinit() and finalize() for JS-exposed types
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-10-20T04:22:55.575Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-20T04:22:55.575Z
Learning: Applies to src/**/*.zig : In Zig code, be careful with allocators and use defer for cleanup
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Implement the core feature in Zig under its own directory within src/<feature>/
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-10-14T23:34:06.388Z
Learnt from: CR
PR: oven-sh/bun#0
File: src/CLAUDE.md:0-0
Timestamp: 2025-10-14T23:34:06.388Z
Learning: Applies to src/**/*.zig : Prefer `import("bun")` rather than `import("root").bun` or `import("../bun.zig")`
Applied to files:
src/install/npm_package_arg.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Format
🔇 Additional comments (1)
src/bun.js/node/path.zig (1)
2991-3005: Consistency: use the imported Environment alias.Elsewhere in this file, Environment is aliased; keep it consistent here.
- const result = if (bun.Environment.isWindows) + const result = if (Environment.isWindows) @@ - const result = if (bun.Environment.isWindows) + const result = if (Environment.isWindows)Also applies to: 3017-3045
⛔ Skipped due to learnings
Learnt from: markovejnovic PR: oven-sh/bun#23710 File: src/install/PackageManager/PackageManagerOptions.zig:187-193 Timestamp: 2025-10-16T17:32:03.074Z Learning: In Bun's codebase (particularly in files like src/install/PackageManager/PackageManagerOptions.zig), mixing bun.EnvVar.*.get() and bun.EnvVar.*.platformGet() for environment variable lookups is intentional and safe. The code is protected by compile-time platform checks (Environment.isWindows, etc.), and compilation will fail if the wrong function is used on the wrong platform. This pattern should not be flagged as a consistency issue.
| /// Utility for getting managing path buffers from the pool. Many functions use two buffers. | ||
| pub const BufferPair = struct { | ||
| buf1: *bun.PathBuffer, | ||
| buf2: *bun.PathBuffer, | ||
|
|
||
| pub fn init() BufferPair { | ||
| return .{ | ||
| .buf1 = bun.path_buffer_pool.get(), | ||
| .buf2 = bun.path_buffer_pool.get(), | ||
| }; | ||
| } | ||
|
|
||
| pub fn deinit(self: *BufferPair) void { | ||
| bun.path_buffer_pool.put(self.buf1); | ||
| bun.path_buffer_pool.put(self.buf2); | ||
| } | ||
| }; |
There was a problem hiding this comment.
Nit: doc grammar and tiny polish for BufferPair.
Fix wording and add a quick usage note to prevent misuse.
-/// Utility for getting managing path buffers from the pool. Many functions use two buffers.
+/// Utility for getting and managing path buffers from the pool. Many functions use two buffers.
+/// Usage: `var bufs = BufferPair.init(); defer bufs.deinit();`🤖 Prompt for AI Agents
In src/bun.js/node/path.zig around lines 2955 to 2971, update the comment for
the BufferPair struct to fix grammar and add a short usage note: reword the
header to something like "Utility for managing paired path buffers from the
pool" (remove extra words), correct "getting managing" to "managing", and add a
one-line note that BufferPair returns two pooled buffers which must both be
returned via deinit to avoid leaks and should not be retained beyond their
intended scope; keep the comment concise and factual.
| /// Utility for getting managing path buffers from the pool. Many functions use three buffers. | ||
| pub const BufferTriplet = struct { | ||
| pair: BufferPair, | ||
| buf3: *bun.PathBuffer, | ||
|
|
||
| pub fn init() BufferTriplet { | ||
| return .{ | ||
| .pair = BufferPair.init(), | ||
| .buf3 = bun.path_buffer_pool.get(), | ||
| }; | ||
| } | ||
|
|
||
| pub fn deinit(self: *BufferTriplet) void { | ||
| self.pair.deinit(); | ||
| bun.path_buffer_pool.put(self.buf3); | ||
| } | ||
| }; | ||
|
|
There was a problem hiding this comment.
Nit: doc grammar for BufferTriplet.
-/// Utility for getting managing path buffers from the pool. Many functions use three buffers.
+/// Utility for getting and managing path buffers from the pool. Many functions use three buffers.
+/// Usage: `var bufs = BufferTriplet.init(); defer bufs.deinit();`📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /// Utility for getting managing path buffers from the pool. Many functions use three buffers. | |
| pub const BufferTriplet = struct { | |
| pair: BufferPair, | |
| buf3: *bun.PathBuffer, | |
| pub fn init() BufferTriplet { | |
| return .{ | |
| .pair = BufferPair.init(), | |
| .buf3 = bun.path_buffer_pool.get(), | |
| }; | |
| } | |
| pub fn deinit(self: *BufferTriplet) void { | |
| self.pair.deinit(); | |
| bun.path_buffer_pool.put(self.buf3); | |
| } | |
| }; | |
| /// Utility for getting and managing path buffers from the pool. Many functions use three buffers. | |
| /// Usage: `var bufs = BufferTriplet.init(); defer bufs.deinit();` | |
| pub const BufferTriplet = struct { | |
| pair: BufferPair, | |
| buf3: *bun.PathBuffer, | |
| pub fn init() BufferTriplet { | |
| return .{ | |
| .pair = BufferPair.init(), | |
| .buf3 = bun.path_buffer_pool.get(), | |
| }; | |
| } | |
| pub fn deinit(self: *BufferTriplet) void { | |
| self.pair.deinit(); | |
| bun.path_buffer_pool.put(self.buf3); | |
| } | |
| }; |
🤖 Prompt for AI Agents
In src/bun.js/node/path.zig around lines 2973 to 2990, the doc comment for
BufferTriplet is grammatically incorrect ("Utility for getting managing path
buffers from the pool."); update the comment to a clear, concise sentence such
as "Utility for managing path buffers from the pool. Many functions use three
buffers." so it reads correctly and explains purpose. Ensure the comment sits
immediately above the BufferTriplet declaration and preserve existing
punctuation and spacing conventions.
| pub fn resolveWithPrefix( | ||
| allocator: std.mem.Allocator, | ||
| comptime prefix: []const u8, | ||
| segments: []const []const u8, | ||
| buffers: *BufferPair, | ||
| ) ![]u8 { | ||
| const resolved = try resolvePath(segments, buffers); | ||
| return std.fmt.allocPrint(allocator, prefix ++ "{s}", .{resolved}); | ||
| } | ||
|
|
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Make prefix runtime-friendly and type the error set.
resolveWithPrefix requires a comptime prefix and has an untyped error set. Allow runtime prefixes and declare precise errors.
-pub fn resolveWithPrefix(
- allocator: std.mem.Allocator,
- comptime prefix: []const u8,
- segments: []const []const u8,
- buffers: *BufferPair,
-) ![]u8 {
- const resolved = try resolvePath(segments, buffers);
- return std.fmt.allocPrint(allocator, prefix ++ "{s}", .{resolved});
-}
+pub fn resolveWithPrefix(
+ allocator: std.mem.Allocator,
+ prefix: []const u8,
+ segments: []const []const u8,
+ buffers: *BufferPair,
+) error{InvalidPath, OutOfMemory}![]u8 {
+ const resolved = try resolvePath(segments, buffers);
+ return std.fmt.allocPrint(allocator, "{s}{s}", .{ prefix, resolved });
+}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| pub fn resolveWithPrefix( | |
| allocator: std.mem.Allocator, | |
| comptime prefix: []const u8, | |
| segments: []const []const u8, | |
| buffers: *BufferPair, | |
| ) ![]u8 { | |
| const resolved = try resolvePath(segments, buffers); | |
| return std.fmt.allocPrint(allocator, prefix ++ "{s}", .{resolved}); | |
| } | |
| pub fn resolveWithPrefix( | |
| allocator: std.mem.Allocator, | |
| prefix: []const u8, | |
| segments: []const []const u8, | |
| buffers: *BufferPair, | |
| ) error{InvalidPath, OutOfMemory}![]u8 { | |
| const resolved = try resolvePath(segments, buffers); | |
| return std.fmt.allocPrint(allocator, "{s}{s}", .{ prefix, resolved }); | |
| } |
🤖 Prompt for AI Agents
In src/bun.js/node/path.zig around lines 3007–3016, change the comptime prefix
and untyped error set: make the prefix a runtime parameter (prefix: []const u8)
instead of comptime, and replace the implicit untyped error return with an
explicit error set that includes the errors from resolvePath and the allocator
(e.g. declare a ResolveWithPrefixError combining resolvePath's error and
std.mem.Allocator.AlsoAllocError or allocator.AllocError), then update the
function signature to return that explicit error set
(ResolveWithPrefixError![]u8) and keep using try to propagate errors from
resolvePath and std.fmt.allocPrint so they map to the declared error set.
| _allocator: std.mem.Allocator, | ||
| /// Single arena buffer containing all owned strings (raw, name, raw_spec, save_spec, | ||
| /// fetch_spec). All string fields are slices into this buffer (or null) | ||
| _arena_buffer: ?[]u8, | ||
| /// The fetch spec slice (may be null, or a slice into arena_buffer or raw_spec) | ||
| _fetch_spec_slice: ?[]const u8, | ||
|
|
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Adopt project’s private-field convention (#-prefixed) instead of underscores.
Consistent with src/**/*.zig guidelines and prior code in this area, prefer #allocator, #arena_buffer, #fetch_spec_slice. Do this as a follow-up mechanical rename across the file to avoid churn now. As per coding guidelines.
🤖 Prompt for AI Agents
In src/install/npm_package_arg.zig around lines 33 to 39, the struct fields use
leading underscores (_allocator, _arena_buffer, _fetch_spec_slice) but the
project convention requires private fields to be prefixed with '#' (e.g.,
#allocator, #arena_buffer, #fetch_spec_slice); perform a mechanical rename of
these fields to use the '#' prefix and update every reference in this file
accordingly (types and semantics unchanged), ensuring nullability and slice
types remain identical and run a build to confirm no further references remain.
| allocator: std.mem.Allocator, | ||
| go: *jsc.JSGlobalObject, | ||
| ) jsc.JSValue { | ||
| var object = jsc.JSValue.createEmptyObject(go, 8); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Minor: preallocate a bit more for toJS object.
You add >8 properties; bumping capacity reduces rehashing.
- var object = jsc.JSValue.createEmptyObject(go, 8);
+ var object = jsc.JSValue.createEmptyObject(go, 12);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| var object = jsc.JSValue.createEmptyObject(go, 8); | |
| var object = jsc.JSValue.createEmptyObject(go, 12); |
🤖 Prompt for AI Agents
In src/install/npm_package_arg.zig around line 155, the JS object is
preallocated with capacity 8 but the code adds more than eight properties
causing rehashing; increase the initial capacity (e.g., to 12 or to the actual
number of properties you add) by changing the createEmptyObject call to use a
larger value, or compute the exact property count and pass that so the object is
allocated with sufficient capacity up front.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (3)
src/install/dependency.zig (2)
573-581: DRY: Extract repeated hosted-git-info probe pattern.This duplication was already flagged in a previous review. The same "dupe → fromUrl → map provider → free" pattern appears 5 times across lines 573-581, 615-624, 666-674, 694-703, and 775-785. Extract this into a helper function as suggested in the prior review to reduce code duplication and future maintenance drift.
Also applies to: 615-624, 666-674, 694-703, 775-785
805-805: Consider usingtoUTF8WithoutReffor read-only string access.Since the UTF-8 string is only read (passed to
Tag.infer) and not modified, consider usingtoUTF8WithoutRefinstead oftoUTF8to avoid unnecessary allocation overhead.Apply this diff:
- var as_utf8 = dependency_str.toUTF8(bun.default_allocator); - defer as_utf8.deinit(); + var as_utf8 = dependency_str.toUTF8WithoutRef(bun.default_allocator); + defer as_utf8.deinit();Based on learnings
src/install/npm_package_arg.zig (1)
897-898: Apply private-field convention to GitAttrs.Like NpaSpec (flagged in existing comment),
GitAttrsuses underscore-prefixed fields_allocatorand_range_bufinstead of the project's#prefix convention. Update to#allocatorand#range_bufand adjust all references accordingly.As per coding guidelines.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
src/install/dependency.zig(10 hunks)src/install/npm_package_arg.zig(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/install/dependency.zigsrc/install/npm_package_arg.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
When adding debug logs in Zig, create a scoped logger and log via Bun APIs:
const log = bun.Output.scoped(.${SCOPE}, .hidden);thenlog("...", .{})
src/**/*.zig: Use private fields in Zig with the#prefix (e.g.,struct { #foo: u32 };)
Prefer decl literals in Zig (e.g.,const decl: Decl = .{ .binding = 0, .value = 0 };)
Prefer placing@importstatements at the bottom of the Zig file (formatter may reorder automatically)
Prefer@import("bun")rather than@import("root").bunor@import("../bun.zig")In Zig code, be careful with allocators and use defer for cleanup
Files:
src/install/dependency.zigsrc/install/npm_package_arg.zig
🧠 Learnings (9)
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Applies to src/**/js_*.zig : Always implement proper cleanup in deinit() and finalize() for JS-exposed types
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-10-20T04:22:55.575Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-10-20T04:22:55.575Z
Learning: Applies to src/**/*.zig : In Zig code, be careful with allocators and use defer for cleanup
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Implement the core feature in Zig under its own directory within src/<feature>/
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-10-14T23:34:06.388Z
Learnt from: CR
PR: oven-sh/bun#0
File: src/CLAUDE.md:0-0
Timestamp: 2025-10-14T23:34:06.388Z
Learning: Applies to src/**/*.zig : Prefer `import("bun")` rather than `import("root").bun` or `import("../bun.zig")`
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-10-14T23:34:06.388Z
Learnt from: CR
PR: oven-sh/bun#0
File: src/CLAUDE.md:0-0
Timestamp: 2025-10-14T23:34:06.388Z
Learning: Applies to src/**/*.zig : Use private fields in Zig with the `#` prefix (e.g., `struct { #foo: u32 };`)
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-02T18:25:27.976Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/allocators/allocation_scope.zig:284-314
Timestamp: 2025-09-02T18:25:27.976Z
Learning: In bun's custom Zig implementation, the `#` prefix for private fields is valid syntax and should not be flagged as invalid. The syntax `#fieldname` creates private fields that cannot be accessed from outside the defining struct, and usage like `self.#fieldname` is correct within the same struct. This applies to fields like `#parent`, `#state`, `#allocator`, `#trace`, etc. throughout the codebase.
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-02T17:14:46.924Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/safety/alloc.zig:93-95
Timestamp: 2025-09-02T17:14:46.924Z
Learning: In bun's Zig codebase, they use a custom extension of Zig that supports private field syntax with the `#` prefix (e.g., `#allocator`, `#trace`). This is not standard Zig syntax but is valid in their custom implementation. Fields prefixed with `#` are private fields that cannot be accessed from outside the defining struct.
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-02T18:27:23.279Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/collections/multi_array_list.zig:24-24
Timestamp: 2025-09-02T18:27:23.279Z
Learning: The `#allocator` syntax in bun's custom Zig implementation is valid and does not require quoting with @"#allocator". Private fields using the `#` prefix work correctly throughout the codebase without special quoting syntax.
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-25T18:14:27.731Z
Learnt from: cirospaciari
PR: oven-sh/bun#22842
File: src/bun.js/webcore/ResumableSink.zig:274-276
Timestamp: 2025-09-25T18:14:27.731Z
Learning: In Zig code, private fields are declared and accessed using the `#` prefix. When a field is declared as `#field_name`, it must be accessed as `this.#field_name`, not `this.field_name`. The `#` prefix is part of the private field access syntax and should not be removed.
Applied to files:
src/install/npm_package_arg.zig
🔇 Additional comments (5)
src/install/dependency.zig (4)
497-500: LGTM: Efficient allocator setup.The use of
stackFallbackwith a 1024-byte buffer is appropriate for the URL/path parsing operations performed in this function. This minimizes heap allocations while providing a fallback for larger strings.
570-571: LGTM: Proper use ofisGitHubShorthand.The replacement of
isGitHubRepoPathwithhosted_git_info.isGitHubShorthandis correct and follows the integration plan. These checks serve as efficient guards before more expensive parsing operations.Also applies to: 612-612, 631-631, 663-663, 735-735, 771-771
1100-1100: LGTM: Assertion correctly validates GitHub shorthand format.The assertion properly validates that the input conforms to GitHub shorthand format after prefix stripping. This helps catch unexpected input in debug builds.
1481-1481: LGTM: Import added correctly.The import of
hosted_git_info.zigis necessary for the integration and follows Zig conventions.src/install/npm_package_arg.zig (1)
1619-1630: LGTM: Imports follow coding guidelines.Imports are correctly placed at the bottom of the file and use
@import("bun")as preferred by the coding guidelines.As per coding guidelines.
| if (bun.strings.hasPrefixComptime(spec_path, "/~/") or | ||
| bun.strings.eqlComptime(spec_path, "/~")) | ||
| { | ||
| if (bun.getenvZ("HOME")) |home_dir| { | ||
| const path_after_tilde = if (spec_path.len > 3) spec_path[3..] else ""; | ||
| const resolved = try PathResolver.resolvePath( | ||
| &.{ home_dir, path_after_tilde }, | ||
| &path_buffers, | ||
| ); | ||
| return PathPair.init(allocator, resolved, spec_path[1..]); | ||
| } else { | ||
| return error.InvalidPath; | ||
| } |
There was a problem hiding this comment.
Validate HOME environment variable is non-empty.
The tilde expansion checks if HOME exists but doesn't validate it's non-empty. An empty HOME would cause incorrect path resolution when concatenating with path_after_tilde.
Apply this diff to add validation:
if (bun.strings.hasPrefixComptime(spec_path, "/~/") or
bun.strings.eqlComptime(spec_path, "/~"))
{
if (bun.getenvZ("HOME")) |home_dir| {
+ if (home_dir.len == 0) {
+ return error.InvalidPath;
+ }
const path_after_tilde = if (spec_path.len > 3) spec_path[3..] else "";
const resolved = try PathResolver.resolvePath(
&.{ home_dir, path_after_tilde },
&path_buffers,
);
return PathPair.init(allocator, resolved, spec_path[1..]);
} else {
return error.InvalidPath;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (bun.strings.hasPrefixComptime(spec_path, "/~/") or | |
| bun.strings.eqlComptime(spec_path, "/~")) | |
| { | |
| if (bun.getenvZ("HOME")) |home_dir| { | |
| const path_after_tilde = if (spec_path.len > 3) spec_path[3..] else ""; | |
| const resolved = try PathResolver.resolvePath( | |
| &.{ home_dir, path_after_tilde }, | |
| &path_buffers, | |
| ); | |
| return PathPair.init(allocator, resolved, spec_path[1..]); | |
| } else { | |
| return error.InvalidPath; | |
| } | |
| if (bun.strings.hasPrefixComptime(spec_path, "/~/") or | |
| bun.strings.eqlComptime(spec_path, "/~")) | |
| { | |
| if (bun.getenvZ("HOME")) |home_dir| { | |
| if (home_dir.len == 0) { | |
| return error.InvalidPath; | |
| } | |
| const path_after_tilde = if (spec_path.len > 3) spec_path[3..] else ""; | |
| const resolved = try PathResolver.resolvePath( | |
| &.{ home_dir, path_after_tilde }, | |
| &path_buffers, | |
| ); | |
| return PathPair.init(allocator, resolved, spec_path[1..]); | |
| } else { | |
| return error.InvalidPath; | |
| } |
🤖 Prompt for AI Agents
In src/install/npm_package_arg.zig around lines 823 to 835, the current branch
checks bun.getenvZ("HOME") only for existence but not that it's non-empty;
update the guard to ensure home_dir is a non-empty string (e.g., check
home_dir.len > 0) before using it in PathResolver, and if empty return
error.InvalidPath so tilde expansion does not proceed with an empty HOME.
a99441c to
8b0615e
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/string/immutable.zig (1)
2084-2097: Critical: Fix unsafe OOM error handling at line 2131.Verification reveals proper narrowing but one problematic call site:
- Line 2107 (
concat()function): ✓ Correct—error properly propagates via return type.- Line 2131 (
concatIfNeeded()function): ✗ Critical issue—catch unreachableconverts OOM into panic, not proper error handling. Should usetryto propagate or implement graceful fallback. The enclosing function's!voidreturn type supports error propagation.
♻️ Duplicate comments (34)
src/comptime_string_map.zig (1)
302-312: Test coverage forgetKeyis still missing.As previously noted, this new public method lacks test coverage. The existing tests (lines 324-425) do not exercise the reverse lookup functionality. Tests should verify:
- Finding a key for an existing value
- Returning null for a non-existent value
- Returning the first key when multiple keys map to the same value (e.g., lines 506-507 where both "0" and "00" map to
.FL)src/resolver/resolve_path.zig (1)
40-47: Deduplicate: call Path.hasPlatformPathSeparators instead of reimplementing.Avoid two copies of identical logic; forward to the canonical helper in src/paths/Path.zig.
Apply within this hunk:
pub fn hasPlatformPathSeparators(input_path: []const u8) bool { - if (bun.Environment.isWindows) { - return bun.strings.containsChar(input_path, '\\'); - } else { - return bun.strings.containsChar(input_path, '/'); - } + return Path.hasPlatformPathSeparators(input_path); }And add the import at the bottom with existing consts (formatter will order it):
const Path = @import("../paths/Path.zig");As per coding guidelines.
src/bun.js/node/path.zig (5)
2955-2971: Doc nit: fix grammar and add quick usage.Make the comment clear and show deinit to prevent leaks.
-/// Utility for getting managing path buffers from the pool. Many functions use two buffers. +/// Utility for getting and managing path buffers from the pool. Many functions use two buffers. +/// Usage: `var bufs = BufferPair.init(); defer bufs.deinit();`
2973-2990: Doc nit: same grammar + usage for BufferTriplet.Mirror the BufferPair polish.
-/// Utility for getting managing path buffers from the pool. Many functions use three buffers. +/// Utility for getting and managing path buffers from the pool. Many functions use three buffers. +/// Usage: `var bufs = BufferTriplet.init(); defer bufs.deinit();`
2991-3005: Tighten error set and document borrowed slice; prefer Environment alias.No allocator use here; only InvalidPath can surface. Also clarify lifetime of returned slice.
-/// JS path.resolve equivalent. +/// JS path.resolve equivalent. +/// Returns a slice borrowed from `buffers`; valid only until `buffers.deinit()`. pub fn resolvePath( segments: []const []const u8, buffers: *BufferPair, -) error{ OutOfMemory, InvalidPath }![]const u8 { - const result = if (bun.Environment.isWindows) +) error{ InvalidPath }![]const u8 { + const result = if (Environment.isWindows) resolveWindowsT(u8, segments, buffers.buf1, buffers.buf2) else resolvePosixT(u8, segments, buffers.buf1, buffers.buf2);
3007-3016: Make prefix runtime and declare explicit errors; avoid comptime concat.Enable dynamic prefixes and precise error set.
-pub fn resolveWithPrefix( - allocator: std.mem.Allocator, - comptime prefix: []const u8, - segments: []const []const u8, - buffers: *BufferPair, -) ![]u8 { +pub fn resolveWithPrefix( + allocator: std.mem.Allocator, + prefix: []const u8, + segments: []const []const u8, + buffers: *BufferPair, +) error{InvalidPath, OutOfMemory}![]u8 { const resolved = try resolvePath(segments, buffers); - return std.fmt.allocPrint(allocator, prefix ++ "{s}", .{resolved}); + return std.fmt.allocPrint(allocator, "{s}{s}", .{ prefix, resolved }); }
3017-3045: Tighten error set and document borrowed slice; prefer Environment alias.Align with resolvePath and clarify ownership to prevent UAF bugs at call sites.
-pub fn computeRelative( +/// Returns a slice borrowed from `buffers`; valid only until `buffers.deinit()`. +pub fn computeRelative( from: []const u8, to: []const u8, buffers: *BufferTriplet, -) ![]const u8 { - const result = if (bun.Environment.isWindows) +) error{ InvalidPath }![]const u8 { + const result = if (Environment.isWindows) relativeWindowsT( u8, from, to, buffers.pair.buf1, buffers.pair.buf2, buffers.buf3, ) else relativePosixT( u8, from, to, buffers.pair.buf1, buffers.pair.buf2, buffers.buf3, );Optional: provide owned helpers to avoid lifetime foot‑guns for public API:
pub fn resolvePathOwned(allocator: std.mem.Allocator, segments: []const []const u8) error{InvalidPath, OutOfMemory}![]u8 { var bufs = BufferPair.init(); defer bufs.deinit(); const s = try resolvePath(segments, &bufs); return allocator.dupe(u8, s); } pub fn computeRelativeOwned(allocator: std.mem.Allocator, from: []const u8, to: []const u8) error{InvalidPath, OutOfMemory}![]u8 { var bufs = BufferTriplet.init(); defer bufs.deinit(); const s = try computeRelative(from, to, &bufs); return allocator.dupe(u8, s); }src/string/immutable.zig (2)
417-422: Make edge-case explicit whenbefore_pos == 0.Optional clarity: early-return null when nothing precedes
before. Functionality unchanged.pub fn lastIndexBeforeChar(in: []const u8, char: u8, before: u8) ?usize { - const before_pos = indexOfChar(in, before) orelse in.len; - return lastIndexOfChar(in[0..before_pos], char); + const before_pos = indexOfChar(in, before) orelse in.len; + if (before_pos == 0) return null; + return lastIndexOfChar(in[0..before_pos], char); }
2203-2243: SlicedBuffer: compile errors and ownership/type issues. Fix#field access, usebuffervariable, and accept[]u8.
inituses undefinedbuf; should usebuffer.- Field access must use
self.#buf/self.#allocatorper Zig private-field syntax. As per coding guidelines.init/initUnslicedaccept[]const u8but#bufis[]u8anddeinitfrees it. Accept[]u8to reflect ownership.Apply this minimal fix; optional: add
slice()accessor for#slice.pub const SlicedBuffer = struct { /// The full allocated buffer #buf: []u8, /// The slice of interest within buf #slice: []const u8, /// Allocator used to free buf #allocator: std.mem.Allocator, - pub fn init(allocator: std.mem.Allocator, buffer: []const u8, slice: []const u8) SlicedBuffer { - bun.assert(@intFromPtr(slice.ptr) >= @intFromPtr(buf.ptr) and - @intFromPtr(slice.ptr) + slice.len <= @intFromPtr(buf.ptr) + buf.len); + pub fn init(allocator: std.mem.Allocator, buffer: []u8, slice: []const u8) SlicedBuffer { + bun.assert(@intFromPtr(slice.ptr) >= @intFromPtr(buffer.ptr) and + @intFromPtr(slice.ptr) + slice.len <= @intFromPtr(buffer.ptr) + buffer.len); return .{ .#buf = buffer, .#slice = slice, .#allocator = allocator, }; } - pub fn buf(self: *const SlicedBuffer) []const u8 { - return self.buf; + pub fn buf(self: *const SlicedBuffer) []const u8 { + return self.#buf; } + + /// Access the active slice. + pub fn slice(self: *const SlicedBuffer) []const u8 { + return self.#slice; + } /// Creates a SlicedBuffer where the slice is the entire buffer (no slicing). - pub fn initUnsliced(allocator: std.mem.Allocator, buffer: []const u8) SlicedBuffer { + pub fn initUnsliced(allocator: std.mem.Allocator, buffer: []u8) SlicedBuffer { return .{ .#buf = buffer, .#slice = buffer, .#allocator = allocator, }; } - pub fn deinit(self: *const SlicedBuffer) void { - self.allocator.free(self.buf); + pub fn deinit(self: *const SlicedBuffer) void { + self.#allocator.free(self.#buf); } };src/install/hosted_git_info.zig (10)
82-84: Private field style: switch_to#(house style)Rename underscore-prefixed fields to
#memory_bufferand#allocatorand update all uses.- _memory_buffer: []const u8, - _allocator: std.mem.Allocator, + #memory_buffer: []const u8, + #allocator: std.mem.Allocator,Also update uses at Lines 141-143 and 167-168 accordingly:
- ._memory_buffer = owned_buffer, - ._allocator = allocator, + .#memory_buffer = owned_buffer, + .#allocator = allocator,And:
- self._allocator.free(self._memory_buffer); + self.#allocator.free(self.#memory_buffer);As per coding guidelines
1148-1153: Private field style in extract.ResultUse
#owned_bufferand#allocatorand update all references (deinit/move).- _owned_buffer: ?[]const u8, - _allocator: std.mem.Allocator, + #owned_buffer: ?[]const u8, + #allocator: std.mem.Allocator,And within methods:
- if (self._owned_buffer) |buf| { - self._allocator.free(buf); + if (self.#owned_buffer) |buf| { + self.#allocator.free(buf); }- if (self._owned_buffer == null) { + if (self.#owned_buffer == null) {- const buffer = self._owned_buffer.?; - const allocator = self._allocator; - self._owned_buffer = null; + const buffer = self.#owned_buffer.?; + const allocator = self.#allocator; + self.#owned_buffer = null;As per coding guidelines
146-163: Rename moveFromextracted → moveFromExtractedAPI polish and consistency. Update definition and call site.
- fn moveFromextracted( + fn moveFromExtracted( extracted: *HostProvider.Config.formatters.extract.Result, host_provider: HostProvider, default_representation: Representation, ) Self { @@ - return HostedGitInfo.moveFromextracted( + return HostedGitInfo.moveFromExtracted( &extracted, host_provider, parsed.proto.defaultRepresentation(), );Also applies to: 363-367
419-443: Unify error name: InvalidGitUrl → InvalidURLKeep error naming consistent with the rest of the codebase and public APIs.
-fn parseUrl(allocator: std.mem.Allocator, npa_str: []u8) error{InvalidGitUrl}!struct { +fn parseUrl(allocator: std.mem.Allocator, npa_str: []u8) error{InvalidURL}!struct { @@ - return error.InvalidGitUrl; + return error.InvalidURL;
486-494: Syntax error: nested return infromStringWithColonReplace with simple conditional; current form won’t compile.
- pub fn fromStringWithColon(protocol_with_colon: []const u8) ?Self { - return if (protocol_with_colon.len == 0) - return null - else - strings.get(bun.strings.trimSuffixComptime(protocol_with_colon, ":")); - } + pub fn fromStringWithColon(protocol_with_colon: []const u8) ?Self { + if (protocol_with_colon.len == 0) return null; + return strings.get(bun.strings.trimSuffixComptime(protocol_with_colon, ":")); + }
628-634: Guard underflow when#is at index 0
npa_str[pi - 1]underflows ifpi == 0. Add a guard.- const does_not_end_with_slash = - if (pound_idx) |pi| - npa_str[pi - 1] != '/' - else - npa_str.len >= 1 and npa_str[npa_str.len - 1] != '/'; + const does_not_end_with_slash = + if (pound_idx) |pi| + if (pi == 0) false else npa_str[pi - 1] != '/' + else + npa_str[npa_str.len - 1] != '/';
126-126: Usetryfor allocation instead ofcatch returnPrefer idiomatic error propagation.
- sb.allocate(allocator) catch return error.OutOfMemory; + try sb.allocate(allocator);
348-351: Propagate parse errors; make logger hiddenDon’t swallow InvalidURL; return it. Also switch scoped logger to
.hiddenand use a generic name.- const parsed = parseUrl(allocator, git_url_mut) catch |err| { - debug("fromUrl: parseUrl failed: {any}\n", .{err}); - return null; - }; + const parsed = try parseUrl(allocator, git_url_mut); @@ -const debug = bun.Output.scoped(.hosted_git_info, .visible); +const log = bun.Output.scoped(.hosted_git_info, .hidden);If you keep logging, change the call site accordingly:
- debug("fromUrl: parseUrl failed: {any}\n", .{err}); + log("fromUrl: parseUrl failed: {any}\n", .{err});Also applies to: 1801-1801
1353-1356: Do not swallow OOM/InvalidURL in extractorsReplace
catch return nullwithtryso real errors propagate; reservenullfor true “no match” cases.@@ - const committish_slice = - if (committish.len > 0) - HostedGitInfo.decodeAndAppend(&sb, committish) catch return null - else - null; + const committish_slice = + if (committish.len > 0) + try HostedGitInfo.decodeAndAppend(&sb, committish) + else + null; @@ - sb.allocate(allocator) catch return null; + try sb.allocate(allocator); @@ - const user_slice = - if (user) |u| - HostedGitInfo.decodeAndAppend(&sb, u) catch return null - else - null; - const project_slice = - HostedGitInfo.decodeAndAppend(&sb, project) catch return null; - const committish_slice = - if (committish) |c| - HostedGitInfo.decodeAndAppend(&sb, c) catch return null - else - null; + const user_slice = if (user) |u| try HostedGitInfo.decodeAndAppend(&sb, u) else null; + const project_slice = try HostedGitInfo.decodeAndAppend(&sb, project); + const committish_slice = if (committish) |c| try HostedGitInfo.decodeAndAppend(&sb, c) else null; @@ - sb.allocate(allocator) catch return null; + try sb.allocate(allocator); @@ - const user_slice = blk: { ... PercentEncoding.decode ... } ; - const project_slice = blk: { ... PercentEncoding.decode ... } ; - const committish_slice = if (committish) |c| blk: { ... } else null; + const user_slice = try HostedGitInfo.decodeAndAppend(&sb, user_part); + const project_slice = try HostedGitInfo.decodeAndAppend(&sb, project); + const committish_slice = if (committish) |c| try HostedGitInfo.decodeAndAppend(&sb, c) else null;Also applies to: 1410-1423, 1471-1505
326-333: Docstring mismatch: ownership semanticsThe value returned by fromUrl owns memory; it’s valid independent of the input string and must be deinitialized by the caller via
deinit(). Update the comment.- /// The HostedGitInfo is valid only for as long as `git_url` is valid. + /// The returned HostedGitInfo owns its memory and remains valid independent of `git_url`. + /// Call `deinit()` when done to free owned allocations.Based on learnings
test/cli/install/validate-npm-package-name/index.ts (1)
5-30: Message remapping is acknowledged debt; track itConsider adding a TODO with issue reference to remove remapping once messages align with npm’s output.
src/install/dependency.zig (1)
811-816: Minor: avoid extra retain with toUTF8WithoutRefUse the no-ref variant since you deref dependency_str already.
Apply this diff:
- const dependency_str = try arguments[0].toBunString(globalObject); - defer dependency_str.deref(); - var as_utf8 = dependency_str.toUTF8(bun.default_allocator); + const dependency_str = try arguments[0].toBunString(globalObject); + defer dependency_str.deref(); + var as_utf8 = dependency_str.toUTF8WithoutRef(bun.default_allocator);test/cli/install/hosted-git-info/cases.ts (1)
28-36: Typos and missing type for invalidGitUrlsFix “shortucts” → “shortcuts”, “protocos” → “protocols”, and add explicit type for invalidGitUrls.
Apply this diff:
- // shortucts + // shortcuts @@ - // shortucts + // shortcuts @@ - // invalid protocos + // invalid protocols @@ -export const invalidGitUrls = { +export const invalidGitUrls: { [K in Provider]: (string | null | undefined)[] } = {Also applies to: 2358-2365, 2464-2471, 2409-2472
src/install/validate_npm_package_name.zig (3)
93-96: Avoid double-flagging for surrounding spacesKeep only name_surrounded_with_spaces here; let later checks handle URL-safety.
Apply this diff:
- result.errors.insert(Error.name_surrounded_with_spaces); - result.errors.insert(Error.name_contains_non_url_safe_characters); + result.errors.insert(Error.name_surrounded_with_spaces);
105-107: Guard builtin check for empty namesSkip extern call when name is empty.
Apply this diff:
- if (ModuleLoader__isBuiltin(name.ptr, name.len)) { + if (name.len > 0 and ModuleLoader__isBuiltin(name.ptr, name.len)) { result.warnings.insert(Warning.core_module_name_conflict); }
198-231: Stabilize JS result shape (always include arrays)Always emit errors and warnings arrays to simplify consumers.
Apply this diff:
- const obj = jsc.JSValue.createEmptyObject(go, 4); + const obj = jsc.JSValue.createEmptyObject(go, 4); @@ - if (result.errors.count() != 0) { - const errors_array = try jsc.JSValue.createEmptyArray(go, 0); - var it = result.errors.iterator(); - while (it.next()) |err| { - try errors_array.push(go, bun.String.fromBytes(err.message()).toJS(go)); - } - obj.put(go, bun.String.static("errors"), errors_array); - } + const errors_array = try jsc.JSValue.createEmptyArray(go, 0); + var it_err = result.errors.iterator(); + while (it_err.next()) |err| { + try errors_array.push(go, bun.String.fromBytes(err.message()).toJS(go)); + } + obj.put(go, bun.String.static("errors"), errors_array); @@ - if (result.warnings.count() != 0) { - const warnings_array = try jsc.JSValue.createEmptyArray(go, 0); - var it = result.warnings.iterator(); - while (it.next()) |warn| { - try warnings_array.push(go, bun.String.fromBytes(warn.message()).toJS(go)); - } - obj.put(go, bun.String.static("warnings"), warnings_array); - } + const warnings_array = try jsc.JSValue.createEmptyArray(go, 0); + var it_warn = result.warnings.iterator(); + while (it_warn.next()) |warn| { + try warnings_array.push(go, bun.String.fromBytes(warn.message()).toJS(go)); + } + obj.put(go, bun.String.static("warnings"), warnings_array);src/install/npm_package_arg.zig (9)
119-129: Deinit order: free arena lastRelease type resources before freeing the arena to avoid dangling slices.
Apply this diff:
- pub fn deinit(self: *Self) void { - if (self._arena_buffer) |arena| { - self._allocator.free(arena); - } - - switch (self.type) { - .git => |*g| g.deinit(self._allocator), - .alias => |*a| a.deinit(self._allocator), - else => {}, - } - } + pub fn deinit(self: *Self) void { + switch (self.type) { + .git => |*g| g.deinit(self._allocator), + .alias => |*a| a.deinit(self._allocator), + else => {}, + } + if (self._arena_buffer) |arena| { + self._allocator.free(arena); + } + }
155-172: JS shape: always include “registry” and preallocate enoughStabilize object shape and bump capacity to reduce rehashing.
Apply this diff:
- var object = jsc.JSValue.createEmptyObject(go, 8); + var object = jsc.JSValue.createEmptyObject(go, 12); @@ - if (self.isRegistry()) { - object.put(go, "registry", .true); - } + object.put(go, "registry", if (self.isRegistry()) .true else .false);Also applies to: 222-226
293-332: SCP-style git+ssh: make saveSpec exclude the hashAlign with npm: saveSpec should be href without fragment.
Apply this diff:
- const raw_spec_slice = arena.copyString(raw_spec); + const raw_spec_slice = arena.copyString(raw_spec); const fetch_spec_slice = arena.copyString(scp_result.fragment); + const hash_idx = bun.strings.indexOfChar(raw_spec, '#'); @@ - .save_spec = raw_spec_slice, + .save_spec = if (hash_idx) |i| arena.copyString(raw_spec[0..i]) else raw_spec_slice,
393-416: Windows drive-letter heuristic: require colon after single-letter hostPrevent misclassifying single-letter hosts (a.example) as drives.
Apply this diff:
- if (parts.host_lower.len == 1 and - std.ascii.isAlphabetic(parts.host_lower[0])) + if (parts.host_lower.len == 1 and + std.ascii.isAlphabetic(parts.host_lower[0]) and + (parts.pathname.len > 0 and parts.pathname[0] == ':'))
836-851: Avoid magic substring; use decoded spec_path for absolute checkRead from spec_path instead of bun.strings.substring(raw_spec, 5, null).
Apply this diff:
- } else if (!std.fs.path.isAbsolute(bun.strings.substring(raw_spec, 5, null))) { + } else if (!std.fs.path.isAbsolute(spec_path)) {
957-965: Normalize path: ensure single leading slash for subdirTrim leading slashes from value before prefixing “/” to avoid “//subdir”.
Apply this diff:
- res.subdir = try std.fmt.allocPrint(allocator, "/{s}", .{value}); + const trimmed = bun.strings.trimChar(value, '/'); + res.subdir = try std.fmt.allocPrint(allocator, "/{s}", .{trimmed});
1520-1554: Tighten JS error messages (consistent, concise)Use consistent phrasing and method names.
Apply this diff:
- return go.throw("Npa.npa takes at least 1 argument", .{}); + return go.throw("Npa.npa requires at least 1 argument", .{}); @@ - ) catch |err| { - return go.throwError(err, "Unexpected error in Npa.npa"); + ) catch |err| { + return go.throwError(err, "Npa.npa failed"); }; @@ - return go.throw("Npa.prototype.resolve takes at least 1 argument", .{}); + return go.throw("Npa.prototype.resolve requires at least 1 argument", .{}); @@ - )) catch |err| { - return go.throwError(err, "Unexpected error in Npa.prototype.resolve"); + )) catch |err| { + return go.throwError(err, "Npa.prototype.resolve failed"); };Also applies to: 1563-1566, 1605-1613
823-835: Validate HOME is non-empty before tilde expansionEmpty HOME should error rather than build an invalid path.
Apply this diff:
- if (bun.getenvZ("HOME")) |home_dir| { + if (bun.getenvZ("HOME")) |home_dir| { + if (home_dir.len == 0) return error.InvalidPath; const path_after_tilde = if (spec_path.len > 3) spec_path[3..] else "";
33-39: Follow private-field convention (#-prefix) in this fileRename _allocator/_arena_buffer/_fetch_spec_slice to #allocator/#arena_buffer/#fetch_spec_slice for consistency.
Based on learnings.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between a99441c and 03dde552d26959ecb4b4bcacd057b6beff8d4edb.
⛔ Files ignored due to path filters (1)
test/cli/install/__snapshots__/bun-install-dep.test.ts.snapis excluded by!**/*.snap
📒 Files selected for processing (25)
src/bun.js/bindings/BunString.cpp(1 hunks)src/bun.js/bindings/URL.zig(1 hunks)src/bun.js/node/path.zig(1 hunks)src/comptime_string_map.zig(1 hunks)src/install/dependency.zig(10 hunks)src/install/hosted_git_info.zig(1 hunks)src/install/npm_package_arg.zig(1 hunks)src/install/validate_npm_package_name.zig(1 hunks)src/js/internal-for-testing.ts(1 hunks)src/resolver/resolve_path.zig(1 hunks)src/semver/SemverQuery.zig(1 hunks)src/string/immutable.zig(10 hunks)src/string/immutable/paths.zig(0 hunks)src/url.zig(2 hunks)test/cli/install/bun-install-dep.test.ts(0 hunks)test/cli/install/hosted-git-info/cases.ts(1 hunks)test/cli/install/hosted-git-info/from-url.test.ts(1 hunks)test/cli/install/hosted-git-info/parse-url.test.ts(1 hunks)test/cli/install/npm-package-arg/cases.ts(1 hunks)test/cli/install/npm-package-arg/index.test.ts(1 hunks)test/cli/install/npm-package-arg/invalid-url.test.ts(1 hunks)test/cli/install/npm-package-arg/memory-safety.test.ts(1 hunks)test/cli/install/npm-package-arg/realize-package-specifier.test.ts(1 hunks)test/cli/install/validate-npm-package-name/cases.ts(1 hunks)test/cli/install/validate-npm-package-name/index.ts(1 hunks)
💤 Files with no reviewable changes (2)
- test/cli/install/bun-install-dep.test.ts
- src/string/immutable/paths.zig
🧰 Additional context used
📓 Path-based instructions (13)
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/bun.js/bindings/URL.zigsrc/url.zigsrc/resolver/resolve_path.zigsrc/bun.js/node/path.zigsrc/install/validate_npm_package_name.zigsrc/install/dependency.zigsrc/comptime_string_map.zigsrc/install/hosted_git_info.zigsrc/install/npm_package_arg.zigsrc/string/immutable.zigsrc/semver/SemverQuery.zig
src/bun.js/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/zig-javascriptcore-classes.mdc)
src/bun.js/**/*.zig: In Zig binding structs, expose generated bindings via pub const js = JSC.Codegen.JS and re-export toJS/fromJS/fromJSDirect
Constructors and prototype methods should return bun.JSError!JSC.JSValue to integrate Zig error handling with JS exceptions
Use parameter name globalObject (not ctx) and accept (*JSC.JSGlobalObject, *JSC.CallFrame) in binding methods/constructors
Implement getters as get(this, globalObject) returning JSC.JSValue and matching the .classes.ts interface
Provide deinit() for resource cleanup and finalize() that calls deinit(); use bun.destroy(this) or appropriate destroy pattern
Access JS call data via CallFrame (argument(i), argumentCount(), thisValue()) and throw errors with globalObject.throw(...)
For properties marked cache: true, use the generated Zig accessors (NameSetCached/GetCached) to work with GC-owned values
In finalize() for objects holding JS references, release them using .deref() before destroy
Files:
src/bun.js/bindings/URL.zigsrc/bun.js/node/path.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
When adding debug logs in Zig, create a scoped logger and log via Bun APIs:
const log = bun.Output.scoped(.${SCOPE}, .hidden);thenlog("...", .{})
src/**/*.zig: Use Zig private fields with the # prefix for encapsulation (e.g., struct { #foo: u32 })
Prefer Decl literals for initialization (e.g., const decl: Decl = .{ .binding = 0, .value = 0 };)
Place @import statements at the bottom of the file (formatter will handle ordering)
src/**/*.zig: In Zig code, manage memory carefully: use appropriate allocators and defer for cleanup
Cache JavaScriptCore class structures in ZigGlobalObject when adding new classes
Files:
src/bun.js/bindings/URL.zigsrc/url.zigsrc/resolver/resolve_path.zigsrc/bun.js/node/path.zigsrc/install/validate_npm_package_name.zigsrc/install/dependency.zigsrc/comptime_string_map.zigsrc/install/hosted_git_info.zigsrc/install/npm_package_arg.zigsrc/string/immutable.zigsrc/semver/SemverQuery.zig
test/**
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place all tests under the test/ directory
Files:
test/cli/install/validate-npm-package-name/cases.tstest/cli/install/hosted-git-info/from-url.test.tstest/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/hosted-git-info/parse-url.test.tstest/cli/install/npm-package-arg/cases.tstest/cli/install/hosted-git-info/cases.ts
test/cli/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Files:
test/cli/install/validate-npm-package-name/cases.tstest/cli/install/hosted-git-info/from-url.test.tstest/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/hosted-git-info/parse-url.test.tstest/cli/install/npm-package-arg/cases.tstest/cli/install/hosted-git-info/cases.ts
test/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable
Files:
test/cli/install/validate-npm-package-name/cases.tstest/cli/install/hosted-git-info/from-url.test.tstest/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/hosted-git-info/parse-url.test.tstest/cli/install/npm-package-arg/cases.tstest/cli/install/hosted-git-info/cases.ts
test/**/*.{ts,tsx,js,jsx,mjs,cjs}
📄 CodeRabbit inference engine (test/CLAUDE.md)
For large/repetitive strings, use
Buffer.alloc(count, fill).toString()instead of"A".repeat(count)
Files:
test/cli/install/validate-npm-package-name/cases.tstest/cli/install/hosted-git-info/from-url.test.tstest/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/hosted-git-info/parse-url.test.tstest/cli/install/npm-package-arg/cases.tstest/cli/install/hosted-git-info/cases.ts
test/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Avoid shell commands in tests (e.g., find, grep); use Bun's Glob and built-in tools
Files:
test/cli/install/validate-npm-package-name/cases.tstest/cli/install/hosted-git-info/from-url.test.tstest/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/hosted-git-info/parse-url.test.tstest/cli/install/npm-package-arg/cases.tstest/cli/install/hosted-git-info/cases.ts
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}: Usebun:testfor files ending with*.test.{ts,js,jsx,tsx,mjs,cjs}
Prefer concurrent tests (test.concurrent/describe.concurrent) over sequential when feasible
Organize tests withdescribeblocks to group related tests
Use utilities likedescribe.each,toMatchSnapshot, and lifecycle hooks (beforeAll,beforeEach,afterEach) and track resources for cleanup
Files:
test/cli/install/hosted-git-info/from-url.test.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/hosted-git-info/parse-url.test.ts
test/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
test/**/*.test.{ts,tsx}: Test files must live under test/ and end with .test.ts or .test.tsx
In tests, always use port: 0; do not hardcode ports or invent random port functions
Prefer snapshot assertions and use normalizeBunSnapshot for snapshot output in tests
Never write tests that assert absence of crashes (e.g., no "panic" or "uncaught exception") in output
Use tempDir from "harness" for temporary directories; do not use tmpdirSync or fs.mkdtempSync in tests
When spawning processes in tests, assert on stdout before asserting exitCode
Do not use setTimeout in tests; await conditions instead to avoid flakiness
Files:
test/cli/install/hosted-git-info/from-url.test.tstest/cli/install/npm-package-arg/invalid-url.test.tstest/cli/install/npm-package-arg/index.test.tstest/cli/install/npm-package-arg/memory-safety.test.tstest/cli/install/npm-package-arg/realize-package-specifier.test.tstest/cli/install/hosted-git-info/parse-url.test.ts
**/*.{cpp,h}
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.{cpp,h}: When exposing a JS class with public Constructor and Prototype, define three C++ types: class Foo : public JSC::DestructibleObject (if it has C++ fields), class FooPrototype : public JSC::JSNonFinalObject, and class FooConstructor : public JSC::InternalFunction
If the class has C++ data members, inherit from JSC::DestructibleObject and provide proper destruction; if it has no C++ fields (only JS properties), avoid a class and use JSC::constructEmptyObject(vm, structure) with putDirectOffset
Prefer placing the subspaceFor implementation in the .cpp file rather than the header when possible
Files:
src/bun.js/bindings/BunString.cpp
**/*.cpp
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.cpp: Include "root.h" at the top of C++ binding files to satisfy lints
Define prototype properties using a const HashTableValue array and declare accessors/functions with JSC_DECLARE_* macros
Prototype classes should subclass JSC::JSNonFinalObject, provide create/createStructure, DECLARE_INFO, finishCreation that reifies static properties, and set mayBePrototype on the Structure
Custom getters should use JSC_DEFINE_CUSTOM_GETTER, jsDynamicCast to validate this, and throwThisTypeError on mismatch
Custom setters should use JSC_DEFINE_CUSTOM_SETTER, validate this via jsDynamicCast, and store via WriteBarrier/set semantics
Prototype functions should use JSC_DEFINE_HOST_FUNCTION, validate this with jsDynamicCast, and return encoded JSValue
Constructors should subclass JSC::InternalFunction, return internalFunctionSpace in subspaceFor, set the prototype property as non-configurable/non-writable, and provide create/createStructure
Provide a setup function that builds the Prototype, Constructor, and Structure, and assigns them to the LazyClassStructure initializer
Use the cached Structure via globalObject->m_.get(globalObject) when constructing instances
Expose constructors to Zig via an extern "C" function that returns the constructor from the LazyClassStructure
Provide an extern "C" Bun____toJS function that creates an instance using the cached Structure and returns an EncodedJSValue
Files:
src/bun.js/bindings/BunString.cpp
src/bun.js/bindings/**/*.cpp
📄 CodeRabbit inference engine (CLAUDE.md)
src/bun.js/bindings/**/*.cpp: When implementing a JavaScript class with a public constructor in C++, create Foo, FooPrototype, and FooConstructor classes
Define class properties using HashTableValue arrays in C++ bindings
Add iso subspaces for classes with C++ fields in JavaScriptCore bindings
Files:
src/bun.js/bindings/BunString.cpp
🧠 Learnings (15)
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/js/third_party/**/*.{js,ts} : Place third-party npm package tests under test/js/third_party/
Applied to files:
test/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/index.test.ts
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/**/*.{js,ts} : Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Applied to files:
test/cli/install/validate-npm-package-name/index.ts
📚 Learning: 2025-10-19T02:44:46.354Z
Learnt from: theshadow27
PR: oven-sh/bun#23798
File: packages/bun-otel/context-propagation.test.ts:1-1
Timestamp: 2025-10-19T02:44:46.354Z
Learning: In the Bun repository, standalone packages under packages/ (e.g., bun-vscode, bun-inspector-protocol, bun-plugin-yaml, bun-plugin-svelte, bun-debug-adapter-protocol, bun-otel) co-locate their tests with package source code using *.test.ts files. This follows standard npm/monorepo patterns. The test/ directory hierarchy (test/js/bun/, test/cli/, test/js/node/) is reserved for testing Bun's core runtime APIs and built-in functionality, not standalone packages.
Applied to files:
test/cli/install/validate-npm-package-name/index.tstest/cli/install/npm-package-arg/realize-package-specifier.test.ts
📚 Learning: 2025-10-16T17:32:03.074Z
Learnt from: markovejnovic
PR: oven-sh/bun#23710
File: src/install/PackageManager/PackageManagerOptions.zig:187-193
Timestamp: 2025-10-16T17:32:03.074Z
Learning: In Bun's codebase (particularly in files like src/install/PackageManager/PackageManagerOptions.zig), mixing bun.EnvVar.*.get() and bun.EnvVar.*.platformGet() for environment variable lookups is intentional and safe. The code is protected by compile-time platform checks (Environment.isWindows, etc.), and compilation will fail if the wrong function is used on the wrong platform. This pattern should not be flagged as a consistency issue.
Applied to files:
src/resolver/resolve_path.zig
📚 Learning: 2025-10-08T13:56:00.875Z
Learnt from: Jarred-Sumner
PR: oven-sh/bun#23373
File: src/bun.js/api/BunObject.zig:2514-2521
Timestamp: 2025-10-08T13:56:00.875Z
Learning: For Bun codebase: prefer using `bun.path` utilities (e.g., `bun.path.joinAbsStringBuf`, `bun.path.join`) over `std.fs.path` functions for path operations.
Applied to files:
src/bun.js/node/path.zig
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Applies to src/{**/js_*.zig,bun.js/api/**/*.zig} : Use bun.JSError!JSValue for proper error propagation in JS-exposed Zig functions
Applied to files:
src/install/validate_npm_package_name.zig
📚 Learning: 2025-10-25T22:53:31.261Z
Learnt from: CR
PR: oven-sh/bun#0
File: src/CLAUDE.md:0-0
Timestamp: 2025-10-25T22:53:31.261Z
Learning: Applies to src/**/*.zig : Use Zig private fields with the # prefix for encapsulation (e.g., struct { #foo: u32 })
Applied to files:
src/install/hosted_git_info.zigsrc/install/npm_package_arg.zig
📚 Learning: 2025-09-02T18:25:27.976Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/allocators/allocation_scope.zig:284-314
Timestamp: 2025-09-02T18:25:27.976Z
Learning: In bun's custom Zig implementation, the `#` prefix for private fields is valid syntax and should not be flagged as invalid. The syntax `#fieldname` creates private fields that cannot be accessed from outside the defining struct, and usage like `self.#fieldname` is correct within the same struct. This applies to fields like `#parent`, `#state`, `#allocator`, `#trace`, etc. throughout the codebase.
Applied to files:
src/install/hosted_git_info.zigsrc/install/npm_package_arg.zig
📚 Learning: 2025-09-02T17:14:46.924Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/safety/alloc.zig:93-95
Timestamp: 2025-09-02T17:14:46.924Z
Learning: In bun's Zig codebase, they use a custom extension of Zig that supports private field syntax with the `#` prefix (e.g., `#allocator`, `#trace`). This is not standard Zig syntax but is valid in their custom implementation. Fields prefixed with `#` are private fields that cannot be accessed from outside the defining struct.
Applied to files:
src/install/hosted_git_info.zigsrc/install/npm_package_arg.zig
📚 Learning: 2025-10-08T03:11:45.286Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/building-bun.mdc:0-0
Timestamp: 2025-10-08T03:11:45.286Z
Learning: Applies to src/**/*.zig : When adding debug logs in Zig, create a scoped logger and log via Bun APIs: `const log = bun.Output.scoped(.${SCOPE}, .hidden);` then `log("...", .{})`
Applied to files:
src/install/hosted_git_info.zig
📚 Learning: 2025-10-18T02:06:31.606Z
Learnt from: pfgithub
PR: oven-sh/bun#23796
File: src/bun.js/test/Execution.zig:624-625
Timestamp: 2025-10-18T02:06:31.606Z
Learning: In Zig files using bun.Output.scoped(), the visibility level `.visible` means logs are enabled by default in debug builds unless `BUN_DEBUG_QUIET_LOGS=1` is set; if that environment variable is set, the logs can be re-enabled with `BUN_DEBUG_<scope>=1`. Use `.visible` for logs that should appear by default in debug builds, and `.hidden` for logs that require explicit opt-in via `BUN_DEBUG_<scope>=1`.
Applied to files:
src/install/hosted_git_info.zig
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Applies to src/**/js_*.zig : Always implement proper cleanup in deinit() and finalize() for JS-exposed types
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Implement the core feature in Zig under its own directory within src/<feature>/
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-02T18:27:23.279Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/collections/multi_array_list.zig:24-24
Timestamp: 2025-09-02T18:27:23.279Z
Learning: The `#allocator` syntax in bun's custom Zig implementation is valid and does not require quoting with @"#allocator". Private fields using the `#` prefix work correctly throughout the codebase without special quoting syntax.
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-25T18:14:27.731Z
Learnt from: cirospaciari
PR: oven-sh/bun#22842
File: src/bun.js/webcore/ResumableSink.zig:274-276
Timestamp: 2025-09-25T18:14:27.731Z
Learning: In Zig code, private fields are declared and accessed using the `#` prefix. When a field is declared as `#field_name`, it must be accessed as `this.#field_name`, not `this.field_name`. The `#` prefix is part of the private field access syntax and should not be removed.
Applied to files:
src/install/npm_package_arg.zig
🧬 Code graph analysis (7)
test/cli/install/hosted-git-info/from-url.test.ts (2)
test/cli/install/hosted-git-info/cases.ts (2)
validGitUrls(26-2407)invalidGitUrls(2409-2472)src/js/internal-for-testing.ts (1)
hostedGitInfo(210-213)
test/cli/install/validate-npm-package-name/index.ts (1)
src/js/internal-for-testing.ts (1)
ValidateNpmPackageName(220-222)
test/cli/install/npm-package-arg/invalid-url.test.ts (1)
src/js/internal-for-testing.ts (1)
Npa(215-218)
test/cli/install/npm-package-arg/index.test.ts (1)
src/js/internal-for-testing.ts (1)
Npa(215-218)
test/cli/install/npm-package-arg/memory-safety.test.ts (1)
src/js/internal-for-testing.ts (1)
Npa(215-218)
test/cli/install/npm-package-arg/realize-package-specifier.test.ts (1)
src/js/internal-for-testing.ts (1)
Npa(215-218)
test/cli/install/hosted-git-info/parse-url.test.ts (1)
src/js/internal-for-testing.ts (1)
hostedGitInfo(210-213)
🔇 Additional comments (17)
src/string/immutable.zig (7)
476-481: LGTM: bounds-checked generic char access.
1028-1036: LGTM: case-insensitive endsWith helpers.
1561-1574: LGTM: countLeadingChar utility.
1601-1608: LGTM: constexpr suffix trim.
1815-1818: LGTM: trimSpaces wrapper.
1825-1832: LGTM: containsUppercaseAscii (SIMD left for later).
2099-2109: Verification complete: All concat() call sites properly handle bun.OOM.The scan identified 12 call sites, and examining full context confirms all properly handle the error type using
try,bun.handleOom(), or explicitcatchpatterns. No unhandled error cases found.src/semver/SemverQuery.zig (2)
231-239: isExact: tightened criteria look goodDirectly checking left == eql and right == unset plus empty next/tail matches getExactVersion invariants. LGTM.
241-243: New isEmpty utility is appropriateClear and matches existing emptiness checks in Formatter; good addition.
test/cli/install/npm-package-arg/invalid-url.test.ts (1)
4-6: LGTM: invalid URL path is coveredSimple and correct assertion for error surface.
test/cli/install/hosted-git-info/parse-url.test.ts (1)
17-21: LGTM: parameterized coverage for parseUrlGood set of canonical and Bun-specific cases; non-null check matches API.
src/js/internal-for-testing.ts (1)
210-222: LGTM!The new testing API exports follow the established pattern and correctly bind to the Zig implementations with appropriate parameter counts.
src/bun.js/bindings/BunString.cpp (1)
627-641: LGTM!The URL fragment accessor functions are correctly implemented:
URL__hashincludes the leading '#' when presentURL__fragmentIdentifierexcludes the leading '#'- Both properly handle empty fragments and use
Bun::toStringReffor memory managementsrc/bun.js/bindings/URL.zig (1)
19-32: LGTM!The URL fragment bindings are well-structured:
- Clear documentation distinguishes
hash()(includes '#') fromfragmentIdentifier()(excludes '#')- Proper use of
markBindingfor tracking- Consistent with other URL method wrappers in this file
test/cli/install/validate-npm-package-name/cases.ts (1)
1-102: LGTM!The test cases provide comprehensive coverage of npm package name validation scenarios, including edge cases for empty names, special characters, reserved names, core modules, and length limits.
src/install/dependency.zig (2)
573-581: DRY the HostedGitInfo probe + mappingThe duplicate “dupe → fromUrl → map provider → free” blocks risk drift. Extract a helper and reuse.
[ suggest_essential_refactor ]
[ duplicate_comment ]
Apply (example):+fn classifyHosted(allocator: std.mem.Allocator, dep: []const u8) ?Version.Tag { + const copy = bun.handleOom(allocator.dupe(u8, dep)); + defer allocator.free(copy); + const info = hosted_git_info.HostedGitInfo.fromUrl(allocator, copy) catch null orelse return null; + defer info.deinit(); + return switch (info.host_provider) { + .github => .github, + .bitbucket, .gitlab, .gist, .sourcehut => .git, + }; +} @@ - const copy = bun.handleOom(allocator.dupe(u8, dependency)); - defer allocator.free(copy); - if (hosted_git_info.HostedGitInfo.fromUrl(allocator, copy) catch null) |info| { - defer info.deinit(); - return switch (info.host_provider) { - .github => .github, - .bitbucket, .gitlab, .gist, .sourcehut => .git, - }; - } + if (classifyHosted(allocator, dependency)) |tag| return tag; @@ - const dep_copy = bun.handleOom(allocator.dupe(u8, dependency)); - defer allocator.free(dep_copy); - if (hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch null) |info| { - defer info.deinit(); - return switch (info.host_provider) { - .github => if (info.default_representation == .shortcut) .github else .git, - .bitbucket, .gitlab, .gist, .sourcehut => .git, - }; - } + if (classifyHosted(allocator, dependency)) |tag| return tag; @@ - const dep_copy = bun.handleOom(allocator.dupe(u8, dependency)); - defer allocator.free(dep_copy); - if (hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch null) |info| { - defer info.deinit(); - return switch (info.host_provider) { - .github => .github, - .bitbucket, .gitlab, .gist, .sourcehut => .git, - }; - } + if (classifyHosted(allocator, dependency)) |tag| return tag; @@ - const dep_copy = bun.handleOom(allocator.dupe(u8, dependency)); - defer allocator.free(dep_copy); - if (hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch null) |info| { - defer info.deinit(); - return switch (info.host_provider) { - .github => .github, - .bitbucket, .gitlab, .gist, .sourcehut => .git, - }; - } + if (classifyHosted(allocator, dependency)) |tag| return tag; @@ - const dep_copy = bun.handleOom(allocator.dupe(u8, dependency)); - defer allocator.free(dep_copy); - if (hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch null) |info| { - defer info.deinit(); - return switch (info.host_provider) { - .github => .github, - .bitbucket, .gitlab, .gist, .sourcehut => .git, - }; - } + if (classifyHosted(allocator, dependency)) |tag| return tag;Also applies to: 615-632, 675-683, 703-711, 782-793
652-686: HTTP(S) fallback may misclassify non-tarball git URLsUnrecognized providers fall through to .tarball. Confirm behavior for https://example.com/org/repo.git and add tests if needed.
Would you add cases asserting Tag.github/.git for:
- https://bitbucket.org/user/repo(.git)
- https://gitlab.com/user/repo(.git)
- https://notgithub.com/user/repo.git
If HostedGitInfo rejects unknown hosts, ensure .git is returned when path ends with “.git”; otherwise .tarball is okay.
| /// Returns a substring starting at `start` up to the end of the string. | ||
| /// If `start` is greater than the string's length, returns an empty string. | ||
| pub fn substring(self: anytype, start: ?usize, stop: ?usize) @TypeOf(self) { | ||
| const sta = start orelse 0; | ||
| const sto = stop orelse self.len; | ||
|
|
||
| return self[@min(sta, self.len)..@min(sto, self.len)]; | ||
| } | ||
|
|
There was a problem hiding this comment.
Fix start > stop slicing and doc mismatch.
Current code can slice with start > stop, which panics at runtime. Also docs mention only start; function accepts stop too. Return empty when s >= e and document semantics.
-/// Returns a substring starting at `start` up to the end of the string.
-/// If `start` is greater than the string's length, returns an empty string.
+/// Returns the substring in [start, stop).
+/// - Null start/stop clamp to [0, self.len]
+/// - If start >= stop (after clamping), returns empty
+/// - Negative indices are not supported
pub fn substring(self: anytype, start: ?usize, stop: ?usize) @TypeOf(self) {
- const sta = start orelse 0;
- const sto = stop orelse self.len;
-
- return self[@min(sta, self.len)..@min(sto, self.len)];
+ const sta = start orelse 0;
+ const sto = stop orelse self.len;
+ const s = @min(sta, self.len);
+ const e = @min(sto, self.len);
+ if (s >= e) return self[self.len..self.len];
+ return self[s..e];
}🤖 Prompt for AI Agents
In src/string/immutable.zig around lines 1156 to 1164, the substring
implementation and doc are incorrect: it allows start > stop which causes a
runtime slice panic and the doc only mentions `start` while the function accepts
`stop`. Clamp both start and stop to [0..self.len], then if the clamped start is
greater than or equal to the clamped stop return an empty string slice instead
of attempting the invalid range; also update the docstring to mention both
`start` and `stop` and the behavior of returning an empty string when the
effective start >= stop.
| 'file:~/path/to/foo': { | ||
| name: null, | ||
| escapedName: null, | ||
| type: 'directory', | ||
| saveSpec: 'file:~/path/to/foo', | ||
| fetchSpec: path.normalize(path.join(os.homedir(), '/path/to/foo')), | ||
| raw: 'file:~/path/to/foo', | ||
| }, |
There was a problem hiding this comment.
Fix tilde expansion: don’t discard HOME with absolute join
path.join(os.homedir(), '/path/to/foo') drops the home dir. Use resolve/join with a relative segment.
Apply this diff:
- fetchSpec: path.normalize(path.join(os.homedir(), '/path/to/foo')),
+ fetchSpec: path.resolve(os.homedir(), 'path/to/foo'),
@@
- fetchSpec: path.normalize(path.join(os.homedir(), '/path/to/foo')),
+ fetchSpec: path.resolve(os.homedir(), 'path/to/foo'),Also applies to: 422-429
🤖 Prompt for AI Agents
In test/cli/install/npm-package-arg/cases.ts around lines 413–420 (and also
lines 422–429), the test constructs fetchSpec using path.join(os.homedir(),
'/path/to/foo') which discards the home directory because the second argument is
absolute; change the join to use a relative segment (e.g.,
path.join(os.homedir(), 'path/to/foo')) or use path.resolve(os.homedir(),
'path/to/foo') and keep path.normalize around the result so tilde expansion
preserves the actual HOME path; apply the same fix to the other mentioned block.
| describe("npm-package-arg memory safety", () => { | ||
| describe("fromAlias error paths", () => { | ||
| test("handles nested alias error without leaking", () => { | ||
| // This should trigger error.NestedAlias | ||
| // Before fix: leaked sub_spec allocation | ||
| expect(() => { | ||
| Npa.npa("foo@npm:bar@npm:baz", "/test/path"); | ||
| }).toThrow(); | ||
| }); | ||
|
|
||
| test("handles non-registry alias without leaking", () => { | ||
| // This should trigger error.NotAliasingRegistry | ||
| // Before fix: leaked sub_spec allocation | ||
| expect(() => { | ||
| Npa.npa("foo@npm:github:user/repo", "/test/path"); | ||
| }).toThrow(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("fromGitSpec error paths", () => { | ||
| test("handles valid git spec without crashing", () => { | ||
| // This should succeed and properly clean up | ||
| const result = Npa.npa("github:user/repo", "/test/path"); | ||
| expect(result.type).toBe("git"); | ||
| expect(result.hosted).toBeDefined(); | ||
| }); | ||
|
|
||
| test("handles git spec with committish", () => { | ||
| // Tests that git_attrs is properly managed | ||
| // Before fix: if internal allocation failed, hosted would leak | ||
| const result = Npa.npa("github:user/repo#v1.0.0", "/test/path"); | ||
| expect(result.type).toBe("git"); | ||
| expect(result.gitCommittish).toBe("v1.0.0"); | ||
| }); | ||
|
|
||
| test("handles git spec with semver range", () => { | ||
| // Tests GitAttrs.fromCommittish with semver parsing | ||
| // This also exercises the double-free fix (Bug #3) | ||
| const result = Npa.npa("github:user/repo#semver:^1.0.0", "/test/path"); | ||
| expect(result.type).toBe("git"); | ||
| expect(result.gitRange).toBe("^1.0.0"); | ||
| }); | ||
|
|
||
| test("handles git spec with path", () => { | ||
| // Tests GitAttrs.fromCommittish with subdir | ||
| const result = Npa.npa("github:user/repo#path:packages/foo", "/test/path"); | ||
| expect(result.type).toBe("git"); | ||
| expect(result.gitSubdir).toBe("/packages/foo"); | ||
| }); | ||
|
|
||
| test("handles git spec with multiple attributes", () => { | ||
| // Tests GitAttrs.fromCommittish with multiple parts | ||
| const result = Npa.npa("github:user/repo#v1.0.0::path:packages/foo", "/test/path"); | ||
| expect(result.type).toBe("git"); | ||
| expect(result.gitCommittish).toBe("v1.0.0"); | ||
| expect(result.gitSubdir).toBe("/packages/foo"); | ||
| }); | ||
| }); | ||
|
|
||
| describe("GitAttrs.fromCommittish edge cases", () => { | ||
| test("handles invalid percent encoding in semver range", () => { | ||
| // This should trigger the error path in PercentEncoding.decode | ||
| // Before fix: double-free when error returned | ||
| // The percent encoding needs to be malformed to trigger decode error | ||
| expect(() => { | ||
| Npa.npa("github:user/repo#semver:%XX", "/test/path"); | ||
| }).toThrow(); | ||
| }); | ||
|
|
||
| test("handles duplicate committish attributes", () => { | ||
| // Should trigger error.InvalidCommittish | ||
| expect(() => { | ||
| Npa.npa("github:user/repo#v1.0.0::v2.0.0", "/test/path"); | ||
| }).toThrow(); | ||
| }); | ||
|
|
||
| test("handles committish and semver conflict", () => { | ||
| // Should trigger error.InvalidCommittish (can't have both) | ||
| expect(() => { | ||
| Npa.npa("github:user/repo#v1.0.0::semver:^1.0.0", "/test/path"); | ||
| }).toThrow(); | ||
| }); | ||
|
|
||
| test("handles duplicate subdir", () => { | ||
| // Should trigger error.InvalidCommittish | ||
| expect(() => { | ||
| Npa.npa("github:user/repo#path:foo::path:bar", "/test/path"); | ||
| }).toThrow(); | ||
| }); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
LGTM; consider making tests concurrent
Safe, focused cases. You can switch to test.concurrent/describe.concurrent to speed up since no shared state.
🤖 Prompt for AI Agents
In test/cli/install/npm-package-arg/memory-safety.test.ts around lines 4 to 94,
the suite is fully isolated and can be executed in parallel; update the test
declarations to run concurrently to speed CI: replace describe(...) with
describe.concurrent(...) for the top-level and inner describe blocks (or
alternatively change individual test(...) to test.concurrent(...) where
preferred), ensuring no shared mutable state exists between tests; keep
assertions and test logic unchanged.
03dde55 to
ed993b5
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (14)
src/resolver/resolve_path.zig (1)
40-48: Duplication issue already raised in previous review.This implementation duplicates the function in
src/paths/Path.zig(lines 966-973). As noted in the previous review, consider consolidating to avoid maintenance burden by having one module call the other.The implementation itself is correct: Windows properly accepts both
\and/as separators, and POSIX correctly checks only for/.src/install/dependency.zig (2)
811-819: Use toUTF8WithoutRef to avoid keeping a JS string alivePrefer without-ref variant to reduce retain window and match local style.
- const dependency_str = try arguments[0].toBunString(globalObject); - defer dependency_str.deref(); - var as_utf8 = dependency_str.toUTF8(bun.default_allocator); + const dependency_str = try arguments[0].toBunString(globalObject); + defer dependency_str.deref(); + var as_utf8 = dependency_str.toUTF8WithoutRef(bun.default_allocator); defer as_utf8.deinit();
1074-1107: .github fallback should degrade to .git with parsed repo/ref (not empty github fields)Returning .github with empty owner/repo leaks structure and loses info. Fall back to .git and split repo/committish from the input.
Apply:
- const info = hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch { - // Fallback to empty if parsing fails - return .{ - .literal = sliced.value(), - .value = .{ - .github = .{ - .owner = String.from(""), - .repo = String.from(""), - .committish = String.from(""), - }, - }, - .tag = .github, - }; - } orelse { - // Fallback to empty if parsing returns null - return .{ - .literal = sliced.value(), - .value = .{ - .github = .{ - .owner = String.from(""), - .repo = String.from(""), - .committish = String.from(""), - }, - }, - .tag = .github, - }; - }; + const info = hosted_git_info.HostedGitInfo.fromUrl(allocator, dep_copy) catch null orelse { + const hash_index = strings.lastIndexOfChar(dependency, '#'); + return .{ + .literal = sliced.value(), + .value = .{ + .git = .{ + .owner = String.from(""), + .repo = sliced.sub(if (hash_index) |i| dependency[0..i] else dependency).value(), + .committish = if (hash_index) |i| sliced.sub(dependency[i + 1 ..]).value() else String.from(""), + }, + }, + .tag = .git, + }; + };Also applies to: 1093-1105, 1141-1144
src/install/npm_package_arg.zig (11)
33-39: Adopt project’s #private-field conventionRename _allocator, _arena_buffer, _fetch_spec_slice to #allocator, #arena_buffer, #fetch_spec_slice, and update uses. Keeps consistency with src/**/*.zig guidelines.
119-129: Deinit order: release payloads before freeing arenaFreeing the arena first is brittle if payloads ever hold arena-backed slices. Deinit .git/.alias first, then free arena.
- pub fn deinit(self: *Self) void { - if (self._arena_buffer) |arena| { - self._allocator.free(arena); - } - switch (self.type) { + pub fn deinit(self: *Self) void { + switch (self.type) { .git => |*g| g.deinit(self._allocator), .alias => |*a| a.deinit(self._allocator), else => {}, } + if (self._arena_buffer) |arena| { + self._allocator.free(arena); + } }As per coding guidelines.
155-155: Preallocate enough properties for toJS objectYou add >8 props; bump initial capacity to reduce rehashing.
- var object = jsc.JSValue.createEmptyObject(go, 8); + var object = jsc.JSValue.createEmptyObject(go, 12);
222-224: Stable JS shape: always include “registry”Set “registry” for all specs (true/false) to keep a stable object shape.
- if (self.isRegistry()) { - object.put(go, "registry", .true); - } + object.put(go, "registry", if (self.isRegistry()) .true else .false);
317-331: git+ssh SCP branch: saveSpec should exclude the hashAlign with npm-package-arg: save the input without the fragment.
- .save_spec = raw_spec_slice, + .save_spec = blk: { + const h = bun.strings.lastIndexOfChar(raw_spec, '#'); + break :blk arena.copyString(if (h) |i| raw_spec[0..i] else raw_spec); + },
408-417: git+file Windows drive-letter heuristic: add colon checkAvoid misclassifying single-letter hosts (e.g., a.example) as drives; also require pathname to start with ‘:’.
- if (parts.host_lower.len == 1 and - std.ascii.isAlphabetic(parts.host_lower[0])) + if (parts.host_lower.len == 1 and + std.ascii.isAlphabetic(parts.host_lower[0]) and + (parts.pathname.len > 0 and parts.pathname[0] == ':'))
823-836: Tilde expansion: validate HOME is non-emptyEmpty HOME should error instead of producing a bad path.
- if (bun.getenvZ("HOME")) |home_dir| { + if (bun.getenvZ("HOME")) |home_dir| { + if (home_dir.len == 0) return error.InvalidPath; const path_after_tilde = if (spec_path.len > 3) spec_path[3..] else "";
836-851: Avoid magic substring on “file:” — use spec_pathThe absolute-path check should use the already-decoded pathname, not bun.strings.substring(raw_spec, 5, null).
- } else if (!std.fs.path.isAbsolute(bun.strings.substring(raw_spec, 5, null))) { + } else if (!std.fs.path.isAbsolute(spec_path)) {
957-965: GitAttrs path: normalize to a single leading slashPrevent “//subdir” when value already starts with ‘/’.
- res.subdir = try std.fmt.allocPrint(allocator, "/{s}", .{value}); + const trimmed = bun.strings.trimChar(value, '/'); + res.subdir = try std.fmt.allocPrint(allocator, "/{s}", .{trimmed});
1521-1521: Tighten jsNpa error messagesShort, consistent phrasing.
- return go.throw("Npa.npa takes at least 1 argument", .{}); + return go.throw("Npa.npa requires at least 1 argument", .{}); @@ - return go.throwError(err, "Unexpected error in Npa.npa"); + return go.throwError(err, "Npa.npa failed");Also applies to: 1552-1553
1564-1565: Tighten jsResolve messagesMatch Bun’s concise style.
- return go.throw("Npa.prototype.resolve takes at least 1 argument", .{}); + return go.throw("Npa.prototype.resolve requires at least 1 argument", .{}); @@ - return go.throwError(err, "Unexpected error in Npa.prototype.resolve"); + return go.throwError(err, "Npa.prototype.resolve failed");Also applies to: 1612-1613
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between 03dde552d26959ecb4b4bcacd057b6beff8d4edb and b81bc348da0923beb335f9dc348fc84f7db70675.
📒 Files selected for processing (3)
src/install/dependency.zig(10 hunks)src/install/npm_package_arg.zig(1 hunks)src/resolver/resolve_path.zig(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/resolver/resolve_path.zigsrc/install/dependency.zigsrc/install/npm_package_arg.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
When adding debug logs in Zig, create a scoped logger and log via Bun APIs:
const log = bun.Output.scoped(.${SCOPE}, .hidden);thenlog("...", .{})
src/**/*.zig: Use Zig private fields with the # prefix for encapsulation (e.g., struct { #foo: u32 })
Prefer Decl literals for initialization (e.g., const decl: Decl = .{ .binding = 0, .value = 0 };)
Place @import statements at the bottom of the file (formatter will handle ordering)
src/**/*.zig: In Zig code, manage memory carefully: use appropriate allocators and defer for cleanup
Cache JavaScriptCore class structures in ZigGlobalObject when adding new classes
Files:
src/resolver/resolve_path.zigsrc/install/dependency.zigsrc/install/npm_package_arg.zig
🧠 Learnings (8)
📚 Learning: 2025-10-16T17:32:03.074Z
Learnt from: markovejnovic
PR: oven-sh/bun#23710
File: src/install/PackageManager/PackageManagerOptions.zig:187-193
Timestamp: 2025-10-16T17:32:03.074Z
Learning: In Bun's codebase (particularly in files like src/install/PackageManager/PackageManagerOptions.zig), mixing bun.EnvVar.*.get() and bun.EnvVar.*.platformGet() for environment variable lookups is intentional and safe. The code is protected by compile-time platform checks (Environment.isWindows, etc.), and compilation will fail if the wrong function is used on the wrong platform. This pattern should not be flagged as a consistency issue.
Applied to files:
src/resolver/resolve_path.zig
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Applies to src/**/js_*.zig : Always implement proper cleanup in deinit() and finalize() for JS-exposed types
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Implement the core feature in Zig under its own directory within src/<feature>/
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-10-25T22:53:31.261Z
Learnt from: CR
PR: oven-sh/bun#0
File: src/CLAUDE.md:0-0
Timestamp: 2025-10-25T22:53:31.261Z
Learning: Applies to src/**/*.zig : Use Zig private fields with the # prefix for encapsulation (e.g., struct { #foo: u32 })
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-02T18:25:27.976Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/allocators/allocation_scope.zig:284-314
Timestamp: 2025-09-02T18:25:27.976Z
Learning: In bun's custom Zig implementation, the `#` prefix for private fields is valid syntax and should not be flagged as invalid. The syntax `#fieldname` creates private fields that cannot be accessed from outside the defining struct, and usage like `self.#fieldname` is correct within the same struct. This applies to fields like `#parent`, `#state`, `#allocator`, `#trace`, etc. throughout the codebase.
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-02T17:14:46.924Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/safety/alloc.zig:93-95
Timestamp: 2025-09-02T17:14:46.924Z
Learning: In bun's Zig codebase, they use a custom extension of Zig that supports private field syntax with the `#` prefix (e.g., `#allocator`, `#trace`). This is not standard Zig syntax but is valid in their custom implementation. Fields prefixed with `#` are private fields that cannot be accessed from outside the defining struct.
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-02T18:27:23.279Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/collections/multi_array_list.zig:24-24
Timestamp: 2025-09-02T18:27:23.279Z
Learning: The `#allocator` syntax in bun's custom Zig implementation is valid and does not require quoting with @"#allocator". Private fields using the `#` prefix work correctly throughout the codebase without special quoting syntax.
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-25T18:14:27.731Z
Learnt from: cirospaciari
PR: oven-sh/bun#22842
File: src/bun.js/webcore/ResumableSink.zig:274-276
Timestamp: 2025-09-25T18:14:27.731Z
Learning: In Zig code, private fields are declared and accessed using the `#` prefix. When a field is declared as `#field_name`, it must be accessed as `this.#field_name`, not `this.field_name`. The `#` prefix is part of the private field access syntax and should not be removed.
Applied to files:
src/install/npm_package_arg.zig
🔇 Additional comments (1)
src/install/npm_package_arg.zig (1)
1457-1459: Nice: switched to countLeadingCharGood adoption; simpler and clearer than manual loop.
| if (hosted_git_info.isGitHubShorthand(url["github.com/".len..])) return .github; | ||
| } | ||
|
|
||
| const copy = bun.handleOom(allocator.dupe(u8, dependency)); | ||
| defer allocator.free(copy); | ||
| if (hosted_git_info.HostedGitInfo.fromUrl(allocator, copy) catch null) |info| { | ||
| defer info.deinit(); | ||
| return switch (info.host_provider) { | ||
| .github => .github, | ||
| .bitbucket, .gitlab, .gist, .sourcehut => .git, | ||
| }; | ||
| } |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
DRY the HostedGitInfo probe and provider mapping
The “dupe → fromUrl → defer deinit → switch host_provider” pattern repeats. Extract a small helper to avoid drift and shrink branches.
Example:
@@
- const copy = bun.handleOom(allocator.dupe(u8, dependency));
- defer allocator.free(copy);
- if (hosted_git_info.HostedGitInfo.fromUrl(allocator, copy) catch null) |info| {
- defer info.deinit();
- return switch (info.host_provider) {
- .github => .github,
- .bitbucket, .gitlab, .gist, .sourcehut => .git,
- };
- }
+ if (inferHostedTag(allocator, dependency, false)) |tag| return tag;Add near Tag.infer:
inline fn inferHostedTag(allocator: std.mem.Allocator, dep: []const u8, githubShortcutOnly: bool) ?Tag {
const copy = bun.handleOom(allocator.dupe(u8, dep));
defer allocator.free(copy);
const info = hosted_git_info.HostedGitInfo.fromUrl(allocator, copy) catch null orelse return null;
defer info.deinit();
if (githubShortcutOnly and info.host_provider == .github and info.default_representation != .shortcut)
return .git;
return switch (info.host_provider) { .github => .github, .bitbucket, .gitlab, .gist, .sourcehut => .git };
}Use githubShortcutOnly = true for the git+http(s) branch to preserve your special-case. Based on coding guidelines.
Also applies to: 615-632, 675-683, 703-711, 783-794
b81bc34 to
69b87ee
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (13)
src/resolver/resolve_path.zig (1)
40-48: Code duplication already flagged in previous review.This implementation duplicates the function in
src/paths/Path.zig. The previous review comment provides a consolidation approach to avoid maintenance overhead.src/install/dependency.zig (2)
820-824: UsetoUTF8WithoutReffor efficiency.The current code uses
toUTF8which increments the reference count, requiring an explicitdeinit(). Since the string lifetime is managed by thedefer dependency_str.deref()on Line 822, you can usetoUTF8WithoutRefto avoid the extra reference counting overhead.Apply this diff:
- var as_utf8 = dependency_str.toUTF8(bun.default_allocator); - defer as_utf8.deinit(); + const as_utf8 = dependency_str.toUTF8WithoutRef(bun.default_allocator);
1088-1114: Fallback to empty.githubis problematic (previously flagged).The error and null fallback paths return
.githubwith emptyowner,repo, andcommittishfields. This was previously flagged in past reviews as "leaky" and the suggestion was to degrade to.gitwith parsed repo/committish from the original dependency string.Note: This issue was marked as "✅ Addressed in commit ed993b5" in past reviews, but the code still shows the problematic pattern. Please verify if this was intentionally reverted or if the fix needs to be re-applied.
src/install/npm_package_arg.zig (10)
119-129: Deinit order: deinit payloads before freeing arena.Freeing the arena first can invalidate slices inside type payloads. Switch the order: deinit .git/.alias first, then free arena.
- pub fn deinit(self: *Self) void { - if (self._arena_buffer) |arena| { - self._allocator.free(arena); - } - - switch (self.type) { - .git => |*g| g.deinit(self._allocator), - .alias => |*a| a.deinit(self._allocator), - else => {}, - } - } + pub fn deinit(self: *Self) void { + switch (self.type) { + .git => |*g| g.deinit(self._allocator), + .alias => |*a| a.deinit(self._allocator), + else => {}, + } + if (self._arena_buffer) |arena| { + self._allocator.free(arena); + } + }As per coding guidelines.
33-39: Adopt project-private field convention (#-prefixed).Rename _allocator/_arena_buffer/_fetch_spec_slice to #allocator/#arena_buffer/#fetch_spec_slice for consistency. Mechanical rename within this file.
As per coding guidelines.
155-155: Preallocate more properties for toJS object.You add >8 props; bump capacity to reduce rehashing.
- var object = jsc.JSValue.createEmptyObject(go, 8); + var object = jsc.JSValue.createEmptyObject(go, 12);
222-226: Stable JS shape: always include “registry”.Write "registry": true/false for all specs to keep object shape consistent.
- if (self.isRegistry()) { - object.put(go, "registry", .true); - } + object.put(go, "registry", if (self.isRegistry()) .true else .false);
317-331: git+ssh SCP: saveSpec should omit hash to match npm behavior.For inputs like git+ssh://user@host:repo.git#branch, saveSpec typically excludes the fragment. Calculate saveSpec without the hash.
- const raw_spec_slice = arena.copyString(raw_spec); + const raw_spec_slice = arena.copyString(raw_spec); + // Save spec without hash fragment for parity with npm + const save_no_hash_len = bun.strings.indexOfChar(raw_spec, '#') orelse raw_spec.len; + const save_spec_slice = arena.copyString(raw_spec[0..save_no_hash_len]); const fetch_spec_slice = arena.copyString(scp_result.fragment); @@ - ._fetch_spec_slice = fetch_spec_slice, - .save_spec = raw_spec_slice, + ._fetch_spec_slice = fetch_spec_slice, + .save_spec = save_spec_slice,Also ensure arena_size accounts for the extra save_spec copy:
- var arena_size: usize = rawFieldLength(raw_arg, name, raw_spec); - arena_size += raw_spec.len + scp_result.fragment.len; + var arena_size: usize = rawFieldLength(raw_arg, name, raw_spec); + const save_no_hash_len = bun.strings.indexOfChar(raw_spec, '#') orelse raw_spec.len; + arena_size += raw_spec.len + scp_result.fragment.len + save_no_hash_len;
408-416: git+file Windows drive-letter heuristic: require a following colon.Avoid treating single-letter hosts like a.example as drive letters; verify the original string has "X:" after the host.
- if (parts.host_lower.len == 1 and - std.ascii.isAlphabetic(parts.host_lower[0])) + if (parts.host_lower.len == 1 and + std.ascii.isAlphabetic(parts.host_lower[0]) and + (after_protocol.len > 1 and after_protocol[1] == ':')) {
823-836: HOME must be non-empty for tilde expansion.Guard against empty HOME to avoid constructing invalid paths.
- if (bun.getenvZ("HOME")) |home_dir| { + if (bun.getenvZ("HOME")) |home_dir| { + if (home_dir.len == 0) { + return error.InvalidPath; + } const path_after_tilde = if (spec_path.len > 3) spec_path[3..] else "";
836-849: Avoid magic substring; use decoded spec_path for absoluteness.Rely on spec_path (already decoded) instead of substring(raw_spec, 5, null).
- } else if (!std.fs.path.isAbsolute(bun.strings.substring(raw_spec, 5, null))) { + } else if (!std.fs.path.isAbsolute(spec_path)) {
957-965: Normalize “path:” value to avoid leading “//subdir”.Trim leading slashes in value before prefixing with one slash.
- res.subdir = try std.fmt.allocPrint(allocator, "/{s}", .{value}); + const trimmed = bun.strings.trimChar(value, '/'); + res.subdir = try std.fmt.allocPrint(allocator, "/{s}", .{trimmed});
1520-1521: Tighten JS error messages; align with method names.Short, consistent phrasing per Bun’s style. No behavior change.
- return go.throw("Npa.npa takes at least 1 argument", .{}); + return go.throw("Npa.npa requires at least 1 argument", .{}); @@ - return go.throwError(err, "Unexpected error in Npa.npa"); + return go.throwError(err, "Npa.npa failed"); @@ - return go.throw("Npa.prototype.resolve takes at least 1 argument", .{}); + return go.throw("Npa.prototype.resolve requires at least 1 argument", .{}); @@ - return go.throwError(err, "Unexpected error in Npa.prototype.resolve"); + return go.throwError(err, "Npa.prototype.resolve failed");Also applies to: 1552-1553, 1564-1565, 1612-1613
📜 Review details
Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📥 Commits
Reviewing files that changed from the base of the PR and between b81bc348da0923beb335f9dc348fc84f7db70675 and 5a7ecc591078bda1a35a4e5f6a9a4eabeeed8d1f.
📒 Files selected for processing (4)
src/install/dependency.zig(10 hunks)src/install/npm_package_arg.zig(1 hunks)src/resolver/resolve_path.zig(1 hunks)test/cli/install/npm-package-arg/index.test.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)
**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue
Files:
src/resolver/resolve_path.zigsrc/install/dependency.zigsrc/install/npm_package_arg.zig
src/**/*.zig
📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)
When adding debug logs in Zig, create a scoped logger and log via Bun APIs:
const log = bun.Output.scoped(.${SCOPE}, .hidden);thenlog("...", .{})
src/**/*.zig: Use Zig private fields with the # prefix for encapsulation (e.g., struct { #foo: u32 })
Prefer Decl literals for initialization (e.g., const decl: Decl = .{ .binding = 0, .value = 0 };)
Place @import statements at the bottom of the file (formatter will handle ordering)
src/**/*.zig: In Zig code, manage memory carefully: use appropriate allocators and defer for cleanup
Cache JavaScriptCore class structures in ZigGlobalObject when adding new classes
Files:
src/resolver/resolve_path.zigsrc/install/dependency.zigsrc/install/npm_package_arg.zig
test/**
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
Place all tests under the test/ directory
Files:
test/cli/install/npm-package-arg/index.test.ts
test/cli/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes
Files:
test/cli/install/npm-package-arg/index.test.ts
test/**/*.{js,ts}
📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)
test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable
Files:
test/cli/install/npm-package-arg/index.test.ts
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}: Usebun:testfor files ending with*.test.{ts,js,jsx,tsx,mjs,cjs}
Prefer concurrent tests (test.concurrent/describe.concurrent) over sequential when feasible
Organize tests withdescribeblocks to group related tests
Use utilities likedescribe.each,toMatchSnapshot, and lifecycle hooks (beforeAll,beforeEach,afterEach) and track resources for cleanup
Files:
test/cli/install/npm-package-arg/index.test.ts
test/**/*.{ts,tsx,js,jsx,mjs,cjs}
📄 CodeRabbit inference engine (test/CLAUDE.md)
For large/repetitive strings, use
Buffer.alloc(count, fill).toString()instead of"A".repeat(count)
Files:
test/cli/install/npm-package-arg/index.test.ts
test/**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
test/**/*.test.{ts,tsx}: Test files must live under test/ and end with .test.ts or .test.tsx
In tests, always use port: 0; do not hardcode ports or invent random port functions
Prefer snapshot assertions and use normalizeBunSnapshot for snapshot output in tests
Never write tests that assert absence of crashes (e.g., no "panic" or "uncaught exception") in output
Use tempDir from "harness" for temporary directories; do not use tmpdirSync or fs.mkdtempSync in tests
When spawning processes in tests, assert on stdout before asserting exitCode
Do not use setTimeout in tests; await conditions instead to avoid flakiness
Files:
test/cli/install/npm-package-arg/index.test.ts
test/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Avoid shell commands in tests (e.g., find, grep); use Bun's Glob and built-in tools
Files:
test/cli/install/npm-package-arg/index.test.ts
🧠 Learnings (9)
📚 Learning: 2025-10-16T17:32:03.074Z
Learnt from: markovejnovic
PR: oven-sh/bun#23710
File: src/install/PackageManager/PackageManagerOptions.zig:187-193
Timestamp: 2025-10-16T17:32:03.074Z
Learning: In Bun's codebase (particularly in files like src/install/PackageManager/PackageManagerOptions.zig), mixing bun.EnvVar.*.get() and bun.EnvVar.*.platformGet() for environment variable lookups is intentional and safe. The code is protected by compile-time platform checks (Environment.isWindows, etc.), and compilation will fail if the wrong function is used on the wrong platform. This pattern should not be flagged as a consistency issue.
Applied to files:
src/resolver/resolve_path.zig
📚 Learning: 2025-08-30T00:12:56.803Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/writing-tests.mdc:0-0
Timestamp: 2025-08-30T00:12:56.803Z
Learning: Applies to test/js/third_party/**/*.{js,ts} : Place third-party npm package tests under test/js/third_party/
Applied to files:
test/cli/install/npm-package-arg/index.test.ts
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Applies to src/**/js_*.zig : Always implement proper cleanup in deinit() and finalize() for JS-exposed types
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-08-30T00:11:57.076Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/registering-bun-modules.mdc:0-0
Timestamp: 2025-08-30T00:11:57.076Z
Learning: Implement the core feature in Zig under its own directory within src/<feature>/
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-10-25T22:53:31.261Z
Learnt from: CR
PR: oven-sh/bun#0
File: src/CLAUDE.md:0-0
Timestamp: 2025-10-25T22:53:31.261Z
Learning: Applies to src/**/*.zig : Use Zig private fields with the # prefix for encapsulation (e.g., struct { #foo: u32 })
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-02T18:25:27.976Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/allocators/allocation_scope.zig:284-314
Timestamp: 2025-09-02T18:25:27.976Z
Learning: In bun's custom Zig implementation, the `#` prefix for private fields is valid syntax and should not be flagged as invalid. The syntax `#fieldname` creates private fields that cannot be accessed from outside the defining struct, and usage like `self.#fieldname` is correct within the same struct. This applies to fields like `#parent`, `#state`, `#allocator`, `#trace`, etc. throughout the codebase.
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-02T17:14:46.924Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/safety/alloc.zig:93-95
Timestamp: 2025-09-02T17:14:46.924Z
Learning: In bun's Zig codebase, they use a custom extension of Zig that supports private field syntax with the `#` prefix (e.g., `#allocator`, `#trace`). This is not standard Zig syntax but is valid in their custom implementation. Fields prefixed with `#` are private fields that cannot be accessed from outside the defining struct.
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-02T18:27:23.279Z
Learnt from: taylordotfish
PR: oven-sh/bun#22227
File: src/collections/multi_array_list.zig:24-24
Timestamp: 2025-09-02T18:27:23.279Z
Learning: The `#allocator` syntax in bun's custom Zig implementation is valid and does not require quoting with @"#allocator". Private fields using the `#` prefix work correctly throughout the codebase without special quoting syntax.
Applied to files:
src/install/npm_package_arg.zig
📚 Learning: 2025-09-25T18:14:27.731Z
Learnt from: cirospaciari
PR: oven-sh/bun#22842
File: src/bun.js/webcore/ResumableSink.zig:274-276
Timestamp: 2025-09-25T18:14:27.731Z
Learning: In Zig code, private fields are declared and accessed using the `#` prefix. When a field is declared as `#field_name`, it must be accessed as `this.#field_name`, not `this.field_name`. The `#` prefix is part of the private field access syntax and should not be removed.
Applied to files:
src/install/npm_package_arg.zig
🧬 Code graph analysis (1)
test/cli/install/npm-package-arg/index.test.ts (1)
src/js/internal-for-testing.ts (1)
Npa(215-218)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Format
🔇 Additional comments (4)
src/install/dependency.zig (3)
497-500: LGTM: Allocator setup for hosted git info parsing.The stack-fallback allocator with 1KB buffer is appropriate for the URL parsing operations in the Tag.infer slow paths.
1117-1144: String extraction approach is acceptable.The use of
strings.indexOfto locateowner,repo, andcommittishin the original dependency string is a reasonable approach. While theoretically fragile if these strings appear multiple times in the URL, this is unlikely in practice for typical GitHub URLs. The fallback to empty strings whenindexOfreturns null provides safe default behavior.
1505-1505: LGTM: Import of hosted_git_info module.The import is correctly placed with other module imports near the bottom of the file, following Zig conventions.
test/cli/install/npm-package-arg/index.test.ts (1)
25-27: Windows filter fix looks good.windowsTests now selects only the “windows” cases.
| const path_pair = Self.normalizePath( | ||
| allocator, | ||
| spec_path, | ||
| raw_spec_cleanest, | ||
| where, | ||
| resolved_path, | ||
| ) catch { | ||
| return error.InvalidPath; | ||
| }; | ||
| defer path_pair.deinit(allocator); |
There was a problem hiding this comment.
Don’t swallow OutOfMemory when normalizing paths.
Catching and mapping every error to InvalidPath hides OOM. Propagate OutOfMemory; only map InvalidPath.
- const path_pair = Self.normalizePath(
+ const path_pair = Self.normalizePath(
allocator,
spec_path,
raw_spec_cleanest,
where,
resolved_path,
- ) catch {
- return error.InvalidPath;
- };
+ ) catch |err| switch (err) {
+ error.OutOfMemory => return error.OutOfMemory,
+ error.InvalidPath => return error.InvalidPath,
+ else => return err,
+ };Alternatively, simply:
- const path_pair = Self.normalizePath(allocator, spec_path, raw_spec_cleanest, where, resolved_path) catch { return error.InvalidPath; };
+ const path_pair = try Self.normalizePath(allocator, spec_path, raw_spec_cleanest, where, resolved_path);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const path_pair = Self.normalizePath( | |
| allocator, | |
| spec_path, | |
| raw_spec_cleanest, | |
| where, | |
| resolved_path, | |
| ) catch { | |
| return error.InvalidPath; | |
| }; | |
| defer path_pair.deinit(allocator); | |
| const path_pair = Self.normalizePath( | |
| allocator, | |
| spec_path, | |
| raw_spec_cleanest, | |
| where, | |
| resolved_path, | |
| ) catch |err| switch (err) { | |
| error.OutOfMemory => return error.OutOfMemory, | |
| error.InvalidPath => return error.InvalidPath, | |
| else => return err, | |
| }; | |
| defer path_pair.deinit(allocator); |
🤖 Prompt for AI Agents
In src/install/npm_package_arg.zig around lines 717 to 726, the current catch
maps all errors from Self.normalizePath to error.InvalidPath which hides
OutOfMemory; change the error handling to propagate OutOfMemory and only convert
path-related errors to error.InvalidPath. Specifically, call Self.normalizePath
and handle its error with a conditional/switch: if the error is
allocator.OutOfMemory (or the function's OOM error), return that error upwards;
if it's a path validation error, map to error.InvalidPath; otherwise forward
other unexpected errors. Ensure defer path_pair.deinit(allocator) remains where
path_pair is only used when normalization succeeded.
| const normalizePaths = (spec: any) => { | ||
| spec.fetchSpec = normalizePath(spec.fetchSpec); | ||
| return spec; | ||
| }; |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Normalize saveSpec too for cross-platform parity.
Windows path differences can surface in saveSpec as well. Normalize it alongside fetchSpec to reduce flaky diffs.
-const normalizePaths = (spec: any) => {
- spec.fetchSpec = normalizePath(spec.fetchSpec);
- return spec;
-};
+const normalizePaths = (spec: any) => {
+ spec.fetchSpec = normalizePath(spec.fetchSpec);
+ if ("saveSpec" in spec) spec.saveSpec = normalizePath(spec.saveSpec);
+ return spec;
+};📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const normalizePaths = (spec: any) => { | |
| spec.fetchSpec = normalizePath(spec.fetchSpec); | |
| return spec; | |
| }; | |
| const normalizePaths = (spec: any) => { | |
| spec.fetchSpec = normalizePath(spec.fetchSpec); | |
| if ("saveSpec" in spec) spec.saveSpec = normalizePath(spec.saveSpec); | |
| return spec; | |
| }; |
🤖 Prompt for AI Agents
In test/cli/install/npm-package-arg/index.test.ts around lines 6 to 9, the
normalizePaths helper only normalizes spec.fetchSpec which can leave
platform-specific differences in spec.saveSpec; update the function to also
normalize spec.saveSpec (e.g., set spec.saveSpec = normalizePath(spec.saveSpec)
when present) so both properties are normalized for cross-platform parity and to
avoid flaky diffs.
| describe("npa", () => { | ||
| describe("valid cases", () => { | ||
| describe.each(platformAgnosticTests)("%s", (_, caseSet: object) => { | ||
| it.each(Object.entries(caseSet))("parses %s", (input, expected) => { | ||
| const result = Npa.npa(input as string, "/test/a/b"); | ||
| expect(result).toMatchObject(expectedPatch(expected)); | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| if (process.platform === "win32") { | ||
| describe("windows specific cases", () => { | ||
| describe.each(windowsTests)("%s", (_, caseSet: object) => { | ||
| it.each(Object.entries(caseSet))("parses %s", (input, expected) => { | ||
| const result = Npa.npa(input as string); | ||
| expect(normalizePaths(result)).toMatchObject(expectedPatch(expected)); | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| }); |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider concurrent test execution.
Use describe.concurrent/test.concurrent to speed CI; assertions remain the same.
Also applies to: 50-109
🤖 Prompt for AI Agents
In test/cli/install/npm-package-arg/index.test.ts around lines 28-48 (and
similarly for lines 50-109), the tests run serially; convert the suites and
cases to concurrent execution by replacing describe / describe.each with
describe.concurrent / describe.concurrent.each and replace it.each(...) with
test.concurrent.each(...) (or it.concurrent.each(...)) for each parameterized
test, including the windows-specific block, ensuring any shared mutable state is
safe for concurrent runs.
5a7ecc5 to
cfef333
Compare
What does this PR do?
This PR attempts to port over our usages to
npm_package_arg.zigand friends partially. Instead of doing a massive cut-over, this PR does so incrementally.How did you verify your code works?
CI, hopefully