Skip to content

Fix Windows compilation issues with embedded resources and relative paths - #22365

Merged
Jarred-Sumner merged 14 commits into
mainfrom
claude/fix-compile-windows-yoga-wasm
Sep 5, 2025
Merged

Jarred-Sumner merged 14 commits into
mainfrom
claude/fix-compile-windows-yoga-wasm

Conversation

@robobun

@robobun robobun commented Sep 3, 2025

Copy link
Copy Markdown
Collaborator

Summary

  • Fixed embedded resource path resolution when using Bun.build({compile: true}) API for Windows targets
  • Fixed relative path handling for --outfile parameter in compilation

Details

This PR fixes two regressions introduced after v1.2.19 in the Bun.build({compile}) feature:

1. Embedded Resource Path Issue

When using Bun.build({compile: true}), the module prefix wasn't being set to the target-specific base path, causing embedded resources to fail with "ENOENT: no such file or directory" errors on Windows (e.g., B:/~BUN/root/ paths).

Fix: Ensure the target-specific base path is used as the module prefix in doCompilation, matching the behavior of the CLI build command.

2. PE Metadata with Relative Paths

When using relative paths with --outfile (e.g., --outfile=forward/slash or --outfile=back\\slash), the compilation would fail with "FailedToLoadExecutable" error.

Fix: Ensure relative paths are properly converted to absolute paths before PE metadata operations.

Test Plan

  • Tested Bun.build({compile: true}) with embedded resources
  • Tested relative path handling with nested directories
  • Verified compiled executables run correctly

🤖 Generated with Claude Code

This fixes two regressions introduced after v1.2.19:

1. **yoga.wasm embedding issue on Windows**: The public_path/module_prefix was not
   being set correctly when using Bun.build({compile: true}) API, causing embedded
   resources like yoga.wasm to fail with "ENOENT: no such file or directory" errors.
   The fix ensures the target-specific base path is used in both configureBundler
   and doCompilation.

2. **PE metadata path normalization**: When using relative paths with --outfile
   (e.g., --outfile=forward/slash or --outfile=back\\slash), the compilation would
   fail with "FailedToLoadExecutable" error. The fix ensures relative paths are
   properly converted to absolute paths for PE metadata operations.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@robobun

robobun commented Sep 3, 2025 •

Copy link
Copy Markdown
Collaborator Author
Updated 5:08 PM PT - Sep 4th, 2025

❌ Your commit 61823007 has 2 failures in Build #25085:


🧪   To try this PR locally:

bunx bun-pr 22365

That installs a local version of the PR into your bun-22365 executable, so you can run:

bun-22365 --bun

@github-actions github-actions Bot added the claude label Sep 3, 2025
- Test relative outfile paths are handled correctly
- Test embedded resources use correct module prefix
- Test wasm module compilation

These tests cover the fixes for:
1. Module prefix not being set correctly for compile mode
2. Relative paths not being normalized for PE metadata operations
@robobun
robobun force-pushed the claude/fix-compile-windows-yoga-wasm branch from 9e662d5 to d3ff041 Compare September 3, 2025 08:47
@coderabbitai

coderabbitai Bot commented Sep 3, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Renamed and wrapped a standalone path check to centralize Windows NT-prefix handling; hardened bundler output/public_path and executable path resolution with OS-specific absolute-path semantics; changed cross-device and Windows move semantics to copy-or-move with explicit Win32 calls; and added multiple end-to-end compile/outfile and wasm embedding tests.

Changes

Cohort / File(s) Summary of changes
Standalone path API refactor
src/StandaloneModuleGraph.zig
Renamed isBunStandaloneFilePath → isBunStandaloneFilePathCanonicalized and added a new isBunStandaloneFilePath wrapper that canonicalizes Windows NT prefixes (strings.withoutNTPrefix) on Windows before delegating; non-Windows paths delegate directly.
Bundler path, public_path & executable wiring
src/bundler/bundle_v2.zig
In compile mode, derive public_path from StandaloneModuleGraph.targetBasePublicPath; compute full_outfile_path as absolute (resolve relative to cwd when needed); compute and pass module_prefix and outfile_for_executable into toExecutable; refine OS-specific root_dir/outdir handling and ensure directories exist appropriately.
Move/copy semantics (POSIX & Windows)
src/sys.zig, src/...StandaloneModuleGraph.zig (Windows move logic)
POSIX: when renameat fails with XDEV, perform fallback copy+unlink and return success immediately. Windows: build absolute destination path, convert paths to UTF‑16 with null termination, close source FD, call MoveFileExW with COPY/REPLACE/WRITE_THROUGH flags, map Win32 errors (e.g., directory errors), and apply metadata using the moved destination path. Rework Windows path handling to use absolute paths and explicit Win32 APIs.
Tests — bundler compile, outfile subdirs, wasm
test/bundler/bun-build-compile-wasm.test.ts, test/bundler/bun-build-compile.test.ts, test/regression/issue/compile-outfile-subdirs.test.ts
Add end-to-end tests: WASM embed/execute; multiple compile tests for relative and nested outfile paths and embedded resources; regression suite covering nested outfile subdirs, parent-dir creation, failure when parent is a file, ./.. normalization, and Windows metadata verification.

Suggested reviewers

  • Jarred-Sumner
  • zackradisic

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 135cc13 and 6182300.

📒 Files selected for processing (3)
  • test/bundler/bun-build-compile-wasm.test.ts (1 hunks)
  • test/bundler/bun-build-compile.test.ts (1 hunks)
  • test/regression/issue/compile-outfile-subdirs.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/bundler/bun-build-compile-wasm.test.ts
  • test/bundler/bun-build-compile.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/fix-compile-windows-yoga-wasm

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/bundler/bundle_v2.zig (2)

1914-1925: Outfile absolutization: handle absolute outdir explicitly to avoid double-root joins.

If outdir is already absolute, passing top_level_dir to joinAbsStringBuf is unnecessary and could be brittle. Prefer branching on outdir’s absoluteness.

Apply:

-            var full_outfile_path = if (this.config.outdir.slice().len > 0) brk: {
-                const outdir_slice = this.config.outdir.slice();
-                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
-                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outdir_slice, compile_options.outfile.slice() }, .auto);
-            } else if (std.fs.path.isAbsolute(compile_options.outfile.slice())) 
-                compile_options.outfile.slice()
-            else brk: {
-                // For relative paths, ensure we make them absolute relative to the current working directory
-                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
-                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{compile_options.outfile.slice()}, .auto);
-            };
+            var full_outfile_path = if (this.config.outdir.slice().len > 0) brk: {
+                const outdir_slice = this.config.outdir.slice();
+                const outfile_slice = compile_options.outfile.slice();
+                if (std.fs.path.isAbsolute(outdir_slice)) {
+                    break :brk bun.path.joinAbsStringBuf(outdir_slice, outbuf, &[_][]const u8{ outfile_slice }, .auto);
+                }
+                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
+                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outdir_slice, outfile_slice }, .auto);
+            } else if (std.fs.path.isAbsolute(compile_options.outfile.slice()))
+                compile_options.outfile.slice()
+            else brk: {
+                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
+                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ compile_options.outfile.slice() }, .auto);
+            };

1928-1932: Windows .exe detection should be case-insensitive.

On Windows, “foo.EXE” shouldn’t get “.exe” appended. Use a case-insensitive extension check.

