Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 54 additions & 34 deletions src/StandaloneModuleGraph.zig
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,20 @@ pub const StandaloneModuleGraph = struct {
};
}

pub fn isBunStandaloneFilePath(str: []const u8) bool {
pub fn isBunStandaloneFilePathCanonicalized(str: []const u8) bool {
return bun.strings.hasPrefixComptime(str, base_path) or
(Environment.isWindows and bun.strings.hasPrefixComptime(str, base_public_path));
}

pub fn isBunStandaloneFilePath(str: []const u8) bool {
if (Environment.isWindows) {
// On Windows, remove NT path prefixes before checking
const canonicalized = strings.withoutNTPrefix(u8, str);
return isBunStandaloneFilePathCanonicalized(canonicalized);
}
return isBunStandaloneFilePathCanonicalized(str);
}

pub fn entryPoint(this: *const StandaloneModuleGraph) *File {
return &this.files.values()[this.entry_point_id];
}
Expand Down Expand Up @@ -980,27 +989,54 @@ pub const StandaloneModuleGraph = struct {
}

if (Environment.isWindows) {
var outfile_buf: bun.OSPathBuffer = undefined;
const outfile_slice = brk: {
const outfile_w = bun.strings.toWPathNormalized(&outfile_buf, std.fs.path.basenameWindows(outfile));
bun.assert(outfile_w.ptr == &outfile_buf);
const outfile_buf_u16 = bun.reinterpretSlice(u16, &outfile_buf);
outfile_buf_u16[outfile_w.len] = 0;
break :brk outfile_buf_u16[0..outfile_w.len :0];
// Get the current path of the temp file
var temp_buf: bun.PathBuffer = undefined;
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");
};
Comment on lines +994 to 996

@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


bun.windows.moveOpenedFileAtLoose(fd, .fromStdDir(root_dir), outfile_slice, true).unwrap() catch |err| {
_ = bun.windows.deleteOpenedFile(fd);
if (err == error.EISDIR) {
return CompileResult.fail(std.fmt.allocPrint(allocator, "{s} is a directory. Please choose a different --outfile or delete the directory", .{outfile}) catch "outfile is a directory");
} else {
return CompileResult.fail(std.fmt.allocPrint(allocator, "failed to move executable to result path: {s}", .{@errorName(err)}) catch "failed to move executable");
}
// Build the absolute destination path
// On Windows, we need an absolute path for MoveFileExW
// Get the current working directory and join with outfile
var cwd_buf: bun.PathBuffer = undefined;
const cwd_path = bun.getcwd(&cwd_buf) catch |err| {
return CompileResult.fail(std.fmt.allocPrint(allocator, "Failed to get current directory: {s}", .{@errorName(err)}) catch "Failed to get current directory");
};

const dest_path = if (std.fs.path.isAbsolute(outfile))
outfile
else
bun.path.joinAbsString(cwd_path, &[_][]const u8{outfile}, .auto);

// 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;

// Close the file handle before moving (Windows requires this)
fd.close();
fd = bun.invalid_fd;

// Move the file using MoveFileExW
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) {
const err = bun.windows.Win32Error.get();
if (err.toSystemErrno()) |sys_err| {
if (sys_err == .EISDIR) {
return CompileResult.fail(std.fmt.allocPrint(allocator, "{s} is a directory. Please choose a different --outfile or delete the directory", .{outfile}) catch "outfile is a directory");
} else {
return CompileResult.fail(std.fmt.allocPrint(allocator, "failed to move executable to {s}: {s}", .{ dest_path, @tagName(sys_err) }) catch "failed to move executable");
}
} else {
return CompileResult.fail(std.fmt.allocPrint(allocator, "failed to move executable to {s}", .{dest_path}) catch "failed to move executable");
}
}

// Set Windows icon and/or metadata using unified function
if (windows_options.icon != null or
windows_options.title != null or
Expand All @@ -1009,25 +1045,9 @@ pub const StandaloneModuleGraph = struct {
windows_options.description != null or
windows_options.copyright != null)
{
// Need to get the full path to the executable
var full_path_buf: bun.OSPathBuffer = undefined;
const full_path = brk: {
// Get the directory path
var dir_buf: bun.PathBuffer = undefined;
const dir_path = bun.getFdPath(bun.FD.fromStdDir(root_dir), &dir_buf) catch |err| {
return CompileResult.fail(std.fmt.allocPrint(allocator, "Failed to get directory path: {s}", .{@errorName(err)}) catch "Failed to get directory path");
};

// Join with the outfile name
const full_path_str = bun.path.joinAbsString(dir_path, &[_][]const u8{outfile}, .auto);
const full_path_w = bun.strings.toWPathNormalized(&full_path_buf, full_path_str);
const buf_u16 = bun.reinterpretSlice(u16, &full_path_buf);
buf_u16[full_path_w.len] = 0;
break :brk buf_u16[0..full_path_w.len :0];
};

// The file has been moved to dest_path
bun.windows.rescle.setWindowsMetadata(
full_path.ptr,
dest_buf_u16[0..dest_w.len :0].ptr,
windows_options.icon,
windows_options.title,
windows_options.publisher,
Expand Down
38 changes: 33 additions & 5 deletions src/bundler/bundle_v2.zig
Original file line number Diff line number Diff line change
Expand Up @@ -1834,11 +1834,19 @@ pub const BundleV2 = struct {
transpiler.options.chunk_naming = config.names.chunk.data;
transpiler.options.asset_naming = config.names.asset.data;

transpiler.options.public_path = config.public_path.list.items;
transpiler.options.output_format = config.format;
transpiler.options.bytecode = config.bytecode;
transpiler.options.compile = config.compile != null;

// For compile mode, set the public_path to the target-specific base path
// This ensures embedded resources like yoga.wasm are correctly found
if (config.compile) |compile_opts| {
const base_public_path = bun.StandaloneModuleGraph.targetBasePublicPath(compile_opts.compile_target.os, "root/");
transpiler.options.public_path = base_public_path;
} else {
transpiler.options.public_path = config.public_path.list.items;
}

transpiler.options.output_dir = config.outdir.slice();
transpiler.options.root_dir = config.rootdir.slice();
transpiler.options.minify_syntax = config.minify.syntax;
Expand Down Expand Up @@ -1903,11 +1911,18 @@ pub const BundleV2 = struct {
const outbuf = bun.path_buffer_pool.get();
defer bun.path_buffer_pool.put(outbuf);

// 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 compile_options.outfile.slice();
} 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);
};

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Add .exe extension for Windows targets if not already present
if (compile_options.compile_target.os == .windows and !strings.hasSuffixComptime(full_outfile_path, ".exe")) {
Expand All @@ -1926,19 +1941,32 @@ pub const BundleV2 = struct {
}
}

if (!(dirname.len == 0 or strings.eqlComptime(dirname, "."))) {
// 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;

Comment on lines +1944 to +1947

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.

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) })));
};
}
Comment on lines +1948 to 1958

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.