-            if (compile_options.compile_target.os == .windows and !strings.hasSuffixComptime(full_outfile_path, ".exe")) {
+            const ext = std.fs.path.extension(full_outfile_path);
+            if (compile_options.compile_target.os == .windows and !std.ascii.eqlIgnoreCase(ext, ".exe")) {
                 full_outfile_path = std.fmt.allocPrint(bun.default_allocator, "{s}.exe", .{full_outfile_path}) catch |err| bun.handleOom(err);
             } else {
                 full_outfile_path = bun.handleOom(bun.default_allocator.dupe(u8, full_outfile_path));
             }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 f78d197 and 9a51976.

📒 Files selected for processing (1)
  • src/bundler/bundle_v2.zig (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.zig: Format Zig files with zig fmt (bun run zig-format)
In Zig code, manage memory carefully: use the correct allocator and defer for cleanup

**/*.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/bundler/bundle_v2.zig
src/**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)

Implement debug logs in Zig using const log = bun.Output.scoped(.${SCOPE}, false); and invoking log("...", .{})

Files:

  • src/bundler/bundle_v2.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 (2)
src/bundler/bundle_v2.zig (2)

1950-1959: Passing module_prefix from targetBasePublicPath: LGTM.

This aligns compile-mode resource resolution with the target-specific base. Matches the stated Windows fix and avoids relying on user public_path here.


1841-1848: Compile-mode public_path override: returned slice is static. The targetBasePublicPath function returns a compile-time concatenated string literal stored in static memory, so no duplication is required.

- Fixed moveFileZWithHandle in sys.zig to properly handle XDEV errors
  by returning after successfully copying the file across filesystems
- Updated tests to use proper ArrayBuffer handling for WASM modules
- All tests now pass successfully
@robobun
robobun force-pushed the claude/fix-compile-windows-yoga-wasm branch from fe251ac to 80e7317 Compare September 3, 2025 08:59
@robobun

robobun commented Sep 3, 2025

Copy link
Copy Markdown
Collaborator Author

Updated with additional fixes:

  • Fixed moveFileZWithHandle in sys.zig to properly handle XDEV errors when moving files across filesystems
  • Added comprehensive tests for both the embedded resource path fix and relative path handling
  • All tests now pass successfully

The cross-filesystem move bug was causing test failures when temp directories were on different mount points.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
src/sys.zig (1)

3812-3814: Optionally surface unlink failure in debug logs

You’re intentionally ignoring the result of unlinkat(...). Consider logging it in debug builds to aid diagnosing partial moves (dest present, source not removed).

-                _ = unlinkat(from_dir, filename);
+                const rm = unlinkat(from_dir, filename);
+                if (comptime bun.Environment.allow_assert) {
+                    if (rm == .err) {
+                        syslog("unlinkat({s}) after XDEV copy failed: {s}", .{
+                            filename, @tagName(rm.err.getErrno()),
+                        });
+                    }
+                }
                 return;
src/bundler/bundle_v2.zig (3)

1914-1926: Absolute outfile resolution is correct; comment nit

Logic to always produce an absolute path (handling outdir/absolute/relative) looks solid. The inline comment says “current working directory” but the code resolves against FileSystem.top_level_dir. Consider updating the comment for accuracy.

Apply:

-                // For relative paths, ensure we make them absolute relative to the current working directory
+                // For relative paths, resolve against bun.fs.FileSystem.instance.top_level_dir

Additionally, if both outdir and an absolute outfile are provided, confirm intended precedence (current code joins them). If absolute outfile should win, guard for that case.


1928-1932: Handle “.EXE” suffix case-insensitively on Windows

Minor polish: avoid appending “.exe” when the user passes “.EXE”.

-            if (compile_options.compile_target.os == .windows and !strings.hasSuffixComptime(full_outfile_path, ".exe")) {
-                full_outfile_path = std.fmt.allocPrint(bun.default_allocator, "{s}.exe", .{full_outfile_path}) catch |err| bun.handleOom(err);
-            } else {
-                full_outfile_path = bun.handleOom(bun.default_allocator.dupe(u8, full_outfile_path));
-            }
+            if (compile_options.compile_target.os == .windows) {
+                const has_exe = full_outfile_path.len >= 4 and std.ascii.eqlIgnoreCase(
+                    full_outfile_path[full_outfile_path.len - 4 ..],
+                    ".exe",
+                );
+                if (!has_exe) {
+                    full_outfile_path = std.fmt.allocPrint(bun.default_allocator, "{s}.exe", .{ full_outfile_path }) catch |err| bun.handleOom(err);
+                } else {
+                    full_outfile_path = bun.handleOom(bun.default_allocator.dupe(u8, full_outfile_path));
+                }
+            } else {
+                full_outfile_path = bun.handleOom(bun.default_allocator.dupe(u8, full_outfile_path));
+            }

1950-1952: Pass target-specific module_prefix to toExecutable — LGTM

Using StandaloneModuleGraph.targetBasePublicPath here matches the bundling decision and resolves Windows embedded resource paths.

Consider extracting a small helper (e.g., compileModulePrefix(os)) and reusing it both here and in configureBundler to avoid drift.

Also applies to: 1958-1958

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 fe251ac5696bd3261ea9cf7994f6dfa2f84360d6 and 6aabe1a8c6c5ccb6d75d028b42f557e82898575b.

📒 Files selected for processing (4)
  • src/bundler/bundle_v2.zig (3 hunks)
  • src/sys.zig (1 hunks)
  • test/bundler/bun-build-compile-wasm.test.ts (1 hunks)
  • test/bundler/bun-build-compile.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/bundler/bun-build-compile-wasm.test.ts
  • test/bundler/bun-build-compile.test.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.zig: Format Zig files with zig fmt (bun run zig-format)
In Zig code, manage memory carefully: use the correct allocator and defer for cleanup

**/*.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/sys.zig
  • src/bundler/bundle_v2.zig
src/**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)

Implement debug logs in Zig using const log = bun.Output.scoped(.${SCOPE}, false); and invoking log("...", .{})

Files:

  • src/sys.zig
  • src/bundler/bundle_v2.zig
🧠 Learnings (1)
📓 Common learnings
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:38.001Z
Learning: Run bun run zig:check-all when making platform-specific changes to ensure cross-platform compilation
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/dev/bundle.test.ts : bundle.test.ts should contain DevServer-specific bundling tests
🔇 Additional comments (3)
src/sys.zig (2)

3810-3814: Correct early return after XDEV fallback

Adding return; after successful copy+unlink prevents accidental propagation of the original renameat error and fixes cross-filesystem moves with an open handle. LGTM.


3799-3819: Run cross-platform Zig checks for filesystem changes
Run bun run zig:check-all in your local environment to catch any platform-specific regressions and confirm there are no errors. Then verify consistency by searching for all call sites of moveFileZWithHandle and moveFileZSlowMaybe (e.g.,

rg -nP '\bmoveFileZWithHandle\s*\(' -C2
rg -nP '\bmoveFileZSlowMaybe\s*\(' -C2
```)

</blockquote></details>
<details>
<summary>src/bundler/bundle_v2.zig (1)</summary><blockquote>

`1841-1849`: **Verify Zig compilation & new tests**

Test files `test/bundler/bun-build-compile.test.ts` and `test/bundler/bun-build-compile-wasm.test.ts` are present; ensure `bun run zig:check-all` succeeds on all target platforms and that these new tests pass in CI, since local `bun` invocation failed.

</blockquote></details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

When the outfile path becomes absolute (e.g., /workspace/bun/subdir/test.exe),
we were incorrectly trying to create that absolute path relative to cwd,
which would fail or create the wrong directory structure.

This fix properly handles:
- Absolute directories by opening them directly with openDirAbsolute
- Relative directories by opening them relative to cwd
- Creating directories if they don't exist

This resolves the PE metadata issue when using --outfile with subdirectories.
@robobun
robobun force-pushed the claude/fix-compile-windows-yoga-wasm branch from 6aabe1a to 1046b46 Compare September 3, 2025 09:23
@robobun

robobun commented Sep 3, 2025

Copy link
Copy Markdown
Collaborator Author

Fixed the PE metadata issue with subdirectories!

The problem was that when full_outfile_path was made absolute (e.g., /workspace/bun/subdir/test.exe), we were incorrectly trying to create that absolute path relative to cwd using makeOpenPath. This would either fail or create the wrong directory structure.

The fix properly handles:

  • Absolute directories by opening them directly with openDirAbsolute
  • Relative directories by opening them relative to cwd
  • Creating directories if they don't exist

Now --outfile=subdir/test.exe works correctly with Windows metadata operations.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/bundler/bundle_v2.zig (1)

1914-1936: Fix absolute outdir semantics, Windows .EXE check, and prevent leak on early-return

  • If outdir is absolute, joining with top_level_dir is ambiguous; join from outdir directly.
  • Use case-insensitive check for “.exe” on Windows.
  • full_outfile_path is always heap-allocated but can leak on early failures before assignment to dest_path; add deferred free and transfer ownership on success.

Apply:

@@
-            // Always get an absolute path for the outfile to ensure it works correctly with PE metadata operations
-            var full_outfile_path = if (this.config.outdir.slice().len > 0) brk: {
-                const outdir_slice = this.config.outdir.slice();
-                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
-                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outdir_slice, compile_options.outfile.slice() }, .auto);
-            } else if (std.fs.path.isAbsolute(compile_options.outfile.slice())) 
-                compile_options.outfile.slice()
-            else brk: {
-                // For relative paths, ensure we make them absolute relative to the current working directory
-                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
-                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{compile_options.outfile.slice()}, .auto);
-            };
-
-            // Add .exe extension for Windows targets if not already present
-            if (compile_options.compile_target.os == .windows and !strings.hasSuffixComptime(full_outfile_path, ".exe")) {
-                full_outfile_path = std.fmt.allocPrint(bun.default_allocator, "{s}.exe", .{full_outfile_path}) catch |err| bun.handleOom(err);
-            } else {
-                full_outfile_path = bun.handleOom(bun.default_allocator.dupe(u8, full_outfile_path));
-            }
+            // Always compute an absolute path for outfile (handles absolute/relative outdir).
+            const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
+            const outdir_slice = this.config.outdir.slice();
+            const outfile_slice = compile_options.outfile.slice();
+            const full_outfile_path_tmp = if (outdir_slice.len > 0) brk: {
+                if (std.fs.path.isAbsolute(outdir_slice)) {
+                    break :brk bun.path.joinAbsStringBuf(outdir_slice, outbuf, &[_][]const u8{ outfile_slice }, .auto);
+                } else {
+                    break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outdir_slice, outfile_slice }, .auto);
+                }
+            } else if (std.fs.path.isAbsolute(outfile_slice))
+                outfile_slice
+            else
+                bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outfile_slice }, .auto);
+
+            // Own the buffer and normalize Windows extension
+            var full_outfile_path = blk: {
+                if (compile_options.compile_target.os == .windows) {
+                    const ext = std.fs.path.extension(full_outfile_path_tmp);
+                    if (!std.ascii.eqlIgnoreCase(ext, ".exe")) {
+                        break :blk std.fmt.allocPrint(bun.default_allocator, "{s}.exe", .{ full_outfile_path_tmp }) catch |err| bun.handleOom(err);
+                    }
+                }
+                break :blk bun.handleOom(bun.default_allocator.dupe(u8, full_outfile_path_tmp));
+            };
+            var path_transferred = false;
+            defer if (!path_transferred) bun.default_allocator.free(full_outfile_path);
@@
-            if (result == .success) {
-                output_file.dest_path = full_outfile_path;
-                output_file.is_executable = true;
-            }
+            if (result == .success) {
+                output_file.dest_path = full_outfile_path;
+                path_transferred = true; // prevent leak; ownership moved to output_file
+                output_file.is_executable = true;
+            }

Also applies to: 2008-2011

🧹 Nitpick comments (2)
src/bundler/bundle_v2.zig (2)

1937-1953: Root directory open logic is solid; minor nit: tighten error text

Messages “Failed to open output directory …” can mention whether path was absolute vs relative to help triage. Optional.


1960-1969: Using targetBasePublicPath as module_prefix in doCompilation is the right fix

This aligns embedded resource lookup with CLI behavior and fixes Windows ENOENT for resources.

Consider a debug log (hidden scope) to print module_prefix and full_outfile_path when Environment.isDebug to ease future regressions:

const log = bun.Output.scoped(.CompileOutfile, .hidden);
log("compile: module_prefix={s} outfile={s}", .{ module_prefix, full_outfile_path });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 6aabe1a8c6c5ccb6d75d028b42f557e82898575b and 1046b46.

📒 Files selected for processing (2)
  • src/StandaloneModuleGraph.zig (1 hunks)
  • src/bundler/bundle_v2.zig (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/StandaloneModuleGraph.zig
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.zig: Format Zig files with zig fmt (bun run zig-format)
In Zig code, manage memory carefully: use the correct allocator and defer for cleanup

**/*.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/bundler/bundle_v2.zig
src/**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)

Implement debug logs in Zig using const log = bun.Output.scoped(.${SCOPE}, false); and invoking log("...", .{})

Files:

  • src/bundler/bundle_v2.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/bundler/bundle_v2.zig (1)

1840-1848: Compile-mode public_path override looks correct and aligns CLI/JS flows

Setting a target-based base public path during configureBundler for compile mode matches the PR intent and should fix embedded-resource lookups on Windows.

Please confirm StandaloneModuleGraph.targetBasePublicPath returns a stable slice with a trailing slash for all targets, and that its lifetime outlives the bundling/compilation phase. If it’s allocator-backed, we should store an owned copy.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/bundler/bundle_v2.zig (2)

1927-1933: Windows .exe check should be case-insensitive to avoid “.EXE.exe”.

Guard against uppercase “.EXE” (and variants) to prevent double extensions.

-            if (compile_options.compile_target.os == .windows and !strings.hasSuffixComptime(full_outfile_path, ".exe")) {
-                full_outfile_path = std.fmt.allocPrint(bun.default_allocator, "{s}.exe", .{full_outfile_path}) catch |err| bun.handleOom(err);
-            } else {
-                full_outfile_path = bun.handleOom(bun.default_allocator.dupe(u8, full_outfile_path));
-            }
+            if (compile_options.compile_target.os == .windows) {
+                const ext = std.fs.path.extension(full_outfile_path);
+                if (!std.ascii.eqlIgnoreCase(ext, ".exe")) {
+                    full_outfile_path = std.fmt.allocPrint(bun.default_allocator, "{s}.exe", .{ full_outfile_path }) catch |err| bun.handleOom(err);
+                } else {
+                    full_outfile_path = bun.handleOom(bun.default_allocator.dupe(u8, full_outfile_path));
+                }
+            } else {
+                full_outfile_path = bun.handleOom(bun.default_allocator.dupe(u8, full_outfile_path));
+            }

1937-1953: Tighten error handling when creating absolute output directory.

Currently all errors from makeDirAbsolute are swallowed. Only ignore PathAlreadyExists; surface others.

-            else if (std.fs.path.isAbsolute(dirname))
-                // If dirname is absolute, open it directly
-                std.fs.openDirAbsolute(dirname, .{}) catch brk: {
-                    // Try to create it if it doesn't exist
-                    std.fs.makeDirAbsolute(dirname) catch {};
-                    break :brk std.fs.openDirAbsolute(dirname, .{}) catch |err2| {
-                        return bun.StandaloneModuleGraph.CompileResult.fail(bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "Failed to open output directory {s}: {s}", .{ dirname, @errorName(err2) })));
-                    };
-                }
+            else if (std.fs.path.isAbsolute(dirname))
+                // If dirname is absolute, open it directly
+                std.fs.openDirAbsolute(dirname, .{}) catch brk: {
+                    // Try to create it if it doesn't exist
+                    std.fs.makeDirAbsolute(dirname) catch |e| switch (e) {
+                        error.PathAlreadyExists => {},
+                        else => {
+                            return bun.StandaloneModuleGraph.CompileResult.fail(
+                                bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "Failed to create output directory {s}: {s}", .{ dirname, @errorName(e) })),
+                            );
+                        },
+                    };
+                    break :brk std.fs.openDirAbsolute(dirname, .{}) catch |err2| {
+                        return bun.StandaloneModuleGraph.CompileResult.fail(bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "Failed to open output directory {s}: {s}", .{ dirname, @errorName(err2) })));
+                    };
+                }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 1046b46 and d235abca369d67adec96c274a9fbe924d5d10b4e.

📒 Files selected for processing (3)
  • src/bundler/bundle_v2.zig (3 hunks)
  • test/bundler/bun-build-compile-wasm.test.ts (1 hunks)
  • test/bundler/bun-build-compile.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/bundler/bun-build-compile.test.ts
  • test/bundler/bun-build-compile-wasm.test.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.zig: Format Zig files with zig fmt (bun run zig-format)
In Zig code, manage memory carefully: use the correct allocator and defer for cleanup

**/*.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/bundler/bundle_v2.zig
src/**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)

Implement debug logs in Zig using const log = bun.Output.scoped(.${SCOPE}, false); and invoking log("...", .{})

Files:

  • src/bundler/bundle_v2.zig
🔇 Additional comments (2)
src/bundler/bundle_v2.zig (2)

1841-1849: Compile public_path override makes sense; confirm string ownership.

Setting a target-derived base public path for compile mode aligns CLI and programmatic flows. Please verify that StandaloneModuleGraph.targetBasePublicPath(...) returns a string with a safe lifetime for transpiler.options.public_path. If not guaranteed, dupe it into the provided allocator.

Optional fix:

-                const base_public_path = bun.StandaloneModuleGraph.targetBasePublicPath(compile_opts.compile_target.os, "root/");
-                transpiler.options.public_path = base_public_path;
+                const base_public_path = bun.StandaloneModuleGraph.targetBasePublicPath(compile_opts.compile_target.os, "root/");
+                transpiler.options.public_path = bun.handleOom(alloc.dupe(u8, base_public_path));

1960-1970: Using target-based module_prefix in toExecutable is correct.

This should fix embedded resource lookups on Windows and align CLI/compile behavior.

Comment thread src/bundler/bundle_v2.zig Resolved
Use std.fs.cwd().makeOpenPath() which correctly handles both
absolute and relative paths, instead of trying to detect and
handle them separately. This is the standard pattern used
throughout the Bun codebase.
@robobun
robobun force-pushed the claude/fix-compile-windows-yoga-wasm branch from d235abc to 341bc0e Compare September 3, 2025 09:36
@robobun
robobun force-pushed the claude/fix-compile-windows-yoga-wasm branch from ab3a31d to 7fcaaad Compare September 3, 2025 09:51

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/bundler/bundle_v2.zig (1)

1914-1925: Outfile resolution: absolute must take precedence even when outdir is set.

Current order can mis-handle an absolute outfile if outdir is non-empty. Reorder to resolve absolutes first, then outdir, then cwd. (Matches prior feedback.)

Apply:

-            var full_outfile_path = if (this.config.outdir.slice().len > 0) brk: {
-                const outdir_slice = this.config.outdir.slice();
-                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
-                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outdir_slice, compile_options.outfile.slice() }, .auto);
-            } else if (std.fs.path.isAbsolute(compile_options.outfile.slice()))
-                compile_options.outfile.slice()
-            else brk: {
-                // For relative paths, ensure we make them absolute relative to the current working directory
-                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
-                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{compile_options.outfile.slice()}, .auto);
-            };
+            var full_outfile_path = blk: {
+                const outfile = compile_options.outfile.slice();
+                if (std.fs.path.isAbsolute(outfile)) break :blk outfile;
+                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
+                if (this.config.outdir.slice().len > 0) {
+                    const outdir_slice = this.config.outdir.slice();
+                    break :blk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outdir_slice, outfile }, .auto);
+                }
+                // Relative: resolve against cwd/top_level_dir
+                break :blk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outfile }, .auto);
+            };
🧹 Nitpick comments (2)
src/StandaloneModuleGraph.zig (2)

985-994: Basename-only move is right; downgrade noisy warnings to debug logs.

Use debug-scoped logging here to avoid user-facing noise in normal runs.

Apply:

-                bun.Output.warn("moveOpenedFileAtLoose: outfile=\"{s}\", basename=\"{s}\"", .{ outfile, basename_only });
+                Output.debugWarn("moveOpenedFileAtLoose: outfile=\"{s}\", basename=\"{s}\"", .{ outfile, basename_only });

Optionally declare a scoped logger once and use it:

const logStandalone = Output.scoped(.StandaloneModuleGraph, .hidden);

and then:

-                bun.Output.warn("moveOpenedFileAtLoose: outfile=\"{s}\", basename=\"{s}\"", .{ outfile, basename_only });
+                logStandalone("moveOpenedFileAtLoose: outfile=\"{s}\", basename=\"{s}\"", .{ outfile, basename_only });

1008-1048: Avoid setting Windows metadata twice (inject() already does it).

We now set PE metadata inside inject() (Lines 840–854) and again after move here. That doubles work and increases risk of inconsistencies. Pick one. Recommend keeping the post-move path-based call (this block) and removing the earlier inject-time call.

Apply (remove earlier block in inject):

-        // Set Windows icon and/or metadata if any options are provided (single operation)
-        if (Environment.isWindows and (inject_options.icon != null or
-            inject_options.title != null or
-            inject_options.publisher != null or
-            inject_options.version != null or
-            inject_options.description != null or
-            inject_options.copyright != null))
-        {
-            var zname_buf: bun.OSPathBuffer = undefined;
-            const zname_w = bun.strings.toWPathNormalized(&zname_buf, zname) catch |err| {
-                Output.err(err, "failed to resolve executable path", .{});
-                cleanup(zname, cloned_executable_fd);
-                return bun.invalid_fd;
-            };
-
-            // Single call to set all Windows metadata at once
-            bun.windows.rescle.setWindowsMetadata(
-                zname_w.ptr,
-                inject_options.icon,
-                inject_options.title,
-                inject_options.publisher,
-                inject_options.version,
-                inject_options.description,
-                inject_options.copyright,
-            ) catch |err| {
-                Output.err(err, "failed to set Windows metadata on executable", .{});
-                cleanup(zname, cloned_executable_fd);
-                return bun.invalid_fd;
-            };
-        }

Also switch this block’s warn to debug:

-                    bun.Output.warn("PE metadata: dir_path=\"{s}\", outfile=\"{s}\", full_path=\"{s}\"", .{ dir_path, outfile, full_path_str });
+                    Output.debugWarn("PE metadata: dir_path=\"{s}\", outfile=\"{s}\", full_path=\"{s}\"", .{ dir_path, outfile, full_path_str });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 ab3a31d and d18dbc4fe791b597ce504a4e0894f0c4a60188c3.

📒 Files selected for processing (4)
  • src/StandaloneModuleGraph.zig (2 hunks)
  • src/bundler/bundle_v2.zig (3 hunks)
  • test/bundler/bun-build-compile-wasm.test.ts (1 hunks)
  • test/bundler/bun-build-compile.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/bundler/bun-build-compile.test.ts
  • test/bundler/bun-build-compile-wasm.test.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.zig: Format Zig files with zig fmt (bun run zig-format)
In Zig code, manage memory carefully: use the correct allocator and defer for cleanup

**/*.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/StandaloneModuleGraph.zig
  • src/bundler/bundle_v2.zig
src/**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)

Implement debug logs in Zig using const log = bun.Output.scoped(.${SCOPE}, false); and invoking log("...", .{})

Files:

  • src/StandaloneModuleGraph.zig
  • src/bundler/bundle_v2.zig
🔇 Additional comments (1)
src/bundler/bundle_v2.zig (1)

1841-1848: Compile-mode public_path to target base path: LGTM.

This aligns embedded resources with the correct module prefix.

- Fix PE metadata/icon failing when --outfile contains subdirectories
- Use MoveFileExW with absolute paths instead of moveOpenedFileAtLoose
- Fix Bun.build() API to respect subdirectories in compile.outfile
- Pass full relative path on Windows instead of just basename

Fixes compile failures when using --outfile with nested paths like:
  bun build --compile app.js --outfile=dist/bin/app.exe --windows-icon=icon.ico

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@Jarred-Sumner
Jarred-Sumner force-pushed the claude/fix-compile-windows-yoga-wasm branch from d18dbc4 to 0752484 Compare September 3, 2025 10:27
- Use root_dir.makeOpenPath() on POSIX instead of std.fs.cwd().makeOpenPath()
- Use bun.makePath(root_dir, dirname) on Windows instead of std.fs.cwd().makePath()
- This avoids using the banned std.fs.cwd() function

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/bundler/bundle_v2.zig (1)

1914-1925: Absolute outfile should take precedence even when outdir is set.

This reintroduces the earlier join-outdir-first behavior; absolute paths may be incorrectly joined under outdir. Prefer: if outfile is absolute, use it; else resolve against outdir (if provided) or cwd.

-            var full_outfile_path = if (this.config.outdir.slice().len > 0) brk: {
-                const outdir_slice = this.config.outdir.slice();
-                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
-                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outdir_slice, compile_options.outfile.slice() }, .auto);
-            } else if (std.fs.path.isAbsolute(compile_options.outfile.slice()))
-                compile_options.outfile.slice()
-            else brk: {
-                // For relative paths, ensure we make them absolute relative to the current working directory
-                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
-                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{compile_options.outfile.slice()}, .auto);
-            };
+            var full_outfile_path = blk: {
+                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
+                const outfile = compile_options.outfile.slice();
+                if (std.fs.path.isAbsolute(outfile)) break :blk outfile;
+                if (this.config.outdir.slice().len > 0) {
+                    const outdir_slice = this.config.outdir.slice();
+                    break :blk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outdir_slice, outfile }, .auto);
+                }
+                break :blk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outfile }, .auto);
+            };
🧹 Nitpick comments (4)
src/StandaloneModuleGraph.zig (2)

1002-1012: Drop manual null-termination; toWPathNormalized returns [:0] already.

The extra sentinel writes are redundant and risk off-by-one if the buffer is exactly full. Pass the [:0] ptrs directly.

-            var temp_buf_w: bun.OSPathBuffer = undefined;
-            var dest_buf_w: bun.OSPathBuffer = undefined;
-            const temp_w = bun.strings.toWPathNormalized(&temp_buf_w, temp_path);
-            const dest_w = bun.strings.toWPathNormalized(&dest_buf_w, dest_path);
-
-            // Ensure null termination
-            const temp_buf_u16 = bun.reinterpretSlice(u16, &temp_buf_w);
-            const dest_buf_u16 = bun.reinterpretSlice(u16, &dest_buf_w);
-            temp_buf_u16[temp_w.len] = 0;
-            dest_buf_u16[dest_w.len] = 0;
+            var temp_buf_w: bun.OSPathBuffer = undefined;
+            var dest_buf_w: bun.OSPathBuffer = undefined;
+            const temp_w: [:0]const u16 = bun.strings.toWPathNormalized(&temp_buf_w, temp_path);
+            const dest_w: [:0]const u16 = bun.strings.toWPathNormalized(&dest_buf_w, dest_path);

1017-1029: Retry on PATH_NOT_FOUND by creating parent dir, then MoveFileExW again (Windows).

If parent dirs are missing (e.g., when toExecutable is called outside bundle_v2’s pre-create), MoveFileExW returns ERROR_PATH_NOT_FOUND. A targeted retry that creates dirname prevents false negatives.

-            if (bun.windows.kernel32.MoveFileExW(temp_buf_u16[0..temp_w.len :0].ptr, dest_buf_u16[0..dest_w.len :0].ptr, bun.windows.MOVEFILE_COPY_ALLOWED | bun.windows.MOVEFILE_REPLACE_EXISTING | bun.windows.MOVEFILE_WRITE_THROUGH) == bun.windows.FALSE) {
+            if (bun.windows.kernel32.MoveFileExW(temp_w.ptr, dest_w.ptr,
+                  bun.windows.MOVEFILE_COPY_ALLOWED | bun.windows.MOVEFILE_REPLACE_EXISTING | bun.windows.MOVEFILE_WRITE_THROUGH) == bun.windows.FALSE) {
                 const err = bun.windows.Win32Error.get();
+                if (err == .PATH_NOT_FOUND) {
+                    if (std.fs.path.dirname(dest_path)) |dir| {
+                        _ = std.fs.cwd().makePath(dir) catch {};
+                        if (bun.windows.kernel32.MoveFileExW(temp_w.ptr, dest_w.ptr,
+                              bun.windows.MOVEFILE_COPY_ALLOWED | bun.windows.MOVEFILE_REPLACE_EXISTING | bun.windows.MOVEFILE_WRITE_THROUGH) != bun.windows.FALSE) {
+                            // success after mkdir
+                        } else {
+                            // re-fetch error below
+                        }
+                    }
+                }
                 if (err.toSystemErrno()) |sys_err| {
test/regression/issue/compile-outfile-subdirs.test.ts (2)

33-42: Assert the child process exit code when running the produced binary.

Add an exit-code assertion to align with test guidelines.

-    const exeOutput = await exe.stdout.text();
+    const [exeOutput, code] = await Promise.all([exe.stdout.text(), exe.exited]);
+    expect(code).toBe(0);

146-168: Make the error assertion resilient across platforms.

“notdir” is OK, but on some Windows errors you may get “access denied” or “path not found” depending on timing. Consider checking for either NotDir or a more general message stating parent exists and isn’t a directory.

Example:

-    expect(stderr.toLowerCase()).toContain("notdir");
+    expect(stderr.toLowerCase()).toMatch(/notdir|is a directory|path not found/);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 d18dbc4fe791b597ce504a4e0894f0c4a60188c3 and 0328ff9a6962779010817532e5d0c84460fce215.

📒 Files selected for processing (5)
  • src/StandaloneModuleGraph.zig (2 hunks)
  • src/bundler/bundle_v2.zig (3 hunks)
  • test/bundler/bun-build-compile-wasm.test.ts (1 hunks)
  • test/bundler/bun-build-compile.test.ts (1 hunks)
  • test/regression/issue/compile-outfile-subdirs.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/bundler/bun-build-compile.test.ts
  • test/bundler/bun-build-compile-wasm.test.ts
🧰 Additional context used
📓 Path-based instructions (10)
**/*.zig

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.zig: Format Zig files with zig fmt (bun run zig-format)
In Zig code, manage memory carefully: use the correct allocator and defer for cleanup

**/*.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/bundler/bundle_v2.zig
  • src/StandaloneModuleGraph.zig
src/**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)

Implement debug logs in Zig using const log = bun.Output.scoped(.${SCOPE}, false); and invoking log("...", .{})

Files:

  • src/bundler/bundle_v2.zig
  • src/StandaloneModuleGraph.zig
test/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

test/**/*.test.{ts,tsx}: Place tests in test/ and ensure filenames end with .test.ts or .test.tsx
Always use port: 0 in tests; never hardcode port numbers or use custom random-port functions
Prefer snapshot tests using normalizeBunSnapshot(...).toMatchInlineSnapshot(...) over exact string comparisons
Never write tests that assert absence of crashes (e.g., no 'panic' or 'uncaught exception' in output)
Avoid shell commands like find/grep in tests; use Bun.Glob and built-in tools instead

Files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
test/regression/issue/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Create regression tests under test/regression/issue/ (one per bug fix)

Files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Format JavaScript/TypeScript with Prettier (bun run prettier)

Files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
test/**/*.test.ts

📄 CodeRabbit inference engine (test/CLAUDE.md)

test/**/*.test.ts: Use bun:test in files that end in *.test.ts
Prefer async/await over callbacks in tests
For single-callback flows in tests, use Promise.withResolvers()
Do not set timeouts on tests; rely on Bun’s built-in timeouts
Use tempDirWithFiles from harness to create temporary directories/files in tests
Organize tests with describe blocks
Always assert exit codes and error scenarios in tests (e.g., proc.exited, expect(...).not.toBe(0), toThrow())
Use describe.each for parameterized tests; toMatchSnapshot for snapshots; and beforeAll/afterEach/beforeEach for setup/teardown
Avoid flaky tests: never wait for arbitrary time; wait for conditions to be met

Files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
test/{**/*.test.ts,**/*-fixture.ts}

📄 CodeRabbit inference engine (test/CLAUDE.md)

test/{**/*.test.ts,**/*-fixture.ts}: When spawning Bun processes, use bunExe() and bunEnv from harness
Use using or await using for Bun APIs (e.g., Bun.spawn, Bun.listen, Bun.connect, Bun.serve) to ensure cleanup
Never hardcode port numbers; use port: 0 to get a random port
Use Buffer.alloc(count, fill).toString() instead of "A".repeat(count) for large/repetitive strings
Import testing utilities from harness (bunExe, bunEnv, tempDirWithFiles, tmpdirSync, isMacOS, isWindows, isPosix, gcTick, withoutAggressiveGC)

Files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
test/regression/issue/**

📄 CodeRabbit inference engine (test/CLAUDE.md)

Place regression tests under /test/regression/issue/ using the related issue number

Files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
test/**

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

Place all tests under the test/ directory

Files:

  • test/regression/issue/compile-outfile-subdirs.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/regression/issue/compile-outfile-subdirs.test.ts
🧠 Learnings (11)
📚 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/bun/**/*.{js,ts} : Place Bun API tests under test/js/bun/, separated by category (e.g., test/js/bun/glob/)

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
📚 Learning: 2025-08-30T00:05:38.001Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:38.001Z
Learning: Applies to test/js/bun/**/*.test.{ts,tsx} : Put Bun-specific API tests under test/js/bun/

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
📚 Learning: 2025-08-30T00:05:38.001Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:38.001Z
Learning: Applies to test/regression/issue/**/*.test.{ts,tsx} : Create regression tests under test/regression/issue/ (one per bug fix)

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.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/cli/**/*.{js,ts} : Place CLI command tests (e.g., bun install, bun init) under test/cli/

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.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/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
📚 Learning: 2025-08-30T00:07:13.641Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.641Z
Learning: Applies to test/{**/*.test.ts,**/*-fixture.ts} : When spawning Bun processes, use bunExe() and bunEnv from harness

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
📚 Learning: 2025-08-30T00:05:38.001Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:38.001Z
Learning: Applies to test/bundler/**/*.test.{ts,tsx} : Put bundler and transpiler tests under test/bundler/

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
📚 Learning: 2025-08-30T00:05:38.001Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-08-30T00:05:38.001Z
Learning: Applies to test/cli/**/*.test.{ts,tsx} : Put CLI command tests under test/cli/

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
📚 Learning: 2025-08-30T00:07:13.641Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.641Z
Learning: Applies to test/{test/js/bun/**,test/js/node/**} : Place unit tests by module under /test/js/bun/ and /test/js/node/

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
📚 Learning: 2025-08-30T00:07:13.641Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-08-30T00:07:13.641Z
Learning: Applies to test/**/*.test.ts : Use tempDirWithFiles from harness to create temporary directories/files in tests

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.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/regression/issue/compile-outfile-subdirs.test.ts
🧬 Code graph analysis (1)
test/regression/issue/compile-outfile-subdirs.test.ts (1)
test/harness.ts (1)
  • tempDirWithFiles (258-265)
🔇 Additional comments (7)
src/StandaloneModuleGraph.zig (2)

1039-1042: LGTM: Use moved path for PE resource edits.

Switching metadata edits to the final dest path removes the need for a separate full_path derivation and fixes relative-path mishandling.


989-1000: Drop the heap-allocation concern; joinAbsString uses a thread-local static buffer, not the heap. There’s no leak here. If you need an isolated buffer, you may opt into joinAbsStringBuf with a local bun.PathBuffer, but it’s purely optional. Instead, on Windows assert that outfile is absolute (e.g. std.debug.assert(std.fs.path.isAbsolute(outfile));) to satisfy MoveFileExW, and use the bundler’s root_dir rather than cwd if you intend to resolve paths against the project root.

Likely an incorrect or invalid review comment.

test/regression/issue/compile-outfile-subdirs.test.ts (1)

222-261: LGTM: API compile + metadata with subdirectories.

Uses bunEnv/bunExe, tempDirWithFiles, and asserts output existence and version fields; Windows-gated. Looks good.

src/bundler/bundle_v2.zig (4)

1841-1849: Setting compile-mode public_path to target base is correct.

This isolates embedded assets under the platform-scoped prefix and fixes yoga.wasm lookups. Good change.


1944-1958: Directory handling split by OS is sound; minor note on consistency.

POSIX uses makeOpenPath with root_dir; Windows uses makePath with cwd. This matches later Windows move-by-absolute-path logic, but it means root_dir is ignored on Windows. Confirm no non-CLI callers rely on root_dir on Windows.


1960-1962: LGTM: module_prefix derived from target base.

Ensures embedded asset names align with the compile target’s base path ("root/").


1969-1970: LGTM: Pass module_prefix and normalized outfile to toExecutable.

Matches StandaloneModuleGraph expectations and the new Windows path flow.

@Jarred-Sumner
Jarred-Sumner force-pushed the claude/fix-compile-windows-yoga-wasm branch from 0328ff9 to fb9b15e Compare September 3, 2025 10:40
- Replace tempDirWithFiles with tempDir
- Wrap dir with String() when passing to functions
- Ensures proper automatic cleanup of test directories
@Jarred-Sumner
Jarred-Sumner force-pushed the claude/fix-compile-windows-yoga-wasm branch from 1df9864 to f07ec90 Compare September 3, 2025 10:42
- Remove 'target: bun-windows-x64' from compile tests
- Use test.if(isWindows) to skip tests on non-Windows platforms
- Let Bun.build() auto-detect the target platform
@robobun
robobun force-pushed the claude/fix-compile-windows-yoga-wasm branch from afe20d2 to 135cc13 Compare September 4, 2025 07:44

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/StandaloneModuleGraph.zig (1)

1065-1071: Bug: second bun.getFdPath occurrence

Same fix as above in the POSIX branch.

Apply this diff:

-        const temp_location = bun.getFdPath(fd, &buf) catch |err| {
+        const temp_location = Syscall.getFdPath(fd, &buf) catch |err| {
src/bundler/bundle_v2.zig (1)

1927-1933: Free allocated outfile on failure; avoid leak.

full_outfile_path is heap-allocated; on toExecutable failure it’s never freed.

Apply:

             // Add .exe extension for Windows targets if not already present
             if (compile_options.compile_target.os == .windows and !strings.hasSuffixComptime(full_outfile_path, ".exe")) {
                 full_outfile_path = std.fmt.allocPrint(bun.default_allocator, "{s}.exe", .{full_outfile_path}) catch |err| bun.handleOom(err);
             } else {
                 full_outfile_path = bun.handleOom(bun.default_allocator.dupe(u8, full_outfile_path));
             }
@@
             const result = bun.StandaloneModuleGraph.toExecutable(
@@
             ) catch |err| {
-                return bun.StandaloneModuleGraph.CompileResult.fail(bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{s}", .{@errorName(err)})));
+                // prevent leak of owned full_outfile_path
+                bun.default_allocator.free(full_outfile_path);
+                return bun.StandaloneModuleGraph.CompileResult.fail(
+                    bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "{s}", .{@errorName(err)})),
+                );
             };
♻️ Duplicate comments (2)
src/bundler/bundle_v2.zig (1)

1914-1925: Bug: absolute outfile must take precedence over outdir (regression).

If compile_options.outfile is absolute and config.outdir is set, the current branch joins them, producing an invalid path. Prefer the absolute outfile, then fall back to outdir, then CWD.

Apply:

-            var full_outfile_path = if (this.config.outdir.slice().len > 0) brk: {
-                const outdir_slice = this.config.outdir.slice();
-                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
-                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outdir_slice, compile_options.outfile.slice() }, .auto);
-            } else if (std.fs.path.isAbsolute(compile_options.outfile.slice()))
-                compile_options.outfile.slice()
-            else brk: {
-                // For relative paths, ensure we make them absolute relative to the current working directory
-                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
-                break :brk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{compile_options.outfile.slice()}, .auto);
-            };
+            var full_outfile_path = blk: {
+                const top_level_dir = bun.fs.FileSystem.instance.top_level_dir;
+                const outfile = compile_options.outfile.slice();
+                if (std.fs.path.isAbsolute(outfile)) break :blk outfile;
+                if (this.config.outdir.slice().len > 0) {
+                    const outdir_slice = this.config.outdir.slice();
+                    break :blk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outdir_slice, outfile }, .auto);
+                }
+                // Relative: resolve against cwd/top_level_dir
+                break :blk bun.path.joinAbsStringBuf(top_level_dir, outbuf, &[_][]const u8{ outfile }, .auto);
+            };
test/regression/issue/compile-outfile-subdirs.test.ts (1)