// Use the target-specific base path for compile mode, not the user-configured public_path
const module_prefix = bun.StandaloneModuleGraph.targetBasePublicPath(compile_options.compile_target.os, "root/");

const result = bun.StandaloneModuleGraph.toExecutable(
&compile_options.compile_target,
bun.default_allocator,
output_files.items,
root_dir,
this.config.public_path.slice(),
basename,
module_prefix,
outfile_for_executable,
this.env,
this.config.format,
.{
Expand Down
1 change: 1 addition & 0 deletions src/sys.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3810,6 +3810,7 @@ pub fn moveFileZWithHandle(from_handle: bun.FileDescriptor, from_dir: bun.FileDe
if (err.getErrno() == .XDEV) {
try copyFileZSlowWithHandle(from_handle, to_dir, destination).unwrap();
_ = unlinkat(from_dir, filename);
return;
}

return bun.errnoToZigErr(err.errno);
Expand Down
126 changes: 126 additions & 0 deletions test/bundler/bun-build-compile-wasm.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { describe, expect, test } from "bun:test";
import { bunEnv, tempDirWithFiles } from "harness";
import { join } from "path";

describe("Bun.build compile with wasm", () => {
test("compile with wasm module imports", async () => {
// This test ensures that embedded wasm modules compile and run correctly
// The regression was that the module prefix wasn't being set correctly

const dir = tempDirWithFiles("build-compile-wasm", {
"app.js": `
// Import a wasm module and properly instantiate it
import wasmPath from "./test.wasm";

async function main() {
try {
// Read the wasm file as ArrayBuffer
const wasmBuffer = await Bun.file(wasmPath).arrayBuffer();
const { instance } = await WebAssembly.instantiate(wasmBuffer);

// Call the add function from wasm
const result = instance.exports.add(2, 3);
console.log("WASM result:", result);

if (result === 5) {
console.log("WASM module loaded successfully");
process.exit(0);
} else {
console.error("WASM module returned unexpected result:", result);
process.exit(1);
}
} catch (error) {
console.error("Failed to load WASM module:", error.message);
process.exit(1);
}
}

main();
`,
// A real WebAssembly module that exports an 'add' function
// (module
// (func $add (param i32 i32) (result i32)
// local.get 0
// local.get 1
// i32.add)
// (export "add" (func $add)))
"test.wasm": Buffer.from([
0x00,
0x61,
0x73,
0x6d, // WASM magic number
0x01,
0x00,
0x00,
0x00, // WASM version 1
// Type section
0x01,
0x07,
0x01,
0x60,
0x02,
0x7f,
0x7f,
0x01,
0x7f,
// Function section
0x03,
0x02,
0x01,
0x00,
// Export section
0x07,
0x07,
0x01,
0x03,
0x61,
0x64,
0x64,
0x00,
0x00,
// Code section
0x0a,
0x09,
0x01,
0x07,
0x00,
0x20,
0x00,
0x20,
0x01,
0x6a,
0x0b,
]),
});

// Test compilation with default target (current platform)
const result = await Bun.build({
entrypoints: [join(dir, "app.js")],
compile: {
outfile: "app-wasm",
},
});

expect(result.success).toBe(true);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
expect(result.outputs.length).toBe(1);

// Run the compiled version to verify it works
const proc = Bun.spawn({
cmd: [result.outputs[0].path],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
]);

expect(exitCode).toBe(0);
expect(stdout).toContain("WASM result: 5");
expect(stdout).toContain("WASM module loaded successfully");
expect(stderr).toBe("");
});
});
Loading