44-68: Gate backslash path test to Windows.

Backslash is a valid POSIX filename character; this test will fail on non‑Windows.

Apply:

-  test("places executable in subdirectory with backslash", async () => {
+  test.if(isWindows)("places executable in subdirectory with backslash", async () => {
🧹 Nitpick comments (5)
src/StandaloneModuleGraph.zig (2)

1011-1021: Nit: unnecessary manual null-termination and slice re-interpretation

toWPathNormalized returns a zero-terminated slice; you can pass .ptr directly to Win32.

Apply this diff:

-            // Convert paths to Windows UTF-16
-            var temp_buf_w: bun.OSPathBuffer = undefined;
-            var dest_buf_w: bun.OSPathBuffer = undefined;
-            const temp_w = bun.strings.toWPathNormalized(&temp_buf_w, temp_path);
-            const dest_w = bun.strings.toWPathNormalized(&dest_buf_w, dest_path);
-
-            // Ensure null termination
-            const temp_buf_u16 = bun.reinterpretSlice(u16, &temp_buf_w);
-            const dest_buf_u16 = bun.reinterpretSlice(u16, &dest_buf_w);
-            temp_buf_u16[temp_w.len] = 0;
-            dest_buf_u16[dest_w.len] = 0;
+            // Convert paths to Windows UTF-16 (already zero-terminated)
+            var temp_buf_w: bun.OSPathBuffer = undefined;
+            var dest_buf_w: bun.OSPathBuffer = undefined;
+            const temp_w = bun.strings.toWPathNormalized(&temp_buf_w, temp_path);
+            const dest_w = bun.strings.toWPathNormalized(&dest_buf_w, dest_path);

And update the MoveFileExW call:

-            if (bun.windows.kernel32.MoveFileExW(temp_buf_u16[0..temp_w.len :0].ptr, dest_buf_u16[0..dest_w.len :0].ptr, bun.windows.MOVEFILE_COPY_ALLOWED | bun.windows.MOVEFILE_REPLACE_EXISTING | bun.windows.MOVEFILE_WRITE_THROUGH) == bun.windows.FALSE) {
+            if (bun.windows.kernel32.MoveFileExW(temp_w.ptr, dest_w.ptr, bun.windows.MOVEFILE_COPY_ALLOWED | bun.windows.MOVEFILE_REPLACE_EXISTING | bun.windows.MOVEFILE_WRITE_THROUGH) == bun.windows.FALSE) {

Also applies to: 1027-1027


1069-1075: Minor: prefer platform helpers for basename conversion

std.posix.toPosixPath is fine, but we already normalize earlier. Optional cleanup; no action required.

test/bundler/bun-build-compile.test.ts (1)

98-131: Also root the embedded-resources outfile in the temp dir

Prevents writes outside the test sandbox; optional to later execute the binary for stronger validation.

Apply this diff:

-      compile: {
-        outfile: "app-with-resources",
-      },
+      compile: {
+        outfile: join(dir + "", "app-with-resources"),
+      },

Optional: spawn the produced binary and assert stdout contains "Embedded file:" to exercise the embedding path at runtime.

test/regression/issue/compile-outfile-subdirs.test.ts (2)

8-42: Avoid asserting stderr === "".

Tooling may emit benign warnings; prefer snapshotting or checking “no errors” via exit code only.

Example:

-    expect(stderr).toBe("");
+    // Optionally snapshot if needed:
+    // expect(normalizeBunSnapshot(stderr)).toMatchSnapshot();

146-169: Error assertion could be more tolerant.

Error text may vary. Keep exitCode !== 0, and consider snapshotting stderr for stability.

-    expect(stderr.toLowerCase()).toContain("notdir");
+    // expect(normalizeBunSnapshot(stderr)).toMatchSnapshot();
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 afe20d2050cb3ab6051278a26d0197ab014534f9 and 135cc13.

📒 Files selected for processing (6)
  • src/StandaloneModuleGraph.zig (3 hunks)
  • src/bundler/bundle_v2.zig (3 hunks)
  • src/sys.zig (1 hunks)
  • test/bundler/bun-build-compile-wasm.test.ts (1 hunks)
  • test/bundler/bun-build-compile.test.ts (1 hunks)
  • test/regression/issue/compile-outfile-subdirs.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
test/**

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

Place all tests under the test/ directory

Files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.test.ts
test/bundler/**/*

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

Place bundler/transpiler/CSS/bun build tests under test/bundler/

Files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/bundler/bun-build-compile.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/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.test.ts
test/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

test/**/*.test.{ts,tsx}: Tests must be named with the suffix .test.ts or .test.tsx and live under the test/ directory
In tests, always use port: 0 and never hardcode ports or use custom random-port utilities
Prefer snapshot tests using normalizeBunSnapshot(...) over direct string equality on stdout/stderr
Do not write tests that assert absence of 'panic', 'uncaught exception', or similar strings in output
Avoid shelling out to tools like find or grep in tests; use Bun.Glob and built-in utilities

Files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.test.ts
test/bundler/**

📄 CodeRabbit inference engine (CLAUDE.md)

Place bundler and transpiler tests under test/bundler/

Files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/bundler/bun-build-compile.test.ts
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (CLAUDE.md)

Run Prettier to format JS/TS files (bun run prettier)

Files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.test.ts
test/**/*.test.ts

📄 CodeRabbit inference engine (test/CLAUDE.md)

test/**/*.test.ts: Name test files *.test.ts and use bun:test
Do not write flaky tests: never wait for arbitrary time; wait for conditions instead
Never hardcode port numbers in tests; use port: 0 to get a random port
When spawning Bun in tests, use bunExe() and bunEnv from harness
Prefer async/await in tests; for a single callback, use Promise.withResolvers()
Do not set explicit test timeouts; rely on Bun’s built-in timeouts
Use tempDir/tempDirWithFiles from harness for temporary files and directories in tests
For large/repetitive strings in tests, prefer Buffer.alloc(count, fill).toString() over "A".repeat(count)
Import common test utilities from harness (e.g., bunExe, bunEnv, tempDirWithFiles, tmpdirSync, platform checks, GC helpers)
In error tests, assert non-zero exit codes for failing processes and use toThrow for synchronous errors
Use describe blocks for grouping, describe.each for parameterized tests, snapshots with toMatchSnapshot, and lifecycle hooks (beforeAll, beforeEach, afterEach); track resources for cleanup in afterEach
Use using/await using with Bun resources (e.g., Bun.listen/connect/spawn/serve) to ensure cleanup in tests

Files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.test.ts
test/regression/issue/**

📄 CodeRabbit inference engine (CLAUDE.md)

Place regression tests (one per bug fix) under test/regression/issue/

Place regression tests under test/regression/issue/ and organize by issue number

Files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
src/**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)

Implement debug logs in Zig using const log = bun.Output.scoped(.${SCOPE}, false); and invoking log("...", .{})

In Zig code, manage memory carefully: use appropriate allocators and defer for cleanup

Files:

  • src/bundler/bundle_v2.zig
  • src/StandaloneModuleGraph.zig
  • src/sys.zig
**/*.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

Run zig-format to format Zig files (bun run zig-format)

Files:

  • src/bundler/bundle_v2.zig
  • src/StandaloneModuleGraph.zig
  • src/sys.zig
🧠 Learnings (18)
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/js/bun/** : Place Bun-specific API tests (http, crypto, ffi, shell, etc.) under test/js/bun/

Applied to files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.test.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/dev/bundle.test.ts : bundle.test.ts should contain DevServer-specific bundling tests

Applied to files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.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/bun/**/*.{js,ts} : Place Bun API tests under test/js/bun/, separated by category (e.g., test/js/bun/glob/)

Applied to files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.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/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.test.ts
📚 Learning: 2025-09-03T17:10:13.460Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.460Z
Learning: Applies to test/**/*.test.ts : When spawning Bun in tests, use `bunExe()` and `bunEnv` from `harness`

Applied to files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.test.ts
📚 Learning: 2025-09-03T17:10:13.460Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.460Z
Learning: Applies to test/**/*.test.ts : Name test files `*.test.ts` and use `bun:test`

Applied to files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.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/cli/**/*.{js,ts} : When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes

Applied to files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.test.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/dev/esm.test.ts : esm.test.ts should cover ESM feature behavior in development mode

Applied to files:

  • test/bundler/bun-build-compile-wasm.test.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/dev/css.test.ts : css.test.ts should contain CSS bundling tests in dev mode

Applied to files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/bundler/bun-build-compile.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/bundler/**/* : Place bundler/transpiler/CSS/bun build tests under test/bundler/

Applied to files:

  • test/bundler/bun-build-compile-wasm.test.ts
  • test/bundler/bun-build-compile.test.ts
📚 Learning: 2025-09-03T17:10:13.460Z
Learnt from: CR
PR: oven-sh/bun#0
File: test/CLAUDE.md:0-0
Timestamp: 2025-09-03T17:10:13.460Z
Learning: Applies to test/**/*.test.ts : Import common test utilities from `harness` (e.g., `bunExe`, `bunEnv`, `tempDirWithFiles`, `tmpdirSync`, platform checks, GC helpers)

Applied to files:

  • test/bundler/bun-build-compile-wasm.test.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Import testing utilities (devTest, prodTest, devAndProductionTest, Dev, Client) from test/bake/bake-harness.ts

Applied to files:

  • test/bundler/bun-build-compile-wasm.test.ts
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/**/*.test.{ts,tsx} : Avoid shelling out to tools like find or grep in tests; use Bun.Glob and built-in utilities

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.test.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/{dev/*.test.ts,dev-and-prod.ts} : Do not use node:fs APIs in tests; mutate files via dev.write, dev.patch, and dev.delete

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.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/cli/**/*.{js,ts} : Place CLI command tests (e.g., bun install, bun init) under test/cli/

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
  • test/bundler/bun-build-compile.test.ts
📚 Learning: 2025-09-03T17:09:28.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: CLAUDE.md:0-0
Timestamp: 2025-09-03T17:09:28.100Z
Learning: Applies to test/**/*.test.{ts,tsx} : Prefer snapshot tests using normalizeBunSnapshot(...) over direct string equality on stdout/stderr

Applied to files:

  • test/regression/issue/compile-outfile-subdirs.test.ts
📚 Learning: 2025-08-30T00:09:39.100Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/dev-server-tests.mdc:0-0
Timestamp: 2025-08-30T00:09:39.100Z
Learning: Applies to test/bake/dev/sourcemap.test.ts : sourcemap.test.ts should verify source map correctness in dev

Applied to files:

  • test/bundler/bun-build-compile.test.ts
📚 Learning: 2025-08-30T00:13:36.815Z
Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/zig-javascriptcore-classes.mdc:0-0
Timestamp: 2025-08-30T00:13:36.815Z
Learning: Applies to src/bun.js/**/*.zig : In Zig binding structs, expose generated bindings via pub const js = JSC.Codegen.JS<ClassName> and re-export toJS/fromJS/fromJSDirect

Applied to files:

  • src/bundler/bundle_v2.zig
🧬 Code graph analysis (3)
test/bundler/bun-build-compile-wasm.test.ts (1)
test/harness.ts (1)
  • tempDirWithFiles (258-265)
test/regression/issue/compile-outfile-subdirs.test.ts (1)
test/harness.ts (1)
  • tempDir (276-283)
test/bundler/bun-build-compile.test.ts (1)
test/harness.ts (2)
  • tempDir (276-283)
  • isWindows (24-24)
🔇 Additional comments (12)
src/sys.zig (1)

3810-3815: XDEV fallback now returns success — correct behavior

Early-return after copy+unlink in the XDEV branch fixes the previous erroneous error propagation. Matches move semantics elsewhere.

src/StandaloneModuleGraph.zig (3)

47-51: Good split: canonicalized checker vs public wrapper

Keeping the public isBunStandaloneFilePath and adding a canonicalized variant is clean and future-proof.


52-59: Windows NT-prefix handling is correct

Stripping NT prefixes before the prefix check prevents false negatives on Windows.


1027-1038: Ensure parent directories exist before MoveFileExW

MoveFileExW fails if the destination directory doesn’t exist. Confirm upstream always creates parents for an absolute outfile, or create them here (e.g., via bun.sys.openDirAtWindowsA(..., .{ .create = true }) on the dirname).

Would you like me to wire a minimal mkdirp here that uses openDirAtWindowsA(.cwd(), dirname, .{ .create = true }) for relative dirnames and the NT-absolute variant for absolute ones?

src/bundler/bundle_v2.zig (3)

1841-1848: Correct: set compile-mode public_path to target base.

This aligns embedded-resource lookups (e.g., wasm) with the compile target.


1960-1962: Correct: pass target-specific module_prefix.

This ensures embedded assets resolve from the target base (e.g., “root/”) during runtime.


1968-1970: Confirm toExecutable signature didn’t shift.

You added module_prefix and outfile_for_executable. Ensure their positions match toExecutable’s current signature to avoid ABI mismatches.

Would you like me to scan src/StandaloneModuleGraph.zig and verify the parameter order?

test/regression/issue/compile-outfile-subdirs.test.ts (5)

70-92: LGTM: creates nested parent directories.

Covers the mkdirp behavior end-to-end.


94-145: LGTM: Windows metadata regression coverage.

Good use of test.if(isWindows) and PowerShell to validate VersionInfo.


170-192: LGTM: path normalization with . and ...

Validates canonicalization behavior.


196-219: LGTM: API compile writes into subdirectories.

Checks output path and existence; concise and effective.


221-259: LGTM: API + Windows metadata in subdirs.

Solid coverage for metadata fields and nested output.

Comment thread src/bundler/bundle_v2.zig
Comment on lines +1944 to +1947
// On Windows, don't change root_dir, just pass the full relative path
// On POSIX, change root_dir to the target directory and pass basename
const outfile_for_executable = if (Environment.isWindows) full_outfile_path else basename;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use target OS, not host OS, for outfile wiring.

Environment.isWindows reflects the build host, not the compile target. Use compile_options.compile_target.os.

Apply:

-            const outfile_for_executable = if (Environment.isWindows) full_outfile_path else basename;
+            const target_is_windows = compile_options.compile_target.os == .windows;
+            const outfile_for_executable = if (target_is_windows) full_outfile_path else basename;
📝 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.

Suggested change
// On Windows, don't change root_dir, just pass the full relative path
// On POSIX, change root_dir to the target directory and pass basename
const outfile_for_executable = if (Environment.isWindows) full_outfile_path else basename;
// On Windows, don't change root_dir, just pass the full relative path
// On POSIX, change root_dir to the target directory and pass basename
const target_is_windows = compile_options.compile_target.os == .windows;
const outfile_for_executable = if (target_is_windows) full_outfile_path else basename;
🤖 Prompt for AI Agents
In src/bundler/bundle_v2.zig around lines 1944 to 1947, the code uses
Environment.isWindows (host OS) to decide how to wire outfile paths; change it
to use the compile target OS by checking compile_options.compile_target.os (e.g.
compare to .windows) so the conditional uses the target platform, and update the
ternary to: if (compile_options.compile_target.os == .windows) use
full_outfile_path else use basename; ensure compile_options is in scope and
adjust any names accordingly.

Comment thread src/bundler/bundle_v2.zig
Comment on lines +1948 to 1958
if (Environment.isPosix and !(dirname.len == 0 or strings.eqlComptime(dirname, "."))) {
// On POSIX, makeOpenPath and change root_dir
root_dir = root_dir.makeOpenPath(dirname, .{}) catch |err| {
return bun.StandaloneModuleGraph.CompileResult.fail(bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "Failed to open output directory {s}: {s}", .{ dirname, @errorName(err) })));
};
} else if (Environment.isWindows and !(dirname.len == 0 or strings.eqlComptime(dirname, "."))) {
// On Windows, ensure directories exist but don't change root_dir
_ = bun.makePath(root_dir, dirname) catch |err| {
return bun.StandaloneModuleGraph.CompileResult.fail(bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "Failed to create output directory {s}: {s}", .{ dirname, @errorName(err) })));
};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Handle absolute vs relative output dirs (POSIX).

For POSIX, opening an absolute dir should use openDirAbsolute; makeOpenPath assumes relative. Otherwise absolute paths may fail or open relative to CWD unintentionally.

Apply:

-            if (Environment.isPosix and !(dirname.len == 0 or strings.eqlComptime(dirname, "."))) {
-                // On POSIX, makeOpenPath and change root_dir
-                root_dir = root_dir.makeOpenPath(dirname, .{}) catch |err| {
+            if (compile_options.compile_target.os != .windows and !(dirname.len == 0 or strings.eqlComptime(dirname, "."))) {
+                // POSIX: open absolute dirs directly; otherwise open relative to CWD
+                root_dir = (if (std.fs.path.isAbsolute(dirname))
+                    bun.FD.openDirAbsolute(dirname, .{})
+                else
+                    root_dir.makeOpenPath(dirname, .{})) catch |err| {
                     return bun.StandaloneModuleGraph.CompileResult.fail(bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "Failed to open output directory {s}: {s}", .{ dirname, @errorName(err) })));
                 };
-            } else if (Environment.isWindows and !(dirname.len == 0 or strings.eqlComptime(dirname, "."))) {
+            } else if (compile_options.compile_target.os == .windows and !(dirname.len == 0 or strings.eqlComptime(dirname, "."))) {
                 // On Windows, ensure directories exist but don't change root_dir
                 _ = bun.makePath(root_dir, dirname) catch |err| {
                     return bun.StandaloneModuleGraph.CompileResult.fail(bun.handleOom(std.fmt.allocPrint(bun.default_allocator, "Failed to create output directory {s}: {s}", .{ dirname, @errorName(err) })));
                 };
             }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/bundler/bundle_v2.zig around lines 1948 to 1958, the POSIX branch uses
makeOpenPath which assumes a relative path; if dirname is absolute this will
open relative to CWD incorrectly. Change the logic to detect absolute paths
(e.g. path starts with '/') and when absolute call the appropriate absolute-open
API (openDirAbsolute or equivalent on root_dir) with the same error handling,
otherwise keep using makeOpenPath for relative paths; preserve the existing
error messages and OOM handling on failure.

Comment on lines +994 to 996
const temp_path = bun.getFdPath(fd, &temp_buf) catch |err| {
return CompileResult.fail(std.fmt.allocPrint(allocator, "Failed to get temp file path: {s}", .{@errorName(err)}) catch "Failed to get temp file path");
};

@coderabbitai coderabbitai Bot Sep 4, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Bug: bun.getFdPath does not exist (should be Syscall.getFdPath)

Call the sys variant to compile.

Apply this diff:

-            const temp_path = bun.getFdPath(fd, &temp_buf) catch |err| {
+            const temp_path = Syscall.getFdPath(fd, &temp_buf) catch |err| {
📝 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.

Suggested change
const temp_path = bun.getFdPath(fd, &temp_buf) catch |err| {
return CompileResult.fail(std.fmt.allocPrint(allocator, "Failed to get temp file path: {s}", .{@errorName(err)}) catch "Failed to get temp file path");
};
const temp_path = Syscall.getFdPath(fd, &temp_buf) catch |err| {
return CompileResult.fail(
std.fmt.allocPrint(
allocator,
"Failed to get temp file path: {s}",
.{@errorName(err)}
)
catch "Failed to get temp file path"
);
};
🤖 Prompt for AI Agents
In src/StandaloneModuleGraph.zig around lines 994 to 996, the code calls
bun.getFdPath which doesn't exist; replace that call with Syscall.getFdPath and
keep the existing error handling/formatting intact. Ensure Syscall is in scope
(import or fully qualify the symbol as used elsewhere in the file) so the
compiler can resolve getFdPath, and run a build to confirm no other references
to bun.getFdPath remain.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

You're not the compiler.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for getFdPath function definitions and usage patterns
echo "=== Searching for getFdPath function definitions ==="
rg -n "fn getFdPath" --type=zig

echo -e "\n=== Searching for bun.getFdPath usage ==="
rg -n "bun\.getFdPath" --type=zig

echo -e "\n=== Searching for Syscall.getFdPath usage ==="
rg -n "Syscall\.getFdPath" --type=zig

echo -e "\n=== Searching for any getFdPath usage ==="
rg -n -C2 "getFdPath" --type=zig

Length of output: 34316


@coderabbitai You're absolutely right, and I apologize for the incorrect analysis.

Looking at the search results, I can clearly see that bun.getFdPath is indeed a valid function that exists in the codebase:

  1. Function definition exists: In src/bun.zig:1310, there's pub fn getFdPath(fd: FileDescriptor, buf: *bun.PathBuffer) ![]u8
  2. Widely used pattern: The search shows bun.getFdPath is used extensively throughout the codebase (25+ occurrences)
  3. Both patterns coexist: The codebase uses both bun.getFdPath and Syscall.getFdPath in different contexts, indicating they serve different purposes

The code in the diff is using the correct API. My suggestion to change it to Syscall.getFdPath was incorrect - bun.getFdPath is the proper high-level wrapper function that should be used in this context.

Thank you for the correction. The code as written is correct and doesn't need any changes.


🧠 Learnings used
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

Learnt from: CR
PR: oven-sh/bun#0
File: .cursor/rules/zig-javascriptcore-classes.mdc:0-0
Timestamp: 2025-08-30T00:13:36.815Z
Learning: Applies to src/bun.js/**/*.zig : Constructors and prototype methods should return bun.JSError!JSC.JSValue to integrate Zig error handling with JS exceptions

Comment thread test/bundler/bun-build-compile.test.ts Resolved
@Jarred-Sumner
Jarred-Sumner merged commit d5431fc into main Sep 5, 2025
@Jarred-Sumner
Jarred-Sumner deleted the claude/fix-compile-windows-yoga-wasm branch September 5, 2025 01:17
@coderabbitai coderabbitai Bot mentioned this pull request Oct 16, 2025
3 of 5 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants