From e4915e43a383bba0a62aeb4347285099fc4e2661 Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Wed, 20 Nov 2024 20:44:29 -0800 Subject: [PATCH 1/2] zig: make throwInvalidArguments use JSError --- src/bake/FrameworkRouter.zig | 8 +- src/bake/bake.zig | 38 ++-- src/bun.js/ConsoleObject.zig | 12 +- src/bun.js/api/BunObject.zig | 274 ++++++++--------------- src/bun.js/api/JSBundler.zig | 31 ++- src/bun.js/api/JSTranspiler.zig | 63 ++---- src/bun.js/api/bun/dns_resolver.zig | 3 +- src/bun.js/api/bun/h2_frame_parser.zig | 14 +- src/bun.js/api/bun/socket.zig | 42 ++-- src/bun.js/api/bun/spawn/stdio.zig | 81 +++---- src/bun.js/api/bun/subprocess.zig | 71 ++---- src/bun.js/api/bun/udp_socket.zig | 69 +++--- src/bun.js/api/ffi.zig | 2 +- src/bun.js/api/filesystem_router.zig | 29 ++- src/bun.js/api/html_rewriter.zig | 35 +-- src/bun.js/api/server.zig | 156 ++++++------- src/bun.js/base.zig | 90 +++----- src/bun.js/bindings/bindings.zig | 28 +-- src/bun.js/javascript.zig | 2 +- src/bun.js/node/node_fs.zig | 166 +++++++------- src/bun.js/node/node_fs_stat_watcher.zig | 6 +- src/bun.js/node/node_fs_watcher.zig | 16 +- src/bun.js/node/node_net_binding.zig | 12 +- src/bun.js/node/types.zig | 46 ++-- src/bun.js/test/expect.zig | 120 ++++------ src/bun.js/webcore.zig | 21 +- src/bun.js/webcore/ObjectURLRegistry.zig | 4 +- src/bun.js/webcore/blob.zig | 53 ++--- src/bun.js/webcore/body.zig | 4 +- src/bun.js/webcore/encoding.zig | 41 ++-- src/bun.js/webcore/response.zig | 8 +- src/deps/c_ares.zig | 12 +- src/logger.zig | 2 +- src/options.zig | 10 +- src/shell/interpreter.zig | 41 +--- src/shell/shell.zig | 2 +- src/sql/postgres.zig | 3 +- src/url.zig | 9 +- 38 files changed, 623 insertions(+), 1001 deletions(-) diff --git a/src/bake/FrameworkRouter.zig b/src/bake/FrameworkRouter.zig index 870474141083ec..b689202c2f06dc 100644 --- a/src/bake/FrameworkRouter.zig +++ b/src/bake/FrameworkRouter.zig @@ -976,10 +976,10 @@ pub const JSFrameworkRouter = struct { pub fn constructor(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) !*JSFrameworkRouter { const opts = callframe.argumentsAsArray(1)[0]; if (!opts.isObject()) - return global.throwInvalidArguments2("FrameworkRouter needs an object as it's first argument", .{}); + return global.throwInvalidArguments("FrameworkRouter needs an object as it's first argument", .{}); const root = try opts.getOptional(global, "root", bun.String.Slice) orelse - return global.throwInvalidArguments2("Missing options.root", .{}); + return global.throwInvalidArguments("Missing options.root", .{}); defer root.deinit(); const style = try validators.validateStringEnum( @@ -1113,7 +1113,7 @@ pub const JSFrameworkRouter = struct { const alloc = arena.allocator(); if (frame.argumentsCount() < 2) - return global.throwInvalidArguments2("parseRoutePattern takes two arguments", .{}); + return global.throwInvalidArguments("parseRoutePattern takes two arguments", .{}); const style_js, const filepath_js = frame.argumentsAsArray(2); const filepath = try filepath_js.toSlice2(global, alloc); @@ -1122,7 +1122,7 @@ pub const JSFrameworkRouter = struct { defer style_string.deinit(); const style = std.meta.stringToEnum(Style, style_string.slice()) orelse - return global.throwInvalidArguments2("unknown router style {}", .{bun.fmt.quote(style_string.slice())}); + return global.throwInvalidArguments("unknown router style {}", .{bun.fmt.quote(style_string.slice())}); var log = TinyLog.empty; const parsed = style.parse(filepath.slice(), std.fs.path.extension(filepath.slice()), &log, alloc) catch |err| switch (err) { diff --git a/src/bake/bake.zig b/src/bake/bake.zig index 3db6f5ce59c374..d21fe1f6340ddd 100644 --- a/src/bake/bake.zig +++ b/src/bake/bake.zig @@ -26,7 +26,7 @@ pub const UserOptions = struct { pub fn fromJS(config: JSValue, global: *JSC.JSGlobalObject) !UserOptions { if (!config.isObject()) { - return global.throwInvalidArguments2("'" ++ api_name ++ "' is not an object", .{}); + return global.throwInvalidArguments("'" ++ api_name ++ "' is not an object", .{}); } var arena = std.heap.ArenaAllocator.init(bun.default_allocator); errdefer arena.deinit(); @@ -38,7 +38,7 @@ pub const UserOptions = struct { const framework = try Framework.fromJS( try config.get(global, "framework") orelse { - return global.throwInvalidArguments2("'" ++ api_name ++ "' is missing 'framework'", .{}); + return global.throwInvalidArguments("'" ++ api_name ++ "' is missing 'framework'", .{}); }, global, &allocations, @@ -278,7 +278,7 @@ pub const Framework = struct { } if (!opts.isObject()) { - return global.throwInvalidArguments2("Framework must be an object", .{}); + return global.throwInvalidArguments("Framework must be an object", .{}); } if (try opts.get(global, "serverEntryPoint") != null) { @@ -296,11 +296,11 @@ pub const Framework = struct { if (rfr == .false or rfr == .null or rfr == .undefined) break :brk null; if (!rfr.isObject()) { - return global.throwInvalidArguments2("'framework.reactFastRefresh' must be an object or 'true'", .{}); + return global.throwInvalidArguments("'framework.reactFastRefresh' must be an object or 'true'", .{}); } const prop = try rfr.get(global, "importSource") orelse { - return global.throwInvalidArguments2("'framework.reactFastRefresh' is missing 'importSource'", .{}); + return global.throwInvalidArguments("'framework.reactFastRefresh' is missing 'importSource'", .{}); }; const str = try prop.toBunString2(global); @@ -316,27 +316,27 @@ pub const Framework = struct { if (sc == .false or sc == .null or sc == .undefined) break :sc null; if (!sc.isObject()) { - return global.throwInvalidArguments2("'framework.serverComponents' must be an object or 'undefined'", .{}); + return global.throwInvalidArguments("'framework.serverComponents' must be an object or 'undefined'", .{}); } break :sc .{ .separate_ssr_graph = brk: { // Intentionally not using a truthiness check const prop = try sc.getOptional(global, "separateSSRGraph", JSValue) orelse { - return global.throwInvalidArguments2("Missing 'framework.serverComponents.separateSSRGraph'", .{}); + return global.throwInvalidArguments("Missing 'framework.serverComponents.separateSSRGraph'", .{}); }; if (prop == .true) break :brk true; if (prop == .false) break :brk false; - return global.throwInvalidArguments2("'framework.serverComponents.separateSSRGraph' must be a boolean", .{}); + return global.throwInvalidArguments("'framework.serverComponents.separateSSRGraph' must be a boolean", .{}); }, .server_runtime_import = refs.track( try sc.getOptional(global, "serverRuntimeImportSource", ZigString.Slice) orelse { - return global.throwInvalidArguments2("Missing 'framework.serverComponents.serverRuntimeImportSource'", .{}); + return global.throwInvalidArguments("Missing 'framework.serverComponents.serverRuntimeImportSource'", .{}); }, ), .server_register_client_reference = refs.track( try sc.getOptional(global, "serverRegisterClientReferenceExport", ZigString.Slice) orelse { - return global.throwInvalidArguments2("Missing 'framework.serverComponents.serverRegisterClientReferenceExport'", .{}); + return global.throwInvalidArguments("Missing 'framework.serverComponents.serverRegisterClientReferenceExport'", .{}); }, ), }; @@ -353,11 +353,11 @@ pub const Framework = struct { var i: usize = 0; while (it.next()) |file| : (i += 1) { if (!file.isObject()) { - return global.throwInvalidArguments2("'builtInModules[{d}]' is not an object", .{i}); + return global.throwInvalidArguments("'builtInModules[{d}]' is not an object", .{i}); } const path = try getOptionalString(file, global, "import", refs, arena) orelse { - return global.throwInvalidArguments2("'builtInModules[{d}]' is missing 'import'", .{i}); + return global.throwInvalidArguments("'builtInModules[{d}]' is missing 'import'", .{i}); }; const value: BuiltInModule = if (try getOptionalString(file, global, "path", refs, arena)) |str| @@ -365,7 +365,7 @@ pub const Framework = struct { else if (try getOptionalString(file, global, "code", refs, arena)) |str| .{ .code = str } else - return global.throwInvalidArguments2("'builtInModules[{d}]' needs either 'path' or 'code'", .{i}); + return global.throwInvalidArguments("'builtInModules[{d}]' needs either 'path' or 'code'", .{i}); files.putAssumeCapacity(path, value); } @@ -374,11 +374,11 @@ pub const Framework = struct { }; const file_system_router_types: []FileSystemRouterType = brk: { const array: JSValue = try opts.getArray(global, "fileSystemRouterTypes") orelse { - return global.throwInvalidArguments2("Missing 'framework.fileSystemRouterTypes'", .{}); + return global.throwInvalidArguments("Missing 'framework.fileSystemRouterTypes'", .{}); }; const len = array.getLength(global); if (len > 256) { - return global.throwInvalidArguments2("Framework can only define up to 256 file-system router types", .{}); + return global.throwInvalidArguments("Framework can only define up to 256 file-system router types", .{}); } const file_system_router_types = try arena.alloc(FileSystemRouterType, len); @@ -386,10 +386,10 @@ pub const Framework = struct { var i: usize = 0; while (it.next()) |fsr_opts| : (i += 1) { const root = try getOptionalString(fsr_opts, global, "root", refs, arena) orelse { - return global.throwInvalidArguments2("'fileSystemRouterTypes[{d}]' is missing 'root'", .{i}); + return global.throwInvalidArguments("'fileSystemRouterTypes[{d}]' is missing 'root'", .{i}); }; const server_entry_point = try getOptionalString(fsr_opts, global, "serverEntryPoint", refs, arena) orelse { - return global.throwInvalidArguments2("'fileSystemRouterTypes[{d}]' is missing 'serverEntryPoint'", .{i}); + return global.throwInvalidArguments("'fileSystemRouterTypes[{d}]' is missing 'serverEntryPoint'", .{i}); }; const client_entry_point = try getOptionalString(fsr_opts, global, "clientEntryPoint", refs, arena); const prefix = try getOptionalString(fsr_opts, global, "prefix", refs, arena) orelse "/"; @@ -421,7 +421,7 @@ pub const Framework = struct { break :exts extensions; } - return global.throwInvalidArguments2("'extensions' must be an array of strings or \"*\" for all extensions", .{}); + return global.throwInvalidArguments("'extensions' must be an array of strings or \"*\" for all extensions", .{}); } else &.{ ".jsx", ".tsx", ".js", ".ts", ".cjs", ".cts", ".mjs", ".mts" }; const ignore_dirs: []const []const u8 = if (try fsr_opts.get(global, "ignoreDirs")) |exts_js| exts: { @@ -435,7 +435,7 @@ pub const Framework = struct { break :exts dirs; } - return global.throwInvalidArguments2("'ignoreDirs' must be an array of strings or \"*\" for all extensions", .{}); + return global.throwInvalidArguments("'ignoreDirs' must be an array of strings or \"*\" for all extensions", .{}); } else &.{ ".git", "node_modules" }; file_system_router_types[i] = .{ diff --git a/src/bun.js/ConsoleObject.zig b/src/bun.js/ConsoleObject.zig index 1c3e66c9f8c40f..cc63da873bc50b 100644 --- a/src/bun.js/ConsoleObject.zig +++ b/src/bun.js/ConsoleObject.zig @@ -706,8 +706,7 @@ pub const FormatOptions = struct { if (opt.isInt32()) { const arg = opt.toInt32(); if (arg < 0) { - globalThis.throwInvalidArguments("expected depth to be greater than or equal to 0, got {d}", .{arg}); - return error.JSError; + return globalThis.throwInvalidArguments("expected depth to be greater than or equal to 0, got {d}", .{arg}); } formatOptions.max_depth = @as(u16, @truncate(@as(u32, @intCast(@min(arg, std.math.maxInt(u16)))))); } else if (opt.isNumber()) { @@ -715,8 +714,7 @@ pub const FormatOptions = struct { if (std.math.isInf(v)) { formatOptions.max_depth = std.math.maxInt(u16); } else { - globalThis.throwInvalidArguments("expected depth to be an integer, got {d}", .{v}); - return error.JSError; + return globalThis.throwInvalidArguments("expected depth to be an integer, got {d}", .{v}); } } } @@ -737,8 +735,7 @@ pub const FormatOptions = struct { if (depthArg.isInt32()) { const arg = depthArg.toInt32(); if (arg < 0) { - globalThis.throwInvalidArguments("expected depth to be greater than or equal to 0, got {d}", .{arg}); - return error.JSError; + return globalThis.throwInvalidArguments("expected depth to be greater than or equal to 0, got {d}", .{arg}); } formatOptions.max_depth = @as(u16, @truncate(@as(u32, @intCast(@min(arg, std.math.maxInt(u16)))))); } else if (depthArg.isNumber()) { @@ -746,8 +743,7 @@ pub const FormatOptions = struct { if (std.math.isInf(v)) { formatOptions.max_depth = std.math.maxInt(u16); } else { - globalThis.throwInvalidArguments("expected depth to be an integer, got {d}", .{v}); - return error.JSError; + return globalThis.throwInvalidArguments("expected depth to be an integer, got {d}", .{v}); } } if (arguments.len > 1 and !arguments[1].isEmptyOrUndefinedOrNull()) { diff --git a/src/bun.js/api/BunObject.zig b/src/bun.js/api/BunObject.zig index cc4b6689e18e06..ab501325fff5a6 100644 --- a/src/bun.js/api/BunObject.zig +++ b/src/bun.js/api/BunObject.zig @@ -601,13 +601,11 @@ pub fn registerMacro(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFram const arguments_ = callframe.arguments_old(2); const arguments = arguments_.slice(); if (arguments.len != 2 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Internal error registering macros: invalid args", .{}); - return .undefined; + return globalObject.throwInvalidArguments("Internal error registering macros: invalid args", .{}); } const id = arguments[0].toInt32(); if (id == -1 or id == 0) { - globalObject.throwInvalidArguments("Internal error registering macros: invalid id", .{}); - return .undefined; + return globalObject.throwInvalidArguments("Internal error registering macros: invalid id", .{}); } if (!arguments[1].isCell() or !arguments[1].isCallable(globalObject.vm())) { @@ -866,8 +864,7 @@ pub fn sleepSync(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b //NOTE: if argument is > max(i32) then it will be truncated const milliseconds = arg.coerce(i32, globalObject); if (milliseconds < 0) { - globalObject.throwInvalidArguments("argument to sleepSync must not be negative, got {d}", .{milliseconds}); - return .undefined; + return globalObject.throwInvalidArguments("argument to sleepSync must not be negative, got {d}", .{milliseconds}); } std.time.sleep(@as(u64, @intCast(milliseconds)) * std.time.ns_per_ms); @@ -893,23 +890,19 @@ fn doResolve(globalThis: *JSC.JSGlobalObject, arguments: []const JSValue) bun.JS var args = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); const specifier = args.protectEatNext() orelse { - globalThis.throwInvalidArguments("Expected a specifier and a from path", .{}); - return error.JSError; + return globalThis.throwInvalidArguments("Expected a specifier and a from path", .{}); }; if (specifier.isUndefinedOrNull()) { - globalThis.throwInvalidArguments("specifier must be a string", .{}); - return error.JSError; + return globalThis.throwInvalidArguments("specifier must be a string", .{}); } const from = args.protectEatNext() orelse { - globalThis.throwInvalidArguments("Expected a from path", .{}); - return error.JSError; + return globalThis.throwInvalidArguments("Expected a from path", .{}); }; if (from.isUndefinedOrNull()) { - globalThis.throwInvalidArguments("from must be a string", .{}); - return error.JSError; + return globalThis.throwInvalidArguments("from must be a string", .{}); } var is_esm = true; @@ -917,8 +910,7 @@ fn doResolve(globalThis: *JSC.JSGlobalObject, arguments: []const JSValue) bun.JS if (next.isBoolean()) { is_esm = next.toBoolean(); } else { - globalThis.throwInvalidArguments("esm must be a boolean", .{}); - return error.JSError; + return globalThis.throwInvalidArguments("esm must be a boolean", .{}); } } @@ -1426,7 +1418,7 @@ pub const Crypto = struct { const length = arguments[3].coerce(i64, globalThis); if (!globalThis.hasException() and (length < 0 or length > std.math.maxInt(i32))) { - return globalThis.throwInvalidArguments2("keylen must be > 0 and < {d}", .{std.math.maxInt(i32)}); + return globalThis.throwInvalidArguments("keylen must be > 0 and < {d}", .{std.math.maxInt(i32)}); } if (globalThis.hasException()) { @@ -1441,7 +1433,7 @@ pub const Crypto = struct { const iteration_count = arguments[2].coerce(i64, globalThis); if (!globalThis.hasException() and (iteration_count < 1 or iteration_count > std.math.maxInt(u32))) { - return globalThis.throwInvalidArguments2("iteration count must be >= 1 and <= maxInt", .{}); + return globalThis.throwInvalidArguments("iteration count must be >= 1 and <= maxInt", .{}); } if (globalThis.hasException()) { @@ -1485,7 +1477,7 @@ pub const Crypto = struct { }; if (out.salt.slice().len > std.math.maxInt(i32)) { - return globalThis.throwInvalidArguments2("salt is too long", .{}); + return globalThis.throwInvalidArguments("salt is too long", .{}); } out.password = JSC.Node.StringOrBuffer.fromJSMaybeAsync(globalThis, bun.default_allocator, arguments[0], is_async) orelse { @@ -1496,7 +1488,7 @@ pub const Crypto = struct { }; if (out.password.slice().len > std.math.maxInt(i32)) { - return globalThis.throwInvalidArguments2("password is too long", .{}); + return globalThis.throwInvalidArguments("password is too long", .{}); } return out; @@ -1645,7 +1637,7 @@ pub const Crypto = struct { const rounds = rounds_value.coerce(i32, globalObject); if (rounds < 4 or rounds > 31) { - return globalObject.throwInvalidArguments2("Rounds must be between 4 and 31", .{}); + return globalObject.throwInvalidArguments("Rounds must be between 4 and 31", .{}); } algorithm.bcrypt = @as(u6, @intCast(rounds)); @@ -1665,7 +1657,7 @@ pub const Crypto = struct { const time_cost = time_value.coerce(i32, globalObject); if (time_cost < 1) { - return globalObject.throwInvalidArguments2("Time cost must be greater than 0", .{}); + return globalObject.throwInvalidArguments("Time cost must be greater than 0", .{}); } argon.time_cost = @as(u32, @intCast(time_cost)); @@ -1680,7 +1672,7 @@ pub const Crypto = struct { const memory_cost = memory_value.coerce(i32, globalObject); if (memory_cost < 1) { - return globalObject.throwInvalidArguments2("Memory cost must be greater than 0", .{}); + return globalObject.throwInvalidArguments("Memory cost must be greater than 0", .{}); } argon.memory_cost = @as(u32, @intCast(memory_cost)); @@ -2136,8 +2128,7 @@ pub const Crypto = struct { errdefer bun.default_allocator.free(password_to_hash); if (password_to_hash.len == 0) { - globalObject.throwInvalidArguments("password must not be empty", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("password must not be empty", .{}); } return hash(globalObject, password_to_hash, algorithm, false); @@ -2167,7 +2158,7 @@ pub const Crypto = struct { defer string_or_buffer.deinit(); if (string_or_buffer.slice().len == 0) { - return globalObject.throwInvalidArguments2("password must not be empty", .{}); + return globalObject.throwInvalidArguments("password must not be empty", .{}); } return hash(globalObject, string_or_buffer.slice(), algorithm, true); @@ -2415,12 +2406,7 @@ pub const Crypto = struct { return JSC.JSValue.createStringArray(globalThis_, &values, values.len, true); } - fn hashToEncoding( - globalThis: *JSGlobalObject, - evp: *EVP, - input: JSC.Node.BlobOrStringOrBuffer, - encoding: JSC.Node.Encoding, - ) JSC.JSValue { + fn hashToEncoding(globalThis: *JSGlobalObject, evp: *EVP, input: JSC.Node.BlobOrStringOrBuffer, encoding: JSC.Node.Encoding) bun.JSError!JSC.JSValue { var output_digest_buf: Digest = undefined; defer input.deinit(); @@ -2439,12 +2425,7 @@ pub const Crypto = struct { return encoding.encodeWithMaxSize(globalThis, BoringSSL.EVP_MAX_MD_SIZE, output_digest_buf[0..len]); } - fn hashToBytes( - globalThis: *JSGlobalObject, - evp: *EVP, - input: JSC.Node.BlobOrStringOrBuffer, - output: ?JSC.ArrayBuffer, - ) JSC.JSValue { + fn hashToBytes(globalThis: *JSGlobalObject, evp: *EVP, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.ArrayBuffer) bun.JSError!JSC.JSValue { var output_digest_buf: Digest = undefined; var output_digest_slice: []u8 = &output_digest_buf; defer input.deinit(); @@ -2458,8 +2439,7 @@ pub const Crypto = struct { const size = evp.size(); var bytes = output_buf.byteSlice(); if (bytes.len < size) { - globalThis.throwInvalidArguments("TypedArray must be at least {d} bytes", .{size}); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("TypedArray must be at least {d} bytes", .{size}); } output_digest_slice = bytes[0..size]; } @@ -2485,10 +2465,9 @@ pub const Crypto = struct { algorithm: ZigString, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.Node.StringOrBuffer, - ) JSC.JSValue { - var evp = EVP.byName(algorithm, globalThis) orelse return CryptoHasherZig.hashByName(globalThis, algorithm, input, output) orelse { - globalThis.throwInvalidArguments("Unsupported algorithm \"{any}\"", .{algorithm}); - return .zero; + ) bun.JSError!JSC.JSValue { + var evp = EVP.byName(algorithm, globalThis) orelse return try CryptoHasherZig.hashByName(globalThis, algorithm, input, output) orelse { + return globalThis.throwInvalidArguments("Unsupported algorithm \"{any}\"", .{algorithm}); }; defer evp.deinit(); @@ -2498,7 +2477,7 @@ pub const Crypto = struct { defer str.deinit(); const encoding = JSC.Node.Encoding.from(str.slice()) orelse { globalThis.ERR_INVALID_ARG_VALUE("Unknown encoding: {s}", .{str.slice()}).throw(); - return JSC.JSValue.zero; + return error.JSError; }; return hashToEncoding(globalThis, &evp, input, encoding); @@ -2516,18 +2495,18 @@ pub const Crypto = struct { pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*CryptoHasher { const arguments = callframe.arguments_old(2); if (arguments.len == 0) { - return globalThis.throwInvalidArguments2("Expected an algorithm name as an argument", .{}); + return globalThis.throwInvalidArguments("Expected an algorithm name as an argument", .{}); } const algorithm_name = arguments.ptr[0]; if (algorithm_name.isEmptyOrUndefinedOrNull() or !algorithm_name.isString()) { - return globalThis.throwInvalidArguments2("algorithm must be a string", .{}); + return globalThis.throwInvalidArguments("algorithm must be a string", .{}); } const algorithm = algorithm_name.getZigString(globalThis); if (algorithm.len == 0) { - return globalThis.throwInvalidArguments2("Invalid algorithm name", .{}); + return globalThis.throwInvalidArguments("Invalid algorithm name", .{}); } const hmac_value = arguments.ptr[1]; @@ -2540,7 +2519,7 @@ pub const Crypto = struct { if (!hmac_value.isEmptyOrUndefinedOrNull()) { hmac_key = JSC.Node.StringOrBuffer.fromJS(globalThis, bun.default_allocator, hmac_value) orelse { - return globalThis.throwInvalidArguments2("key must be a string or buffer", .{}); + return globalThis.throwInvalidArguments("key must be a string or buffer", .{}); }; } @@ -2571,7 +2550,7 @@ pub const Crypto = struct { break :brk .{ .evp = EVP.byName(algorithm, globalThis) orelse return CryptoHasherZig.constructor(algorithm) orelse { - return globalThis.throwInvalidArguments2("Unsupported algorithm {any}", .{algorithm}); + return globalThis.throwInvalidArguments("Unsupported algorithm {any}", .{algorithm}); }, }; }); @@ -2589,11 +2568,11 @@ pub const Crypto = struct { const arguments = callframe.arguments_old(2); const input = arguments.ptr[0]; if (input.isEmptyOrUndefinedOrNull()) { - return globalThis.throwInvalidArguments2("expected blob, string or buffer", .{}); + return globalThis.throwInvalidArguments("expected blob, string or buffer", .{}); } const encoding = arguments.ptr[1]; const buffer = try JSC.Node.BlobOrStringOrBuffer.fromJSWithEncodingValue(globalThis, globalThis.bunVM().allocator, input, encoding) orelse { - if (!globalThis.hasException()) globalThis.throwInvalidArguments("expected blob, string or buffer", .{}); + if (!globalThis.hasException()) return globalThis.throwInvalidArguments("expected blob, string or buffer", .{}); return error.JSError; }; defer buffer.deinit(); @@ -2662,18 +2641,14 @@ pub const Crypto = struct { return CryptoHasher.new(new).toJS(globalObject); } - pub fn digest_( - this: *CryptoHasher, - globalThis: *JSGlobalObject, - output: ?JSC.Node.StringOrBuffer, - ) JSC.JSValue { + pub fn digest_(this: *CryptoHasher, globalThis: *JSGlobalObject, output: ?JSC.Node.StringOrBuffer) bun.JSError!JSC.JSValue { if (output) |string_or_buffer| { switch (string_or_buffer) { inline else => |*str| { defer str.deinit(); const encoding = JSC.Node.Encoding.from(str.slice()) orelse { globalThis.ERR_INVALID_ARG_VALUE("Unknown encoding: {s}", .{str.slice()}).throw(); - return JSC.JSValue.zero; + return error.JSError; }; return this.digestToEncoding(globalThis, encoding); @@ -2690,14 +2665,13 @@ pub const Crypto = struct { } } - fn digestToBytes(this: *CryptoHasher, globalThis: *JSGlobalObject, output: ?JSC.ArrayBuffer) JSC.JSValue { + fn digestToBytes(this: *CryptoHasher, globalThis: *JSGlobalObject, output: ?JSC.ArrayBuffer) bun.JSError!JSC.JSValue { var output_digest_buf: EVP.Digest = undefined; var output_digest_slice: []u8 = &output_digest_buf; if (output) |output_buf| { var bytes = output_buf.byteSlice(); if (bytes.len < output_digest_buf.len) { - globalThis.throwInvalidArguments(comptime std.fmt.comptimePrint("TypedArray must be at least {d} bytes", .{output_digest_buf.len}), .{}); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments(comptime std.fmt.comptimePrint("TypedArray must be at least {d} bytes", .{output_digest_buf.len}), .{}); } output_digest_slice = bytes[0..bytes.len]; } else { @@ -2706,7 +2680,7 @@ pub const Crypto = struct { const result = this.final(globalThis, output_digest_slice) catch return .zero; if (globalThis.hasException()) { - return JSC.JSValue.zero; + return error.JSError; } if (output) |output_buf| { @@ -2717,12 +2691,12 @@ pub const Crypto = struct { } } - fn digestToEncoding(this: *CryptoHasher, globalThis: *JSGlobalObject, encoding: JSC.Node.Encoding) JSC.JSValue { + fn digestToEncoding(this: *CryptoHasher, globalThis: *JSGlobalObject, encoding: JSC.Node.Encoding) bun.JSError!JSC.JSValue { var output_digest_buf: EVP.Digest = std.mem.zeroes(EVP.Digest); const output_digest_slice: []u8 = &output_digest_buf; const out = this.final(globalThis, output_digest_slice) catch return .zero; if (globalThis.hasException()) { - return JSC.JSValue.zero; + return error.JSError; } return encoding.encodeWithMaxSize(globalThis, BoringSSL.EVP_MAX_MD_SIZE, out); } @@ -2783,28 +2757,23 @@ pub const Crypto = struct { }; } - pub fn hashByName( - globalThis: *JSGlobalObject, - algorithm: ZigString, - input: JSC.Node.BlobOrStringOrBuffer, - output: ?JSC.Node.StringOrBuffer, - ) ?JSC.JSValue { + pub fn hashByName(globalThis: *JSGlobalObject, algorithm: ZigString, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.Node.StringOrBuffer) bun.JSError!?JSC.JSValue { inline for (algo_map) |item| { if (bun.strings.eqlComptime(algorithm.slice(), item[0])) { - return hashByNameInner(globalThis, item[1], input, output); + return try hashByNameInner(globalThis, item[1], input, output); } } return null; } - fn hashByNameInner(globalThis: *JSGlobalObject, comptime Algorithm: type, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.Node.StringOrBuffer) JSC.JSValue { + fn hashByNameInner(globalThis: *JSGlobalObject, comptime Algorithm: type, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.Node.StringOrBuffer) bun.JSError!JSC.JSValue { if (output) |string_or_buffer| { switch (string_or_buffer) { inline else => |*str| { defer str.deinit(); const encoding = JSC.Node.Encoding.from(str.slice()) orelse { globalThis.ERR_INVALID_ARG_VALUE("Unknown encoding: {s}", .{str.slice()}).throw(); - return JSC.JSValue.zero; + return error.JSError; }; if (encoding == .buffer) { @@ -2838,7 +2807,7 @@ pub const Crypto = struct { return encoding.encodeWithSize(globalThis, digestLength(Algorithm), &out); } - fn hashByNameInnerToBytes(globalThis: *JSGlobalObject, comptime Algorithm: type, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.ArrayBuffer) JSC.JSValue { + fn hashByNameInnerToBytes(globalThis: *JSGlobalObject, comptime Algorithm: type, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.ArrayBuffer) bun.JSError!JSC.JSValue { defer input.deinit(); if (input == .blob and input.blob.isBunFile()) { @@ -2851,8 +2820,7 @@ pub const Crypto = struct { if (output) |output_buf| { if (output_buf.byteSlice().len < digest_length_comptime) { - globalThis.throwInvalidArguments("TypedArray must be at least {d} bytes", .{digest_length_comptime}); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("TypedArray must be at least {d} bytes", .{digest_length_comptime}); } } @@ -2972,18 +2940,13 @@ pub const Crypto = struct { return encoding.encodeWithSize(globalThis, Hasher.digest, &output_digest_buf); } - fn hashToBytes( - globalThis: *JSGlobalObject, - input: JSC.Node.BlobOrStringOrBuffer, - output: ?JSC.ArrayBuffer, - ) JSC.JSValue { + fn hashToBytes(globalThis: *JSGlobalObject, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.ArrayBuffer) bun.JSError!JSC.JSValue { var output_digest_buf: Hasher.Digest = undefined; var output_digest_slice: *Hasher.Digest = &output_digest_buf; if (output) |output_buf| { var bytes = output_buf.byteSlice(); if (bytes.len < Hasher.digest) { - globalThis.throwInvalidArguments(comptime std.fmt.comptimePrint("TypedArray must be at least {d} bytes", .{Hasher.digest}), .{}); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments(comptime std.fmt.comptimePrint("TypedArray must be at least {d} bytes", .{Hasher.digest}), .{}); } output_digest_slice = bytes[0..Hasher.digest]; } @@ -3006,12 +2969,11 @@ pub const Crypto = struct { globalThis: *JSGlobalObject, input: JSC.Node.BlobOrStringOrBuffer, output: ?JSC.Node.StringOrBuffer, - ) JSC.JSValue { + ) bun.JSError!JSC.JSValue { defer input.deinit(); if (input == .blob and input.blob.isBunFile()) { - globalThis.throw("Bun.file() is not supported here yet (it needs an async version)", .{}); - return .zero; + return globalThis.throw2("Bun.file() is not supported here yet (it needs an async version)", .{}); } if (output) |string_or_buffer| { @@ -3020,7 +2982,7 @@ pub const Crypto = struct { defer str.deinit(); const encoding = JSC.Node.Encoding.from(str.slice()) orelse { globalThis.ERR_INVALID_ARG_VALUE("Unknown encoding: {s}", .{str.slice()}).throw(); - return JSC.JSValue.zero; + return error.JSError; }; return hashToEncoding(globalThis, input, encoding); @@ -3055,8 +3017,7 @@ pub const Crypto = struct { const thisValue = callframe.this(); const input = callframe.argument(0); const buffer = JSC.Node.BlobOrStringOrBuffer.fromJS(globalThis, globalThis.bunVM().allocator, input) orelse { - globalThis.throwInvalidArguments("expected blob or string or buffer", .{}); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected blob or string or buffer", .{}); }; defer buffer.deinit(); @@ -3072,7 +3033,7 @@ pub const Crypto = struct { this: *@This(), globalThis: *JSGlobalObject, output: ?JSC.Node.StringOrBuffer, - ) JSC.JSValue { + ) bun.JSError!JSC.JSValue { if (this.digested) { globalThis.ERR_INVALID_STATE(name ++ " hasher already digested, create a new instance to digest again", .{}).throw(); return .zero; @@ -3083,7 +3044,7 @@ pub const Crypto = struct { defer str.deinit(); const encoding = JSC.Node.Encoding.from(str.slice()) orelse { globalThis.ERR_INVALID_ARG_VALUE("Unknown encoding: {s}", .{str.slice()}).throw(); - return JSC.JSValue.zero; + return error.JSError; }; return this.digestToEncoding(globalThis, encoding); @@ -3100,14 +3061,13 @@ pub const Crypto = struct { } } - fn digestToBytes(this: *@This(), globalThis: *JSGlobalObject, output: ?JSC.ArrayBuffer) JSC.JSValue { + fn digestToBytes(this: *@This(), globalThis: *JSGlobalObject, output: ?JSC.ArrayBuffer) bun.JSError!JSC.JSValue { var output_digest_buf: Hasher.Digest = undefined; var output_digest_slice: *Hasher.Digest = &output_digest_buf; if (output) |output_buf| { var bytes = output_buf.byteSlice(); if (bytes.len < Hasher.digest) { - globalThis.throwInvalidArguments(comptime std.fmt.comptimePrint("TypedArray must be at least {d} bytes", .{Hasher.digest}), .{}); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments(comptime std.fmt.comptimePrint("TypedArray must be at least {d} bytes", .{Hasher.digest}), .{}); } output_digest_slice = bytes[0..Hasher.digest]; } else { @@ -3356,8 +3316,7 @@ pub fn allocUnsafe(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b const arguments = callframe.arguments_old(1); const size = arguments.ptr[0]; if (!size.isUInt32AsAnyInt()) { - globalThis.throwInvalidArguments("Expected a positive number", .{}); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Expected a positive number", .{}); } return JSC.JSValue.createUninitializedUint8Array(globalThis, size.toUInt64NoTruncate()); @@ -3378,15 +3337,13 @@ pub fn mmapFile(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. if (path.isString()) { const path_str = path.toSlice(globalThis, args.arena.allocator()); if (path_str.len > bun.MAX_PATH_BYTES) { - globalThis.throwInvalidArguments("Path too long", .{}); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Path too long", .{}); } const paths = &[_]string{path_str.slice()}; break :brk bun.path.joinAbsStringBuf(bun.fs.FileSystem.instance.top_level_dir, &buf, paths, .auto); } } - globalThis.throwInvalidArguments("Expected a path", .{}); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Expected a path", .{}); }; buf[path.len] = 0; @@ -3518,8 +3475,7 @@ const HashObject = struct { .DataView, => { var array_buffer = arg.asArrayBuffer(globalThis) orelse { - globalThis.throwInvalidArguments("ArrayBuffer conversion error", .{}); - return .zero; + return globalThis.throwInvalidArguments("ArrayBuffer conversion error", .{}); }; input = array_buffer.byteSlice(); }, @@ -3655,8 +3611,7 @@ const UnsafeObject = struct { ) bun.JSError!JSC.JSValue { const args = callframe.arguments_old(2).slice(); if (args.len < 1 or !args[0].isCell() or !args[0].jsType().isTypedArray()) { - globalThis.throwInvalidArguments("Expected an ArrayBuffer", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected an ArrayBuffer", .{}); } const array_buffer = JSC.ArrayBuffer.fromTypedArray(globalThis, args[0]); @@ -3704,8 +3659,7 @@ const TOMLObject = struct { var log = logger.Log.init(default_allocator); const arguments = callframe.arguments_old(1).slice(); if (arguments.len == 0 or arguments[0].isEmptyOrUndefinedOrNull()) { - globalThis.throwInvalidArguments("Expected a string to parse", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected a string to parse", .{}); } var input_slice = arguments[0].toSlice(globalThis, bun.default_allocator); @@ -3814,10 +3768,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) u8, @ptrFromInt(addr)).*; @@ -3827,10 +3780,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) u16, @ptrFromInt(addr)).*; @@ -3840,10 +3792,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) u32, @ptrFromInt(addr)).*; @@ -3853,10 +3804,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) u64, @ptrFromInt(addr)).*; @@ -3866,10 +3816,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) i8, @ptrFromInt(addr)).*; @@ -3879,10 +3828,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) i16, @ptrFromInt(addr)).*; @@ -3892,10 +3840,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) i32, @ptrFromInt(addr)).*; @@ -3905,10 +3852,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) i64, @ptrFromInt(addr)).*; @@ -3919,10 +3865,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) f32, @ptrFromInt(addr)).*; @@ -3933,10 +3878,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) f64, @ptrFromInt(addr)).*; @@ -3947,10 +3891,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) i64, @ptrFromInt(addr)).*; @@ -3961,10 +3904,9 @@ pub const FFIObject = struct { globalObject: *JSGlobalObject, _: JSValue, arguments: []const JSValue, - ) JSValue { + ) bun.JSError!JSValue { if (arguments.len == 0 or !arguments[0].isNumber()) { - globalObject.throwInvalidArguments("Expected a pointer", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected a pointer", .{}); } const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @as(usize, @intCast(arguments[1].to(i32))) else @as(usize, 0); const value = @as(*align(1) u64, @ptrFromInt(addr)).*; @@ -4492,57 +4434,43 @@ pub const JSZlib = struct { }; // This has to be `inline` due to the callframe. - inline fn getOptions(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) ?struct { JSC.Node.StringOrBuffer, ?JSValue } { + inline fn getOptions(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!struct { JSC.Node.StringOrBuffer, ?JSValue } { const arguments = callframe.arguments_old(2).slice(); const buffer_value = if (arguments.len > 0) arguments[0] else .undefined; const options_val: ?JSValue = if (arguments.len > 1 and arguments[1].isObject()) arguments[1] else if (arguments.len > 1 and !arguments[1].isUndefined()) { - globalThis.throwInvalidArguments("Expected options to be an object", .{}); - return null; + return globalThis.throwInvalidArguments("Expected options to be an object", .{}); } else null; if (JSC.Node.StringOrBuffer.fromJS(globalThis, bun.default_allocator, buffer_value)) |buffer| { return .{ buffer, options_val }; } - globalThis.throwInvalidArguments("Expected buffer to be a string or buffer", .{}); - return null; + return globalThis.throwInvalidArguments("Expected buffer to be a string or buffer", .{}); } - pub fn gzipSync( - globalThis: *JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSValue { - const buffer, const options_val = getOptions(globalThis, callframe) orelse return .zero; + pub fn gzipSync(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + const buffer, const options_val = try getOptions(globalThis, callframe); defer buffer.deinit(); return gzipOrDeflateSync(globalThis, buffer, options_val, true); } - pub fn inflateSync( - globalThis: *JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSValue { - const buffer, const options_val = getOptions(globalThis, callframe) orelse return .zero; + pub fn inflateSync(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + const buffer, const options_val = try getOptions(globalThis, callframe); defer buffer.deinit(); return gunzipOrInflateSync(globalThis, buffer, options_val, false); } - pub fn deflateSync( - globalThis: *JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSValue { - const buffer, const options_val = getOptions(globalThis, callframe) orelse return .zero; + pub fn deflateSync(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + const buffer, const options_val = try getOptions(globalThis, callframe); defer buffer.deinit(); return gzipOrDeflateSync(globalThis, buffer, options_val, false); } - pub fn gunzipSync( - globalThis: *JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSValue { - const buffer, const options_val = getOptions(globalThis, callframe) orelse return .zero; + pub fn gunzipSync(globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { + const buffer, const options_val = try getOptions(globalThis, callframe); defer buffer.deinit(); return gunzipOrInflateSync(globalThis, buffer, options_val, true); } @@ -4576,13 +4504,11 @@ pub const JSZlib = struct { if (try options_val.getTruthy(globalThis, "library")) |library_value| { if (!library_value.isString()) { - globalThis.throwInvalidArguments("Expected library to be a string", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected library to be a string", .{}); } library = Library.map.fromJS(globalThis, library_value) orelse { - globalThis.throwInvalidArguments("Expected library to be one of 'zlib' or 'libdeflate'", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected library to be one of 'zlib' or 'libdeflate'", .{}); }; } } @@ -4702,13 +4628,11 @@ pub const JSZlib = struct { if (try options_val.getTruthy(globalThis, "library")) |library_value| { if (!library_value.isString()) { - globalThis.throwInvalidArguments("Expected library to be a string", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected library to be a string", .{}); } library = Library.map.fromJS(globalThis, library_value) orelse { - globalThis.throwInvalidArguments("Expected library to be one of 'zlib' or 'libdeflate'", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected library to be one of 'zlib' or 'libdeflate'", .{}); }; } diff --git a/src/bun.js/api/JSBundler.zig b/src/bun.js/api/JSBundler.zig index c22af05941a511..45bd817209e859 100644 --- a/src/bun.js/api/JSBundler.zig +++ b/src/bun.js/api/JSBundler.zig @@ -118,20 +118,20 @@ pub const JSBundler = struct { var i: usize = 0; while (iter.next()) |plugin| : (i += 1) { if (!plugin.isObject()) { - return globalThis.throwInvalidArguments2("Expected plugin to be an object", .{}); + return globalThis.throwInvalidArguments("Expected plugin to be an object", .{}); } if (try plugin.getOptional(globalThis, "name", ZigString.Slice)) |slice| { defer slice.deinit(); if (slice.len == 0) { - return globalThis.throwInvalidArguments2("Expected plugin to have a non-empty name", .{}); + return globalThis.throwInvalidArguments("Expected plugin to have a non-empty name", .{}); } } else { - return globalThis.throwInvalidArguments2("Expected plugin to have a name", .{}); + return globalThis.throwInvalidArguments("Expected plugin to have a name", .{}); } const function = try plugin.getFunction(globalThis, "setup") orelse { - return globalThis.throwInvalidArguments2("Expected plugin to have a setup() function", .{}); + return globalThis.throwInvalidArguments("Expected plugin to have a setup() function", .{}); }; var bun_plugins: *Plugin = plugins.* orelse brk: { @@ -193,7 +193,7 @@ pub const JSBundler = struct { this.target = target; if (target != .bun and this.bytecode) { - return globalThis.throwInvalidArguments2("target must be 'bun' when bytecode is true", .{}); + return globalThis.throwInvalidArguments("target must be 'bun' when bytecode is true", .{}); } } @@ -239,7 +239,7 @@ pub const JSBundler = struct { this.format = format; if (this.bytecode and format != .cjs) { - return globalThis.throwInvalidArguments2("format must be 'cjs' when bytecode is true. Eventually we'll add esm support as well.", .{}); + return globalThis.throwInvalidArguments("format must be 'cjs' when bytecode is true. Eventually we'll add esm support as well.", .{}); } } @@ -264,7 +264,7 @@ pub const JSBundler = struct { this.minify.identifiers = syntax; } } else { - return globalThis.throwInvalidArguments2("Expected minify to be a boolean or an object", .{}); + return globalThis.throwInvalidArguments("Expected minify to be a boolean or an object", .{}); } } @@ -276,7 +276,7 @@ pub const JSBundler = struct { try this.entry_points.insert(slice.slice()); } } else { - return globalThis.throwInvalidArguments2("Expected entrypoints to be an array of strings", .{}); + return globalThis.throwInvalidArguments("Expected entrypoints to be an array of strings", .{}); } if (try config.getBooleanLoose(globalThis, "emitDCEAnnotations")) |flag| { @@ -300,7 +300,7 @@ pub const JSBundler = struct { try this.conditions.insert(slice.slice()); } } else { - return globalThis.throwInvalidArguments2("Expected conditions to be an array of strings", .{}); + return globalThis.throwInvalidArguments("Expected conditions to be an array of strings", .{}); } } @@ -403,13 +403,13 @@ pub const JSBundler = struct { this.names.asset.data = this.names.owned_asset.list.items; } } else { - return globalThis.throwInvalidArguments2("Expected naming to be a string or an object", .{}); + return globalThis.throwInvalidArguments("Expected naming to be a string or an object", .{}); } } if (try config.getOwnObject(globalThis, "define")) |define| { if (!define.isObject()) { - return globalThis.throwInvalidArguments2("define must be an object", .{}); + return globalThis.throwInvalidArguments("define must be an object", .{}); } var define_iter = JSC.JSPropertyIterator(.{ @@ -423,7 +423,7 @@ pub const JSBundler = struct { const value_type = property_value.jsType(); if (!value_type.isStringLike()) { - return globalThis.throwInvalidArguments2("define \"{s}\" must be a JSON string", .{prop}); + return globalThis.throwInvalidArguments("define \"{s}\" must be a JSON string", .{prop}); } var val = JSC.ZigString.init(""); @@ -457,7 +457,7 @@ pub const JSBundler = struct { while (loader_iter.next()) |prop| { if (!prop.hasPrefixComptime(".") or prop.length() < 2) { - return globalThis.throwInvalidArguments2("loader property names must be file extensions, such as '.txt'", .{}); + return globalThis.throwInvalidArguments("loader property names must be file extensions, such as '.txt'", .{}); } loader_values[loader_iter.i] = try loader_iter.value.toEnumFromMap( @@ -538,10 +538,9 @@ pub const JSBundler = struct { fn build( globalThis: *JSC.JSGlobalObject, arguments: []const JSC.JSValue, - ) JSC.JSValue { + ) bun.JSError!JSC.JSValue { if (arguments.len == 0 or !arguments[0].isObject()) { - globalThis.throwInvalidArguments("Expected a config object to be passed to Bun.build", .{}); - return .undefined; + return globalThis.throwInvalidArguments("Expected a config object to be passed to Bun.build", .{}); } var plugins: ?*Plugin = null; diff --git a/src/bun.js/api/JSTranspiler.zig b/src/bun.js/api/JSTranspiler.zig index dea18decda916b..2716bc3968f5a5 100644 --- a/src/bun.js/api/JSTranspiler.zig +++ b/src/bun.js/api/JSTranspiler.zig @@ -325,8 +325,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std }; if (!object.isObject()) { - globalObject.throwInvalidArguments("Expected an object", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("Expected an object", .{}); } if (try object.getTruthy(globalObject, "define")) |define| { @@ -336,8 +335,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std } if (!define.isObject()) { - globalObject.throwInvalidArguments("define must be an object", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("define must be an object", .{}); } var define_iter = JSC.JSPropertyIterator(.{ @@ -358,8 +356,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std const value_type = property_value.jsType(); if (!value_type.isStringLike()) { - globalObject.throwInvalidArguments("define \"{s}\" must be a JSON string", .{prop}); - return error.JSError; + return globalObject.throwInvalidArguments("define \"{s}\" must be a JSON string", .{prop}); } names[define_iter.i] = prop.toOwnedSlice(allocator) catch unreachable; @@ -399,8 +396,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std var i: usize = 0; while (iter.next()) |entry| { if (!entry.jsType().isStringLike()) { - globalObject.throwInvalidArguments("external must be a string or string[]", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("external must be a string or string[]", .{}); } var zig_str = JSC.ZigString.init(""); @@ -412,8 +408,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std transpiler.transform.external = externals[0..i]; } else { - globalObject.throwInvalidArguments("external must be a string or string[]", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("external must be a string or string[]", .{}); } } } @@ -421,8 +416,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std if (try object.get(globalThis, "loader")) |loader| { if (try Loader.fromJS(globalThis, loader)) |resolved| { if (!resolved.isJavaScriptLike()) { - globalObject.throwInvalidArguments("only JavaScript-like loaders supported for now", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("only JavaScript-like loaders supported for now", .{}); } transpiler.default_loader = resolved; @@ -443,8 +437,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std defer out.deref(); if (kind.isArray()) { - globalObject.throwInvalidArguments("tsconfig must be a string or object", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("tsconfig must be a string or object", .{}); } if (!kind.isStringLike()) { @@ -484,8 +477,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std const kind = macros.jsType(); const is_object = kind.isObject(); if (!(kind.isStringLike() or is_object)) { - globalObject.throwInvalidArguments("macro must be an object", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("macro must be an object", .{}); } var out = bun.String.empty; @@ -545,8 +537,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std transpiler.minify_identifiers = syntax; } } else { - globalObject.throwInvalidArguments("Expected minify to be a boolean or an object", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("Expected minify to be a boolean or an object", .{}); } } @@ -561,8 +552,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std if (options.SourceMapOption.Map.fromJS(globalObject, flag)) |source| { transpiler.transform.source_map = source.toAPI(); } else { - globalObject.throwInvalidArguments("sourcemap must be one of \"inline\", \"linked\", \"external\", or \"none\"", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("sourcemap must be one of \"inline\", \"linked\", \"external\", or \"none\"", .{}); } } } @@ -583,8 +573,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std if (try object.getTruthy(globalThis, "exports")) |exports| { if (!exports.isObject()) { - globalObject.throwInvalidArguments("exports must be an object", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("exports must be an object", .{}); } var replacements = Runtime.Features.ReplaceableExport.Map{}; @@ -592,8 +581,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std if (try exports.getTruthy(globalThis, "eliminate")) |eliminate| { if (!eliminate.jsType().isArray()) { - globalObject.throwInvalidArguments("exports.eliminate must be an array", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("exports.eliminate must be an array", .{}); } var total_name_buf_len: u32 = 0; @@ -620,8 +608,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std const str = value.getZigString(globalThis); if (str.len == 0) continue; const name = std.fmt.bufPrint(buf.items.ptr[buf.items.len..buf.capacity], "{}", .{str}) catch { - globalObject.throwInvalidArguments("Error reading exports.eliminate. TODO: utf-16", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("Error reading exports.eliminate. TODO: utf-16", .{}); }; buf.items.len += name.len; if (name.len > 0) { @@ -634,8 +621,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std if (try exports.getTruthy(globalThis, "replace")) |replace| { if (!replace.isObject()) { - globalObject.throwInvalidArguments("replace must be an object", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("replace must be an object", .{}); } var iter = JSC.JSPropertyIterator(.{ @@ -664,9 +650,8 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std const key = try key_.toOwnedSlice(bun.default_allocator); if (!JSLexer.isIdentifier(key)) { - globalObject.throwInvalidArguments("\"{s}\" is not a valid ECMAScript identifier", .{key}); bun.default_allocator.free(key); - return error.JSError; + return globalObject.throwInvalidArguments("\"{s}\" is not a valid ECMAScript identifier", .{key}); } const entry = replacements.getOrPutAssumeCapacity(key); @@ -684,9 +669,8 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std const replacement_name = slice.slice(); if (!JSLexer.isIdentifier(replacement_name)) { - globalObject.throwInvalidArguments("\"{s}\" is not a valid ECMAScript identifier", .{replacement_name}); slice.deinit(); - return error.JSError; + return globalObject.throwInvalidArguments("\"{s}\" is not a valid ECMAScript identifier", .{replacement_name}); } entry.value_ptr.* = .{ @@ -699,8 +683,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std } } - globalObject.throwInvalidArguments("exports.replace values can only be string, null, undefined, number or boolean", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("exports.replace values can only be string, null, undefined, number or boolean", .{}); } } } @@ -713,8 +696,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std if (logger.Log.Level.Map.fromJS(globalObject, logLevel)) |level| { transpiler.log.level = level; } else { - globalObject.throwInvalidArguments("logLevel must be one of \"verbose\", \"debug\", \"info\", \"warn\", or \"error\"", .{}); - return error.JSError; + return globalObject.throwInvalidArguments("logLevel must be one of \"verbose\", \"debug\", \"info\", \"warn\", or \"error\"", .{}); } } @@ -1156,11 +1138,7 @@ fn namedImportsToJS( return array; } -pub fn scanImports( - this: *Transpiler, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { +pub fn scanImports(this: *Transpiler, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { const arguments = callframe.arguments_old(2); var args = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); defer args.deinit(); @@ -1189,8 +1167,7 @@ pub fn scanImports( } if (!loader.isJavaScriptLike()) { - globalThis.throwInvalidArguments("Only JavaScript-like files support this fast path", .{}); - return .zero; + return globalThis.throwInvalidArguments("Only JavaScript-like files support this fast path", .{}); } var arena = Mimalloc.Arena.init() catch unreachable; diff --git a/src/bun.js/api/bun/dns_resolver.zig b/src/bun.js/api/bun/dns_resolver.zig index 2e1bb7e5da3132..b1300f6b975c2d 100644 --- a/src/bun.js/api/bun/dns_resolver.zig +++ b/src/bun.js/api/bun/dns_resolver.zig @@ -1648,8 +1648,7 @@ pub const InternalDNS = struct { if (hostname_or_url.isString()) { hostname_slice = hostname_or_url.toSlice(globalThis, bun.default_allocator); } else { - globalThis.throwInvalidArguments("hostname must be a string", .{}); - return .zero; + return globalThis.throwInvalidArguments("hostname must be a string", .{}); } const hostname_z = bun.default_allocator.dupeZ(u8, hostname_slice.slice()) catch { diff --git a/src/bun.js/api/bun/h2_frame_parser.zig b/src/bun.js/api/bun/h2_frame_parser.zig index 1b6e8b85d612a8..3c5fd21b8e59ff 100644 --- a/src/bun.js/api/bun/h2_frame_parser.zig +++ b/src/bun.js/api/bun/h2_frame_parser.zig @@ -593,7 +593,7 @@ const Handlers = struct { }; if (opts.isEmptyOrUndefinedOrNull() or opts.isBoolean() or !opts.isObject()) { - return globalObject.throwInvalidArguments2("Expected \"handlers\" to be an object", .{}); + return globalObject.throwInvalidArguments("Expected \"handlers\" to be an object", .{}); } const pairs = .{ @@ -616,7 +616,7 @@ const Handlers = struct { inline for (pairs) |pair| { if (try opts.getTruthy(globalObject, pair.@"1")) |callback_value| { if (!callback_value.isCell() or !callback_value.isCallable(globalObject.vm())) { - return globalObject.throwInvalidArguments2("Expected \"{s}\" callback to be a function", .{pair[1]}); + return globalObject.throwInvalidArguments("Expected \"{s}\" callback to be a function", .{pair[1]}); } @field(handlers, pair.@"0") = callback_value; @@ -625,7 +625,7 @@ const Handlers = struct { if (opts.fastGet(globalObject, .@"error")) |callback_value| { if (!callback_value.isCell() or !callback_value.isCallable(globalObject.vm())) { - return globalObject.throwInvalidArguments2("Expected \"error\" callback to be a function", .{}); + return globalObject.throwInvalidArguments("Expected \"error\" callback to be a function", .{}); } handlers.onError = callback_value; @@ -633,16 +633,16 @@ const Handlers = struct { // onWrite is required for duplex support or if more than 1 parser is attached to the same socket (unliked) if (handlers.onWrite == .zero) { - return globalObject.throwInvalidArguments2("Expected at least \"write\" callback", .{}); + return globalObject.throwInvalidArguments("Expected at least \"write\" callback", .{}); } if (try opts.getTruthy(globalObject, "binaryType")) |binary_type_value| { if (!binary_type_value.isString()) { - return globalObject.throwInvalidArguments2("Expected \"binaryType\" to be a string", .{}); + return globalObject.throwInvalidArguments("Expected \"binaryType\" to be a string", .{}); } handlers.binary_type = try BinaryType.fromJSValue(globalObject, binary_type_value) orelse { - return globalObject.throwInvalidArguments2("Expected 'binaryType' to be 'ArrayBuffer', 'Uint8Array', or 'Buffer'", .{}); + return globalObject.throwInvalidArguments("Expected 'binaryType' to be 'ArrayBuffer', 'Uint8Array', or 'Buffer'", .{}); }; } @@ -3723,7 +3723,7 @@ pub const H2FrameParser = struct { const options = args_list.ptr[0]; if (options.isEmptyOrUndefinedOrNull() or options.isBoolean() or !options.isObject()) { - return globalObject.throwInvalidArguments2("expected options as argument", .{}); + return globalObject.throwInvalidArguments("expected options as argument", .{}); } const context_obj = try options.get(globalObject, "context") orelse { diff --git a/src/bun.js/api/bun/socket.zig b/src/bun.js/api/bun/socket.zig index a7399b98a84913..2865d920744030 100644 --- a/src/bun.js/api/bun/socket.zig +++ b/src/bun.js/api/bun/socket.zig @@ -225,7 +225,7 @@ const Handlers = struct { }; if (opts.isEmptyOrUndefinedOrNull() or opts.isBoolean() or !opts.isObject()) { - return globalObject.throwInvalidArguments2("Expected \"socket\" to be an object", .{}); + return globalObject.throwInvalidArguments("Expected \"socket\" to be an object", .{}); } const pairs = .{ @@ -242,7 +242,7 @@ const Handlers = struct { inline for (pairs) |pair| { if (try opts.getTruthyComptime(globalObject, pair.@"1")) |callback_value| { if (!callback_value.isCell() or !callback_value.isCallable(globalObject.vm())) { - return globalObject.throwInvalidArguments2("Expected \"{s}\" callback to be a function", .{pair[1]}); + return globalObject.throwInvalidArguments("Expected \"{s}\" callback to be a function", .{pair[1]}); } @field(handlers, pair.@"0") = callback_value; @@ -250,16 +250,16 @@ const Handlers = struct { } if (handlers.onData == .zero and handlers.onWritable == .zero) { - return globalObject.throwInvalidArguments2("Expected at least \"data\" or \"drain\" callback", .{}); + return globalObject.throwInvalidArguments("Expected at least \"data\" or \"drain\" callback", .{}); } if (try opts.getTruthy(globalObject, "binaryType")) |binary_type_value| { if (!binary_type_value.isString()) { - return globalObject.throwInvalidArguments2("Expected \"binaryType\" to be a string", .{}); + return globalObject.throwInvalidArguments("Expected \"binaryType\" to be a string", .{}); } handlers.binary_type = try BinaryType.fromJSValue(globalObject, binary_type_value) orelse { - return globalObject.throwInvalidArguments2("Expected 'binaryType' to be 'ArrayBuffer', 'Uint8Array', or 'Buffer'", .{}); + return globalObject.throwInvalidArguments("Expected 'binaryType' to be 'ArrayBuffer', 'Uint8Array', or 'Buffer'", .{}); }; } @@ -341,7 +341,7 @@ pub const SocketConfig = struct { if (try opts.getTruthy(globalObject, "unix")) |unix_socket| { if (!unix_socket.isString()) { - return globalObject.throwInvalidArguments2("Expected \"unix\" to be a string", .{}); + return globalObject.throwInvalidArguments("Expected \"unix\" to be a string", .{}); } hostname_or_unix = unix_socket.getZigString(globalObject).toSlice(bun.default_allocator); @@ -365,7 +365,7 @@ pub const SocketConfig = struct { if (try opts.getTruthy(globalObject, "hostname") orelse try opts.getTruthy(globalObject, "host")) |hostname| { if (!hostname.isString()) { - return globalObject.throwInvalidArguments2("Expected \"hostname\" to be a string", .{}); + return globalObject.throwInvalidArguments("Expected \"hostname\" to be a string", .{}); } var port_value = try opts.get(globalObject, "port") orelse JSValue.zero; @@ -381,7 +381,7 @@ pub const SocketConfig = struct { } if (port_value.isEmptyOrUndefinedOrNull()) { - return globalObject.throwInvalidArguments2("Expected \"port\" to be a number between 0 and 65535", .{}); + return globalObject.throwInvalidArguments("Expected \"port\" to be a number between 0 and 65535", .{}); } const porti32 = port_value.coerceToInt32(globalObject); @@ -390,13 +390,13 @@ pub const SocketConfig = struct { } if (porti32 < 0 or porti32 > 65535) { - return globalObject.throwInvalidArguments2("Expected \"port\" to be a number between 0 and 65535", .{}); + return globalObject.throwInvalidArguments("Expected \"port\" to be a number between 0 and 65535", .{}); } port = @intCast(porti32); if (hostname_or_unix.len == 0) { - return globalObject.throwInvalidArguments2("Expected \"hostname\" to be a non-empty string", .{}); + return globalObject.throwInvalidArguments("Expected \"hostname\" to be a non-empty string", .{}); } if (hostname_or_unix.len > 0) { @@ -405,10 +405,10 @@ pub const SocketConfig = struct { } if (hostname_or_unix.len == 0) { - return globalObject.throwInvalidArguments2("Expected \"unix\" or \"hostname\" to be a non-empty string", .{}); + return globalObject.throwInvalidArguments("Expected \"unix\" or \"hostname\" to be a non-empty string", .{}); } - return globalObject.throwInvalidArguments2("Expected either \"hostname\" or \"unix\"", .{}); + return globalObject.throwInvalidArguments("Expected either \"hostname\" or \"unix\"", .{}); } errdefer hostname_or_unix.deinit(); @@ -577,8 +577,7 @@ pub const Listener = struct { pub fn listen(globalObject: *JSC.JSGlobalObject, opts: JSValue) bun.JSError!JSValue { log("listen", .{}); if (opts.isEmptyOrUndefinedOrNull() or opts.isBoolean() or !opts.isObject()) { - globalObject.throwInvalidArguments("Expected object", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected object", .{}); } const vm = JSC.VirtualMachine.get(); @@ -637,9 +636,8 @@ pub const Listener = struct { this.listener = .{ // we need to add support for the backlog parameter on listen here we use the default value of nodejs .namedPipe = WindowsNamedPipeListeningContext.listen(globalObject, pipe_name, 511, ssl, this) catch { - globalObject.throwInvalidArguments("Failed to listen at {s}", .{pipe_name}); this.deinit(); - return .zero; + return globalObject.throwInvalidArguments("Failed to listen at {s}", .{pipe_name}); }, }; @@ -882,12 +880,10 @@ pub const Listener = struct { pub fn addServerName(this: *Listener, global: *JSC.JSGlobalObject, hostname: JSValue, tls: JSValue) bun.JSError!JSValue { if (!this.ssl) { - global.throwInvalidArguments("addServerName requires SSL support", .{}); - return .zero; + return global.throwInvalidArguments("addServerName requires SSL support", .{}); } if (!hostname.isString()) { - global.throwInvalidArguments("hostname pattern expects a string", .{}); - return .zero; + return global.throwInvalidArguments("hostname pattern expects a string", .{}); } const host_str = hostname.toSlice( global, @@ -897,8 +893,7 @@ pub const Listener = struct { const server_name = bun.default_allocator.dupeZ(u8, host_str.slice()) catch bun.outOfMemory(); defer bun.default_allocator.free(server_name); if (server_name.len == 0) { - global.throwInvalidArguments("hostname pattern cannot be empty", .{}); - return .zero; + return global.throwInvalidArguments("hostname pattern cannot be empty", .{}); } if (try JSC.API.ServerConfig.SSLConfig.fromJS(JSC.VirtualMachine.get(), global, tls)) |ssl_config| { @@ -1040,8 +1035,7 @@ pub const Listener = struct { pub fn connect(globalObject: *JSC.JSGlobalObject, opts: JSValue) bun.JSError!JSValue { if (opts.isEmptyOrUndefinedOrNull() or opts.isBoolean() or !opts.isObject()) { - globalObject.throwInvalidArguments("Expected options object", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected options object", .{}); } const vm = globalObject.bunVM(); diff --git a/src/bun.js/api/bun/spawn/stdio.zig b/src/bun.js/api/bun/spawn/stdio.zig index 320118d72f1e5e..d9197ba862025d 100644 --- a/src/bun.js/api/bun/spawn/stdio.zig +++ b/src/bun.js/api/bun/spawn/stdio.zig @@ -290,19 +290,14 @@ pub const Stdio = union(enum) { }; } - pub fn extract( - out_stdio: *Stdio, - globalThis: *JSC.JSGlobalObject, - i: u32, - value: JSValue, - ) bool { + pub fn extract(out_stdio: *Stdio, globalThis: *JSC.JSGlobalObject, i: u32, value: JSValue) bun.JSError!void { switch (value) { // undefined: default - .undefined, .zero => return true, + .undefined, .zero => return, // null: ignore .null => { out_stdio.* = Stdio{ .ignore = {} }; - return true; + return; }, else => {}, } @@ -318,58 +313,47 @@ pub const Stdio = union(enum) { } else if (str.eqlComptime("ipc")) { out_stdio.* = Stdio{ .ipc = {} }; } else { - globalThis.throwInvalidArguments("stdio must be an array of 'inherit', 'pipe', 'ignore', Bun.file(pathOrFd), number, or null", .{}); - return false; + return globalThis.throwInvalidArguments("stdio must be an array of 'inherit', 'pipe', 'ignore', Bun.file(pathOrFd), number, or null", .{}); } - - return true; + return; } else if (value.isNumber()) { const fd = value.asFileDescriptor(); const file_fd = bun.uvfdcast(fd); if (file_fd < 0) { - globalThis.throwInvalidArguments("file descriptor must be a positive integer", .{}); - return false; + return globalThis.throwInvalidArguments("file descriptor must be a positive integer", .{}); } if (file_fd >= std.math.maxInt(i32)) { var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; - globalThis.throwInvalidArguments("file descriptor must be a valid integer, received: {}", .{ - value.toFmt(&formatter), - }); - return false; + return globalThis.throwInvalidArguments("file descriptor must be a valid integer, received: {}", .{value.toFmt(&formatter)}); } switch (bun.FDTag.get(fd)) { .stdin => { if (i == 1 or i == 2) { - globalThis.throwInvalidArguments("stdin cannot be used for stdout or stderr", .{}); - return false; + return globalThis.throwInvalidArguments("stdin cannot be used for stdout or stderr", .{}); } out_stdio.* = Stdio{ .inherit = {} }; - return true; + return; }, - .stdout, .stderr => |tag| { if (i == 0) { - globalThis.throwInvalidArguments("stdout and stderr cannot be used for stdin", .{}); - return false; + return globalThis.throwInvalidArguments("stdout and stderr cannot be used for stdin", .{}); } - if (i == 1 and tag == .stdout) { out_stdio.* = .{ .inherit = {} }; - return true; + return; } else if (i == 2 and tag == .stderr) { out_stdio.* = .{ .inherit = {} }; - return true; + return; } }, else => {}, } out_stdio.* = Stdio{ .fd = fd }; - - return true; + return; } else if (value.as(JSC.WebCore.Blob)) |blob| { return out_stdio.extractBlob(globalThis, .{ .Blob = blob.dupe() }, i); } else if (value.as(JSC.WebCore.Request)) |req| { @@ -388,16 +372,15 @@ pub const Stdio = union(enum) { switch (req.ptr) { .File, .Blob => { globalThis.throwTODO("Support fd/blob backed ReadableStream in spawn stdin. See https://github.com/oven-sh/bun/issues/8049") catch {}; - return false; + return error.JSError; }, .Direct, .JavaScript, .Bytes => { // out_stdio.* = .{ .connect = req }; globalThis.throwTODO("Re-enable ReadableStream support in spawn stdin. ") catch {}; - return false; + return error.JSError; }, .Invalid => { - globalThis.throwInvalidArguments("ReadableStream is in invalid state.", .{}); - return false; + return globalThis.throwInvalidArguments("ReadableStream is in invalid state.", .{}); }, } } @@ -405,7 +388,7 @@ pub const Stdio = union(enum) { // Change in Bun v1.0.34: don't throw for empty ArrayBuffer if (array_buffer.byteSlice().len == 0) { out_stdio.* = .{ .ignore = {} }; - return true; + return; } out_stdio.* = .{ @@ -414,20 +397,13 @@ pub const Stdio = union(enum) { .held = JSC.Strong.create(array_buffer.value, globalThis), }, }; - - return true; + return; } - globalThis.throwInvalidArguments("stdio must be an array of 'inherit', 'ignore', or null", .{}); - return false; + return globalThis.throwInvalidArguments("stdio must be an array of 'inherit', 'ignore', or null", .{}); } - pub fn extractBlob( - stdio: *Stdio, - globalThis: *JSC.JSGlobalObject, - blob: JSC.WebCore.AnyBlob, - i: u32, - ) bool { + pub fn extractBlob(stdio: *Stdio, globalThis: *JSC.JSGlobalObject, blob: JSC.WebCore.AnyBlob, i: u32) bun.JSError!void { const fd = bun.stdio(i); if (blob.needsToReadFile()) { @@ -439,15 +415,13 @@ pub const Stdio = union(enum) { switch (bun.FDTag.get(i)) { .stdin => { if (i == 1 or i == 2) { - globalThis.throwInvalidArguments("stdin cannot be used for stdout or stderr", .{}); - return false; + return globalThis.throwInvalidArguments("stdin cannot be used for stdout or stderr", .{}); } }, .stdout, .stderr => { if (i == 0) { - globalThis.throwInvalidArguments("stdout and stderr cannot be used for stdin", .{}); - return false; + return globalThis.throwInvalidArguments("stdout and stderr cannot be used for stdin", .{}); } }, else => {}, @@ -456,26 +430,25 @@ pub const Stdio = union(enum) { stdio.* = Stdio{ .fd = store.data.file.pathlike.fd }; } - return true; + return; } stdio.* = .{ .path = store.data.file.pathlike.path }; - return true; + return; } } if (i == 1 or i == 2) { - globalThis.throwInvalidArguments("Blobs are immutable, and cannot be used for stdout/stderr", .{}); - return false; + return globalThis.throwInvalidArguments("Blobs are immutable, and cannot be used for stdout/stderr", .{}); } // Instead of writing an empty blob, lets just make it /dev/null if (blob.fastSize() == 0) { stdio.* = .{ .ignore = {} }; - return true; + return; } stdio.* = .{ .blob = blob }; - return true; + return; } }; diff --git a/src/bun.js/api/bun/subprocess.zig b/src/bun.js/api/bun/subprocess.zig index 53c1ccc912e93f..8686fb33f569e4 100644 --- a/src/bun.js/api/bun/subprocess.zig +++ b/src/bun.js/api/bun/subprocess.zig @@ -625,18 +625,15 @@ pub const Subprocess = struct { // This matches node behavior, minus some details with the error messages: https://gist.github.com/Jarred-Sumner/23ba38682bf9d84dff2f67eb35c42ab6 if (std.math.isInf(sig64) or @trunc(sig64) != sig64) { - globalThis.throwInvalidArguments("Unknown signal", .{}); - return .zero; + return globalThis.throwInvalidArguments("Unknown signal", .{}); } if (sig64 < 0) { - globalThis.throwInvalidArguments("Invalid signal: must be >= 0", .{}); - return .zero; + return globalThis.throwInvalidArguments("Invalid signal: must be >= 0", .{}); } if (sig64 > 31) { - globalThis.throwInvalidArguments("Invalid signal: must be < 32", .{}); - return .zero; + return globalThis.throwInvalidArguments("Invalid signal: must be < 32", .{}); } break :brk @intFromFloat(sig64); @@ -647,8 +644,7 @@ pub const Subprocess = struct { const signal_code = try arguments.ptr[0].toEnum(globalThis, "signal", SignalCode); break :brk @intFromEnum(signal_code); } else if (!arguments.ptr[0].isEmptyOrUndefinedOrNull()) { - globalThis.throwInvalidArguments("Invalid signal: must be a string or an integer", .{}); - return .zero; + return globalThis.throwInvalidArguments("Invalid signal: must be a string or an integer", .{}); } break :brk SignalCode.default; @@ -726,8 +722,7 @@ pub const Subprocess = struct { }); if (callFrame.argumentsCount() == 0) { - global.throwInvalidArguments("Subprocess.send() requires one argument", .{}); - return .zero; + return global.throwInvalidArguments("Subprocess.send() requires one argument", .{}); } const value = callFrame.argument(0); @@ -1724,8 +1719,7 @@ pub const Subprocess = struct { { if (args.isEmptyOrUndefinedOrNull()) { - globalThis.throwInvalidArguments("cmd must be an array", .{}); - return .zero; + return globalThis.throwInvalidArguments("cmd must be an array", .{}); } const args_type = args.jsType(); @@ -1733,13 +1727,11 @@ pub const Subprocess = struct { cmd_value = args; args = secondaryArgsValue orelse JSValue.zero; } else if (!args.isObject()) { - globalThis.throwInvalidArguments("cmd must be an array", .{}); - return .zero; + return globalThis.throwInvalidArguments("cmd must be an array", .{}); } else if (try args.getTruthy(globalThis, "cmd")) |cmd_value_| { cmd_value = cmd_value_; } else { - globalThis.throwInvalidArguments("cmd must be an array", .{}); - return .zero; + return globalThis.throwInvalidArguments("cmd must be an array", .{}); } if (args.isObject()) { @@ -1775,13 +1767,11 @@ pub const Subprocess = struct { }; if (cmd_value.isEmptyOrUndefinedOrNull()) { - globalThis.throwInvalidArguments("cmd must be an array of strings", .{}); - return .zero; + return globalThis.throwInvalidArguments("cmd must be an array of strings", .{}); } if (cmds_array.len == 0) { - globalThis.throwInvalidArguments("cmd must not be empty", .{}); - return .zero; + return globalThis.throwInvalidArguments("cmd must not be empty", .{}); } { @@ -1792,8 +1782,7 @@ pub const Subprocess = struct { if (argv0 == null) { var path_buf: bun.PathBuffer = undefined; const resolved = Which.which(&path_buf, PATH, cwd, arg0.slice()) orelse { - globalThis.throwInvalidArguments("Executable not found in $PATH: \"{s}\"", .{arg0.slice()}); - return .zero; + return globalThis.throwInvalidArguments("Executable not found in $PATH: \"{s}\"", .{arg0.slice()}); }; argv0 = allocator.dupeZ(u8, resolved) catch { globalThis.throwOutOfMemory(); @@ -1802,8 +1791,7 @@ pub const Subprocess = struct { } else { var path_buf: bun.PathBuffer = undefined; const resolved = Which.which(&path_buf, PATH, cwd, bun.sliceTo(argv0.?, 0)) orelse { - globalThis.throwInvalidArguments("Executable not found in $PATH: \"{s}\"", .{arg0.slice()}); - return .zero; + return globalThis.throwInvalidArguments("Executable not found in $PATH: \"{s}\"", .{arg0.slice()}); }; argv0 = allocator.dupeZ(u8, resolved) catch { globalThis.throwOutOfMemory(); @@ -1831,8 +1819,7 @@ pub const Subprocess = struct { } if (argv.items.len == 0) { - globalThis.throwInvalidArguments("cmd must be an array of strings", .{}); - return .zero; + return globalThis.throwInvalidArguments("cmd must be an array of strings", .{}); } } @@ -1846,9 +1833,9 @@ pub const Subprocess = struct { if (mode_val.isString()) { break :ipc_mode IPC.Mode.fromJS(globalThis, mode_val) orelse { if (!globalThis.hasException()) { - globalThis.throwInvalidArguments("serialization must be \"json\" or \"advanced\"", .{}); + return globalThis.throwInvalidArguments("serialization must be \"json\" or \"advanced\"", .{}); } - return .zero; + return error.JSError; }; } else { if (!globalThis.hasException()) { @@ -1875,8 +1862,7 @@ pub const Subprocess = struct { if (try args.getTruthy(globalThis, "onDisconnect")) |onDisconnect_| { if (!onDisconnect_.isCell() or !onDisconnect_.isCallable(globalThis.vm())) { - globalThis.throwInvalidArguments("onDisconnect must be a function or undefined", .{}); - return .zero; + return globalThis.throwInvalidArguments("onDisconnect must be a function or undefined", .{}); } on_disconnect_callback = if (comptime is_sync) @@ -1887,8 +1873,7 @@ pub const Subprocess = struct { if (try args.getTruthy(globalThis, "onExit")) |onExit_| { if (!onExit_.isCell() or !onExit_.isCallable(globalThis.vm())) { - globalThis.throwInvalidArguments("onExit must be a function or undefined", .{}); - return .zero; + return globalThis.throwInvalidArguments("onExit must be a function or undefined", .{}); } on_exit_callback = if (comptime is_sync) @@ -1899,8 +1884,7 @@ pub const Subprocess = struct { if (try args.getTruthy(globalThis, "env")) |object| { if (!object.isObject()) { - globalThis.throwInvalidArguments("env must be an object", .{}); - return .zero; + return globalThis.throwInvalidArguments("env must be an object", .{}); } override_env = true; @@ -1919,8 +1903,7 @@ pub const Subprocess = struct { var stdio_iter = stdio_val.arrayIterator(globalThis); var i: u32 = 0; while (stdio_iter.next()) |value| : (i += 1) { - if (!stdio[i].extract(globalThis, i, value)) - return .undefined; + try stdio[i].extract(globalThis, i, value); if (i == 2) break; } @@ -1928,9 +1911,7 @@ pub const Subprocess = struct { while (stdio_iter.next()) |value| : (i += 1) { var new_item: Stdio = undefined; - if (!new_item.extract(globalThis, i, value)) { - return .undefined; - } + try new_item.extract(globalThis, i, value); const opt = switch (new_item.asSpawnOption(i)) { .result => |opt| opt, @@ -1947,24 +1928,20 @@ pub const Subprocess = struct { }; } } else { - globalThis.throwInvalidArguments("stdio must be an array", .{}); - return .zero; + return globalThis.throwInvalidArguments("stdio must be an array", .{}); } } } else { if (try args.get(globalThis, "stdin")) |value| { - if (!stdio[0].extract(globalThis, 0, value)) - return .zero; + try stdio[0].extract(globalThis, 0, value); } if (try args.get(globalThis, "stderr")) |value| { - if (!stdio[2].extract(globalThis, 2, value)) - return .zero; + try stdio[2].extract(globalThis, 2, value); } if (try args.get(globalThis, "stdout")) |value| { - if (!stdio[1].extract(globalThis, 1, value)) - return .zero; + try stdio[1].extract(globalThis, 1, value); } } diff --git a/src/bun.js/api/bun/udp_socket.zig b/src/bun.js/api/bun/udp_socket.zig index f7e41b19598dad..6e330048a48e0d 100644 --- a/src/bun.js/api/bun/udp_socket.zig +++ b/src/bun.js/api/bun/udp_socket.zig @@ -124,13 +124,13 @@ pub const UDPSocketConfig = struct { pub fn fromJS(globalThis: *JSGlobalObject, options: JSValue) bun.JSError!This { if (options.isEmptyOrUndefinedOrNull() or !options.isObject()) { - return globalThis.throwInvalidArguments2("Expected an object", .{}); + return globalThis.throwInvalidArguments("Expected an object", .{}); } const hostname = brk: { if (try options.getTruthy(globalThis, "hostname")) |value| { if (!value.isString()) { - return globalThis.throwInvalidArguments2("Expected \"hostname\" to be a string", .{}); + return globalThis.throwInvalidArguments("Expected \"hostname\" to be a string", .{}); } const str = value.toBunString(globalThis); defer str.deref(); @@ -145,7 +145,7 @@ pub const UDPSocketConfig = struct { if (try options.getTruthy(globalThis, "port")) |value| { const number = value.coerceToInt32(globalThis); if (number < 0 or number > 0xffff) { - return globalThis.throwInvalidArguments2("Expected \"port\" to be an integer between 0 and 65535", .{}); + return globalThis.throwInvalidArguments("Expected \"port\" to be an integer between 0 and 65535", .{}); } break :brk @intCast(number); } else { @@ -160,23 +160,23 @@ pub const UDPSocketConfig = struct { if (try options.getTruthy(globalThis, "socket")) |socket| { if (!socket.isObject()) { - return globalThis.throwInvalidArguments2("Expected \"socket\" to be an object", .{}); + return globalThis.throwInvalidArguments("Expected \"socket\" to be an object", .{}); } if (try options.getTruthy(globalThis, "binaryType")) |value| { if (!value.isString()) { - return globalThis.throwInvalidArguments2("Expected \"socket.binaryType\" to be a string", .{}); + return globalThis.throwInvalidArguments("Expected \"socket.binaryType\" to be a string", .{}); } config.binary_type = try JSC.BinaryType.fromJSValue(globalThis, value) orelse { - return globalThis.throwInvalidArguments2("Expected \"socket.binaryType\" to be 'arraybuffer', 'uint8array', or 'buffer'", .{}); + return globalThis.throwInvalidArguments("Expected \"socket.binaryType\" to be 'arraybuffer', 'uint8array', or 'buffer'", .{}); }; } inline for (handlers) |handler| { if (try socket.getTruthyComptime(globalThis, handler.@"0")) |value| { if (!value.isCell() or !value.isCallable(globalThis.vm())) { - return globalThis.throwInvalidArguments2("Expected \"socket.{s}\" to be a function", .{handler.@"0"}); + return globalThis.throwInvalidArguments("Expected \"socket.{s}\" to be a function", .{handler.@"0"}); } @field(config, handler.@"1") = value; } @@ -193,19 +193,19 @@ pub const UDPSocketConfig = struct { if (try options.getTruthy(globalThis, "connect")) |connect| { if (!connect.isObject()) { - return globalThis.throwInvalidArguments2("Expected \"connect\" to be an object", .{}); + return globalThis.throwInvalidArguments("Expected \"connect\" to be an object", .{}); } const connect_host_js = try connect.getTruthy(globalThis, "hostname") orelse { - return globalThis.throwInvalidArguments2("Expected \"connect.hostname\" to be a string", .{}); + return globalThis.throwInvalidArguments("Expected \"connect.hostname\" to be a string", .{}); }; if (!connect_host_js.isString()) { - return globalThis.throwInvalidArguments2("Expected \"connect.hostname\" to be a string", .{}); + return globalThis.throwInvalidArguments("Expected \"connect.hostname\" to be a string", .{}); } const connect_port_js = try connect.getTruthy(globalThis, "port") orelse { - return globalThis.throwInvalidArguments2("Expected \"connect.port\" to be an integer", .{}); + return globalThis.throwInvalidArguments("Expected \"connect.port\" to be an integer", .{}); }; const connect_port = connect_port_js.coerceToInt32(globalThis); @@ -362,8 +362,7 @@ pub const UDPSocket = struct { } const arguments = callframe.arguments_old(1); if (arguments.len != 1) { - globalThis.throwInvalidArguments("Expected 1 argument, got {}", .{arguments.len}); - return .zero; + return globalThis.throwInvalidArguments("Expected 1 argument, got {}", .{arguments.len}); } const arg = arguments.ptr[0]; @@ -374,8 +373,7 @@ pub const UDPSocket = struct { const array_len = arg.getLength(globalThis); if (this.connect_info == null and array_len % 3 != 0) { - globalThis.throwInvalidArguments("Expected 3 arguments for each packet", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected 3 arguments for each packet", .{}); } const len = if (this.connect_info == null) array_len / 3 else array_len; @@ -395,8 +393,7 @@ pub const UDPSocket = struct { var port: JSValue = .zero; while (iter.next()) |val| : (i += 1) { if (i >= array_len) { - globalThis.throwInvalidArguments("Mismatch between array length property and number of items", .{}); - return .zero; + return globalThis.throwInvalidArguments("Mismatch between array length property and number of items", .{}); } const slice_idx = if (this.connect_info == null) i / 3 else i; if (this.connect_info != null or i % 3 == 0) { @@ -406,8 +403,7 @@ pub const UDPSocket = struct { } else if (val.isString()) { break :brk val.toString(globalThis).toSlice(globalThis, alloc).slice(); } else { - globalThis.throwInvalidArguments("Expected ArrayBufferView or string as payload", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected ArrayBufferView or string as payload", .{}); } }; payloads[slice_idx] = slice.ptr; @@ -423,15 +419,13 @@ pub const UDPSocket = struct { } if (i % 3 == 2) { if (!this.parseAddr(globalThis, port, val, &addrs[slice_idx])) { - globalThis.throwInvalidArguments("Invalid address", .{}); - return .zero; + return globalThis.throwInvalidArguments("Invalid address", .{}); } addr_ptrs[slice_idx] = &addrs[slice_idx]; } } if (i != array_len) { - globalThis.throwInvalidArguments("Mismatch between array length property and number of items", .{}); - return .zero; + return globalThis.throwInvalidArguments("Mismatch between array length property and number of items", .{}); } const res = this.socket.send(payloads, lens, addr_ptrs); if (bun.JSC.Maybe(void).errnoSys(res, .send)) |err| { @@ -457,15 +451,12 @@ pub const UDPSocket = struct { break :brk null; } if (arguments.len == 3) { - globalThis.throwInvalidArguments("Cannot specify destination on connected socket", .{}); - return .zero; + return globalThis.throwInvalidArguments("Cannot specify destination on connected socket", .{}); } - globalThis.throwInvalidArguments("Expected 1 argument, got {}", .{arguments.len}); - return .zero; + return globalThis.throwInvalidArguments("Expected 1 argument, got {}", .{arguments.len}); } else { if (arguments.len != 3) { - globalThis.throwInvalidArguments("Expected 3 arguments, got {}", .{arguments.len}); - return .zero; + return globalThis.throwInvalidArguments("Expected 3 arguments, got {}", .{arguments.len}); } break :brk .{ .port = arguments.ptr[1], @@ -484,8 +475,7 @@ pub const UDPSocket = struct { payload_str = payload_arg.asString().toSlice(globalThis, bun.default_allocator); break :brk payload_str.slice(); } else { - globalThis.throwInvalidArguments("Expected ArrayBufferView or string as first argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected ArrayBufferView or string as first argument", .{}); } }; @@ -493,8 +483,7 @@ pub const UDPSocket = struct { const addr_ptr = brk: { if (dst) |dest| { if (!this.parseAddr(globalThis, dest.port, dest.address, &addr)) { - globalThis.throwInvalidArguments("Invalid address", .{}); - return .zero; + return globalThis.throwInvalidArguments("Invalid address", .{}); } break :brk &addr; } else { @@ -576,7 +565,7 @@ pub const UDPSocket = struct { const args = callframe.arguments_old(1); if (args.len < 1) { - return globalThis.throwInvalidArguments2("Expected 1 argument", .{}); + return globalThis.throwInvalidArguments("Expected 1 argument", .{}); } const options = args.ptr[0]; @@ -679,8 +668,7 @@ pub const UDPSocket = struct { const args = callFrame.arguments_old(2); const this = callFrame.this().as(UDPSocket) orelse { - globalThis.throwInvalidArguments("Expected UDPSocket as 'this'", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected UDPSocket as 'this'", .{}); }; if (this.connect_info != null) { @@ -694,8 +682,7 @@ pub const UDPSocket = struct { } if (args.len < 2) { - globalThis.throwInvalidArguments("Expected 2 arguments", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected 2 arguments", .{}); } const str = args.ptr[0].toBunString(globalThis); @@ -706,8 +693,7 @@ pub const UDPSocket = struct { const connect_port_js = args.ptr[1]; if (!connect_port_js.isNumber()) { - globalThis.throwInvalidArguments("Expected \"port\" to be an integer", .{}); - return .zero; + return globalThis.throwInvalidArguments("Expected \"port\" to be an integer", .{}); } const connect_port = connect_port_js.asInt32(); @@ -727,8 +713,7 @@ pub const UDPSocket = struct { pub fn jsDisconnect(globalObject: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { const this = callFrame.this().as(UDPSocket) orelse { - globalObject.throwInvalidArguments("Expected UDPSocket as 'this'", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected UDPSocket as 'this'", .{}); }; if (this.connect_info == null) { diff --git a/src/bun.js/api/ffi.zig b/src/bun.js/api/ffi.zig index 468b4061dc4b50..8db8af0055e97b 100644 --- a/src/bun.js/api/ffi.zig +++ b/src/bun.js/api/ffi.zig @@ -625,7 +625,7 @@ pub const FFI = struct { pub fn Bun__FFI__cc(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { const arguments = callframe.arguments_old(1).slice(); if (arguments.len == 0 or !arguments[0].isObject()) { - return globalThis.throwInvalidArguments2("Expected object", .{}); + return globalThis.throwInvalidArguments("Expected object", .{}); } // Step 1. compile the user's code diff --git a/src/bun.js/api/filesystem_router.zig b/src/bun.js/api/filesystem_router.zig index fdba1f11344441..2baa031f5cf199 100644 --- a/src/bun.js/api/filesystem_router.zig +++ b/src/bun.js/api/filesystem_router.zig @@ -52,12 +52,12 @@ pub const FileSystemRouter = struct { pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*FileSystemRouter { const argument_ = callframe.arguments_old(1); if (argument_.len == 0) { - return globalThis.throwInvalidArguments2("Expected object", .{}); + return globalThis.throwInvalidArguments("Expected object", .{}); } const argument = argument_.ptr[0]; if (argument.isEmptyOrUndefinedOrNull() or !argument.isObject()) { - return globalThis.throwInvalidArguments2("Expected object", .{}); + return globalThis.throwInvalidArguments("Expected object", .{}); } var vm = globalThis.bunVM(); @@ -69,15 +69,15 @@ pub const FileSystemRouter = struct { var out_buf: [bun.MAX_PATH_BYTES * 2]u8 = undefined; if (try argument.get(globalThis, "style")) |style_val| { if (!style_val.getZigString(globalThis).eqlComptime("nextjs")) { - return globalThis.throwInvalidArguments2("Only 'nextjs' style is currently implemented", .{}); + return globalThis.throwInvalidArguments("Only 'nextjs' style is currently implemented", .{}); } } else { - return globalThis.throwInvalidArguments2("Expected 'style' option (ex: \"style\": \"nextjs\")", .{}); + return globalThis.throwInvalidArguments("Expected 'style' option (ex: \"style\": \"nextjs\")", .{}); } if (try argument.get(globalThis, "dir")) |dir| { if (!dir.isString()) { - return globalThis.throwInvalidArguments2("Expected dir to be a string", .{}); + return globalThis.throwInvalidArguments("Expected dir to be a string", .{}); } const root_dir_path_ = dir.toSlice(globalThis, globalThis.allocator()); if (!(root_dir_path_.len == 0 or strings.eqlComptime(root_dir_path_.slice(), "."))) { @@ -92,7 +92,7 @@ pub const FileSystemRouter = struct { } } else { // dir is not optional - return globalThis.throwInvalidArguments2("Expected dir to be a string", .{}); + return globalThis.throwInvalidArguments("Expected dir to be a string", .{}); } var arena = globalThis.allocator().create(bun.ArenaAllocator) catch unreachable; arena.* = bun.ArenaAllocator.init(globalThis.allocator()); @@ -103,7 +103,7 @@ pub const FileSystemRouter = struct { origin_str.deinit(); arena.deinit(); globalThis.allocator().destroy(arena); - return globalThis.throwInvalidArguments2("Expected fileExtensions to be an Array", .{}); + return globalThis.throwInvalidArguments("Expected fileExtensions to be an Array", .{}); } var iter = file_extensions.arrayIterator(globalThis); @@ -113,7 +113,7 @@ pub const FileSystemRouter = struct { origin_str.deinit(); arena.deinit(); globalThis.allocator().destroy(arena); - return globalThis.throwInvalidArguments2("Expected fileExtensions to be an Array of strings", .{}); + return globalThis.throwInvalidArguments("Expected fileExtensions to be an Array of strings", .{}); } if (val.getLength(globalThis) == 0) continue; extensions.appendAssumeCapacity((val.toSlice(globalThis, allocator).clone(allocator) catch unreachable).slice()[1..]); @@ -125,7 +125,7 @@ pub const FileSystemRouter = struct { origin_str.deinit(); arena.deinit(); globalThis.allocator().destroy(arena); - return globalThis.throwInvalidArguments2("Expected assetPrefix to be a string", .{}); + return globalThis.throwInvalidArguments("Expected assetPrefix to be a string", .{}); } asset_prefix_slice = asset_prefix.toSlice(globalThis, allocator).clone(allocator) catch unreachable; @@ -166,7 +166,7 @@ pub const FileSystemRouter = struct { if (!origin.isString()) { arena.deinit(); globalThis.allocator().destroy(arena); - return globalThis.throwInvalidArguments2("Expected origin to be a string", .{}); + return globalThis.throwInvalidArguments("Expected origin to be a string", .{}); } origin_str = origin.toSlice(globalThis, globalThis.allocator()); } @@ -248,14 +248,12 @@ pub const FileSystemRouter = struct { pub fn match(this: *FileSystemRouter, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { const argument_ = callframe.arguments_old(2); if (argument_.len == 0) { - globalThis.throwInvalidArguments("Expected string, Request or Response", .{}); - return JSValue.zero; + return globalThis.throwInvalidArguments("Expected string, Request or Response", .{}); } const argument = argument_.ptr[0]; if (argument.isEmptyOrUndefinedOrNull() or !argument.isCell()) { - globalThis.throwInvalidArguments("Expected string, Request or Response", .{}); - return JSValue.zero; + return globalThis.throwInvalidArguments("Expected string, Request or Response", .{}); } var path: ZigString.Slice = brk: { @@ -274,8 +272,7 @@ pub const FileSystemRouter = struct { } } - globalThis.throwInvalidArguments("Expected string, Request or Response", .{}); - return JSValue.zero; + return globalThis.throwInvalidArguments("Expected string, Request or Response", .{}); }; if (path.len == 0 or (path.len == 1 and path.ptr[0] == '/')) { diff --git a/src/bun.js/api/html_rewriter.zig b/src/bun.js/api/html_rewriter.zig index b7865f982c87b2..ef03999d237573 100644 --- a/src/bun.js/api/html_rewriter.zig +++ b/src/bun.js/api/html_rewriter.zig @@ -168,11 +168,10 @@ pub const HTMLRewriter = struct { return BufferOutputSink.init(new_context, global, response, this.builder); } - pub fn transform_(this: *HTMLRewriter, global: *JSGlobalObject, response_value: JSC.JSValue) JSValue { + pub fn transform_(this: *HTMLRewriter, global: *JSGlobalObject, response_value: JSC.JSValue) bun.JSError!JSValue { if (response_value.as(Response)) |response| { if (response.body.value == .Used) { - global.throwInvalidArguments("Response body already used", .{}); - return .zero; + return global.throwInvalidArguments("Response body already used", .{}); } const out = this.beginTransform(global, response); @@ -230,8 +229,7 @@ pub const HTMLRewriter = struct { } } - global.throwInvalidArguments("Expected Response or Body", .{}); - return .zero; + return global.throwInvalidArguments("Expected Response or Body", .{}); } pub const on = JSC.wrapInstanceMethod(HTMLRewriter, "on_", false); @@ -777,8 +775,7 @@ const DocumentHandler = struct { }; if (!thisObject.isObject()) { - global.throwInvalidArguments("Expected object", .{}); - return error.JSError; + return global.throwInvalidArguments("Expected object", .{}); } errdefer { @@ -801,8 +798,7 @@ const DocumentHandler = struct { if (try thisObject.get(global, "doctype")) |val| { if (val.isUndefinedOrNull() or !val.isCell() or !val.isCallable(global.vm())) { - global.throwInvalidArguments("doctype must be a function", .{}); - return error.JSError; + return global.throwInvalidArguments("doctype must be a function", .{}); } val.protect(); handler.onDocTypeCallback = val; @@ -810,8 +806,7 @@ const DocumentHandler = struct { if (try thisObject.get(global, "comments")) |val| { if (val.isUndefinedOrNull() or !val.isCell() or !val.isCallable(global.vm())) { - global.throwInvalidArguments("comments must be a function", .{}); - return error.JSError; + return global.throwInvalidArguments("comments must be a function", .{}); } val.protect(); handler.onCommentCallback = val; @@ -819,8 +814,7 @@ const DocumentHandler = struct { if (try thisObject.get(global, "text")) |val| { if (val.isUndefinedOrNull() or !val.isCell() or !val.isCallable(global.vm())) { - global.throwInvalidArguments("text must be a function", .{}); - return error.JSError; + return global.throwInvalidArguments("text must be a function", .{}); } val.protect(); handler.onTextCallback = val; @@ -828,8 +822,7 @@ const DocumentHandler = struct { if (try thisObject.get(global, "end")) |val| { if (val.isUndefinedOrNull() or !val.isCell() or !val.isCallable(global.vm())) { - global.throwInvalidArguments("end must be a function", .{}); - return error.JSError; + return global.throwInvalidArguments("end must be a function", .{}); } val.protect(); handler.onEndCallback = val; @@ -933,14 +926,12 @@ const ElementHandler = struct { } if (!thisObject.isObject()) { - global.throwInvalidArguments("Expected object", .{}); - return error.JSError; + return global.throwInvalidArguments("Expected object", .{}); } if (try thisObject.get(global, "element")) |val| { if (val.isUndefinedOrNull() or !val.isCell() or !val.isCallable(global.vm())) { - global.throwInvalidArguments("element must be a function", .{}); - return error.JSError; + return global.throwInvalidArguments("element must be a function", .{}); } val.protect(); handler.onElementCallback = val; @@ -948,8 +939,7 @@ const ElementHandler = struct { if (try thisObject.get(global, "comments")) |val| { if (val.isUndefinedOrNull() or !val.isCell() or !val.isCallable(global.vm())) { - global.throwInvalidArguments("comments must be a function", .{}); - return error.JSError; + return global.throwInvalidArguments("comments must be a function", .{}); } val.protect(); handler.onCommentCallback = val; @@ -957,8 +947,7 @@ const ElementHandler = struct { if (try thisObject.get(global, "text")) |val| { if (val.isUndefinedOrNull() or !val.isCell() or !val.isCallable(global.vm())) { - global.throwInvalidArguments("text must be a function", .{}); - return error.JSError; + return global.throwInvalidArguments("text must be a function", .{}); } val.protect(); handler.onTextCallback = val; diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index 3279bf584675a0..63f773e2eca090 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -109,8 +109,7 @@ const BlobFileContentResult = struct { if (str.len > 0) { return .{ .data = str }; } - global.throwInvalidArguments(std.fmt.comptimePrint("Invalid {s} file", .{fieldname}), .{}); - return error.JSError; + return global.throwInvalidArguments(std.fmt.comptimePrint("Invalid {s} file", .{fieldname}), .{}); }, } } @@ -210,11 +209,11 @@ const StaticRoute = struct { var blob: AnyBlob = brk: { switch (response.body.value) { .Used => { - return globalThis.throwInvalidArguments2("Response body has already been used", .{}); + return globalThis.throwInvalidArguments("Response body has already been used", .{}); }, else => { - return globalThis.throwInvalidArguments2("Body must be fully buffered before it can be used in a static route. Consider calling new Response(await response.blob()) to buffer the body.", .{}); + return globalThis.throwInvalidArguments("Body must be fully buffered before it can be used in a static route. Consider calling new Response(await response.blob()) to buffer the body.", .{}); }, .Null, .Empty => { break :brk AnyBlob{ @@ -269,7 +268,7 @@ const StaticRoute = struct { }); } - return globalThis.throwInvalidArguments2("Expected a Response object", .{}); + return globalThis.throwInvalidArguments("Expected a Response object", .{}); } // HEAD requests have no body. @@ -759,7 +758,7 @@ pub const ServerConfig = struct { defer arena.deinit(); if (!obj.isObject()) { - return global.throwInvalidArguments2("tls option expects an object", .{}); + return global.throwInvalidArguments("tls option expects an object", .{}); } var any = false; @@ -773,7 +772,7 @@ pub const ServerConfig = struct { if (sliced.len > 0) { result.key_file_name = bun.default_allocator.dupeZ(u8, sliced.slice()) catch unreachable; if (std.posix.system.access(result.key_file_name, std.posix.F_OK) != 0) { - return global.throwInvalidArguments2("Unable to access keyFile path", .{}); + return global.throwInvalidArguments("Unable to access keyFile path", .{}); } any = true; result.requires_custom_request_ctx = true; @@ -811,10 +810,9 @@ pub const ServerConfig = struct { return null; } } else { - global.throwInvalidArguments("key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); // mark and free all keys result.key = native_array; - return error.JSError; + return global.throwInvalidArguments("key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); } } @@ -853,10 +851,9 @@ pub const ServerConfig = struct { bun.default_allocator.free(native_array); } } else { - global.throwInvalidArguments("key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); // mark and free all certs result.key = native_array; - return error.JSError; + return global.throwInvalidArguments("key argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); } } } @@ -867,7 +864,7 @@ pub const ServerConfig = struct { if (sliced.len > 0) { result.cert_file_name = bun.default_allocator.dupeZ(u8, sliced.slice()) catch unreachable; if (std.posix.system.access(result.cert_file_name, std.posix.F_OK) != 0) { - return global.throwInvalidArguments2("Unable to access certFile path", .{}); + return global.throwInvalidArguments("Unable to access certFile path", .{}); } any = true; result.requires_custom_request_ctx = true; @@ -886,7 +883,7 @@ pub const ServerConfig = struct { any = true; result.requires_custom_request_ctx = true; } else { - return global.throwInvalidArguments2("ALPNProtocols argument must be an string, Buffer or TypedArray", .{}); + return global.throwInvalidArguments("ALPNProtocols argument must be an string, Buffer or TypedArray", .{}); } } @@ -921,10 +918,9 @@ pub const ServerConfig = struct { return null; } } else { - global.throwInvalidArguments("cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); // mark and free all certs result.cert = native_array; - return error.JSError; + return global.throwInvalidArguments("cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); } } @@ -963,10 +959,9 @@ pub const ServerConfig = struct { bun.default_allocator.free(native_array); } } else { - global.throwInvalidArguments("cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); // mark and free all certs result.cert = native_array; - return error.JSError; + return global.throwInvalidArguments("cert argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); } } } @@ -1040,10 +1035,9 @@ pub const ServerConfig = struct { return null; } } else { - global.throwInvalidArguments("ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); // mark and free all CA's result.cert = native_array; - return error.JSError; + return global.throwInvalidArguments("ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); } } @@ -1082,10 +1076,9 @@ pub const ServerConfig = struct { bun.default_allocator.free(native_array); } } else { - global.throwInvalidArguments("ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); // mark and free all certs result.ca = native_array; - return error.JSError; + return global.throwInvalidArguments("ca argument must be an string, Buffer, TypedArray, BunFile or an array containing string, Buffer, TypedArray or BunFile", .{}); } } } @@ -1096,7 +1089,7 @@ pub const ServerConfig = struct { if (sliced.len > 0) { result.ca_file_name = bun.default_allocator.dupeZ(u8, sliced.slice()) catch unreachable; if (std.posix.system.access(result.ca_file_name, std.posix.F_OK) != 0) { - return global.throwInvalidArguments2("Invalid caFile path", .{}); + return global.throwInvalidArguments("Invalid caFile path", .{}); } } } @@ -1126,7 +1119,7 @@ pub const ServerConfig = struct { if (sliced.len > 0) { result.dh_params_file_name = bun.default_allocator.dupeZ(u8, sliced.slice()) catch unreachable; if (std.posix.system.access(result.dh_params_file_name, std.posix.F_OK) != 0) { - return global.throwInvalidArguments2("Invalid dhParamsFile path", .{}); + return global.throwInvalidArguments("Invalid dhParamsFile path", .{}); } } } @@ -1221,12 +1214,12 @@ pub const ServerConfig = struct { if (arguments.next()) |arg| { if (!arg.isObject()) { - return global.throwInvalidArguments2("Bun.serve expects an object", .{}); + return global.throwInvalidArguments("Bun.serve expects an object", .{}); } if (try arg.get(global, "static")) |static| { if (!static.isObject()) { - return global.throwInvalidArguments2("Bun.serve expects 'static' to be an object shaped like { [pathname: string]: Response }", .{}); + return global.throwInvalidArguments("Bun.serve expects 'static' to be an object shaped like { [pathname: string]: Response }", .{}); } var iter = JSC.JSPropertyIterator(.{ @@ -1242,12 +1235,12 @@ pub const ServerConfig = struct { if (path.len == 0 or path[0] != '/') { bun.default_allocator.free(path); - return global.throwInvalidArguments2("Invalid static route \"{s}\". path must start with '/'", .{path}); + return global.throwInvalidArguments("Invalid static route \"{s}\". path must start with '/'", .{path}); } if (!is_ascii) { bun.default_allocator.free(path); - return global.throwInvalidArguments2("Invalid static route \"{s}\". Please encode all non-ASCII characters in the path.", .{path}); + return global.throwInvalidArguments("Invalid static route \"{s}\". Please encode all non-ASCII characters in the path.", .{path}); } const route = try StaticRoute.fromJS(global, value); @@ -1263,15 +1256,13 @@ pub const ServerConfig = struct { if (try arg.get(global, "idleTimeout")) |value| { if (!value.isUndefinedOrNull()) { if (!value.isAnyInt()) { - global.throwInvalidArguments("Bun.serve expects idleTimeout to be an integer", .{}); - return error.JSError; + return global.throwInvalidArguments("Bun.serve expects idleTimeout to be an integer", .{}); } args.has_idleTimeout = true; const idleTimeout: u64 = @intCast(@max(value.toInt64(), 0)); if (idleTimeout > 255) { - global.throwInvalidArguments("Bun.serve expects idleTimeout to be 255 or less", .{}); - return error.JSError; + return global.throwInvalidArguments("Bun.serve expects idleTimeout to be 255 or less", .{}); } args.idleTimeout = @truncate(idleTimeout); @@ -1280,11 +1271,10 @@ pub const ServerConfig = struct { if (try arg.getTruthy(global, "webSocket") orelse try arg.getTruthy(global, "websocket")) |websocket_object| { if (!websocket_object.isObject()) { - global.throwInvalidArguments("Expected websocket to be an object", .{}); if (args.ssl_config) |*conf| { conf.deinit(); } - return error.JSError; + return global.throwInvalidArguments("Expected websocket to be an object", .{}); } errdefer if (args.ssl_config) |*conf| conf.deinit(); @@ -1336,8 +1326,7 @@ pub const ServerConfig = struct { defer unix_str.deinit(); if (unix_str.len > 0) { if (has_hostname) { - global.throwInvalidArguments("Cannot specify both hostname and unix", .{}); - return error.JSError; + return global.throwInvalidArguments("Cannot specify both hostname and unix", .{}); } args.address = .{ .unix = bun.default_allocator.dupeZ(u8, unix_str.slice()) catch unreachable }; @@ -1371,13 +1360,13 @@ pub const ServerConfig = struct { if (try arg.getTruthy(global, "app")) |bake_args_js| { if (!bun.FeatureFlags.bake) { - return global.throwInvalidArguments2("To use the experimental \"app\" option, upgrade to the canary build of bun via \"bun upgrade --canary\"", .{}); + return global.throwInvalidArguments("To use the experimental \"app\" option, upgrade to the canary build of bun via \"bun upgrade --canary\"", .{}); } if (!allow_bake_config) { - return global.throwInvalidArguments2("To use the \"app\" option, change from calling \"Bun.serve({ app })\" to \"export default { app: ... }\"", .{}); + return global.throwInvalidArguments("To use the \"app\" option, change from calling \"Bun.serve({ app })\" to \"export default { app: ... }\"", .{}); } if (!args.development) { - return global.throwInvalidArguments2("TODO: 'development: false' in serve options with 'app'. For now, use `bun build --app` or set 'development: true'", .{}); + return global.throwInvalidArguments("TODO: 'development: false' in serve options with 'app'. For now, use `bun build --app` or set 'development: true'", .{}); } args.bake = try bun.bake.UserOptions.fromJS(bake_args_js, global); @@ -1392,8 +1381,7 @@ pub const ServerConfig = struct { args.inspector = inspector.coerce(bool, global); if (args.inspector and !args.development) { - global.throwInvalidArguments("Cannot enable inspector in production. Please set development: true in Bun.serve()", .{}); - return error.JSError; + return global.throwInvalidArguments("Cannot enable inspector in production. Please set development: true in Bun.serve()", .{}); } } if (global.hasException()) return error.JSError; @@ -1407,8 +1395,7 @@ pub const ServerConfig = struct { if (try arg.getTruthyComptime(global, "error")) |onError| { if (!onError.isCallable(global.vm())) { - global.throwInvalidArguments("Expected error to be a function", .{}); - return error.JSError; + return global.throwInvalidArguments("Expected error to be a function", .{}); } const onErrorSnapshot = onError.withAsyncContextIfNeeded(global); args.onError = onErrorSnapshot; @@ -1418,16 +1405,14 @@ pub const ServerConfig = struct { if (try arg.getTruthy(global, "fetch")) |onRequest_| { if (!onRequest_.isCallable(global.vm())) { - global.throwInvalidArguments("Expected fetch() to be a function", .{}); - return error.JSError; + return global.throwInvalidArguments("Expected fetch() to be a function", .{}); } const onRequest = onRequest_.withAsyncContextIfNeeded(global); JSC.C.JSValueProtect(global, onRequest.asObjectRef()); args.onRequest = onRequest; } else if (args.bake == null) { if (global.hasException()) return error.JSError; - global.throwInvalidArguments("Expected fetch() to be a function", .{}); - return error.JSError; + return global.throwInvalidArguments("Expected fetch() to be a function", .{}); } else { if (global.hasException()) return error.JSError; } @@ -1438,8 +1423,7 @@ pub const ServerConfig = struct { } else if (tls.jsType().isArray()) { var value_iter = tls.arrayIterator(global); if (value_iter.len == 1) { - global.throwInvalidArguments("tls option expects at least 1 tls object", .{}); - return error.JSError; + return global.throwInvalidArguments("tls option expects at least 1 tls object", .{}); } while (value_iter.next()) |item| { var ssl_config = try SSLConfig.fromJS(vm, global, item) orelse { @@ -1456,8 +1440,7 @@ pub const ServerConfig = struct { } else { if (ssl_config.server_name == null or std.mem.span(ssl_config.server_name).len == 0) { defer ssl_config.deinit(); - global.throwInvalidArguments("SNI tls object must have a serverName", .{}); - return error.JSError; + return global.throwInvalidArguments("SNI tls object must have a serverName", .{}); } if (args.sni == null) { args.sni = bun.BabyList(SSLConfig).initCapacity(bun.default_allocator, value_iter.len - 1) catch bun.outOfMemory(); @@ -1488,24 +1471,21 @@ pub const ServerConfig = struct { } } } else { - global.throwInvalidArguments("Bun.serve expects an object", .{}); - return error.JSError; + return global.throwInvalidArguments("Bun.serve expects an object", .{}); } if (args.base_uri.len > 0) { args.base_url = URL.parse(args.base_uri); if (args.base_url.hostname.len == 0) { - global.throwInvalidArguments("baseURI must have a hostname", .{}); bun.default_allocator.free(@constCast(args.base_uri)); args.base_uri = ""; - return error.JSError; + return global.throwInvalidArguments("baseURI must have a hostname", .{}); } if (!strings.isAllASCII(args.base_uri)) { - global.throwInvalidArguments("Unicode baseURI must already be encoded for now.\nnew URL(baseuRI).toString() should do the trick.", .{}); bun.default_allocator.free(@constCast(args.base_uri)); args.base_uri = ""; - return error.JSError; + return global.throwInvalidArguments("Unicode baseURI must already be encoded for now.\nnew URL(baseuRI).toString() should do the trick.", .{}); } if (args.base_url.protocol.len == 0) { @@ -1570,10 +1550,9 @@ pub const ServerConfig = struct { } if (!strings.isAllASCII(hostname)) { - global.throwInvalidArguments("Unicode hostnames must already be encoded for now.\nnew URL(input).hostname should do the trick.", .{}); bun.default_allocator.free(@constCast(args.base_uri)); args.base_uri = ""; - return error.JSError; + return global.throwInvalidArguments("Unicode hostnames must already be encoded for now.\nnew URL(input).hostname should do the trick.", .{}); } args.base_url = URL.parse(args.base_uri); @@ -1582,17 +1561,15 @@ pub const ServerConfig = struct { // I don't think there's a case where this can happen // but let's check anyway, just in case if (args.base_url.hostname.len == 0) { - global.throwInvalidArguments("baseURI must have a hostname", .{}); bun.default_allocator.free(@constCast(args.base_uri)); args.base_uri = ""; - return error.JSError; + return global.throwInvalidArguments("baseURI must have a hostname", .{}); } if (args.base_url.username.len > 0 or args.base_url.password.len > 0) { - global.throwInvalidArguments("baseURI can't have a username or password", .{}); bun.default_allocator.free(@constCast(args.base_uri)); args.base_uri = ""; - return error.JSError; + return global.throwInvalidArguments("baseURI can't have a username or password", .{}); } return; @@ -4160,7 +4137,7 @@ pub const WebSocketServer = struct { if (try object.getTruthyComptime(globalObject, "message")) |message_| { if (!message_.isCallable(vm)) { - return globalObject.throwInvalidArguments2("websocket expects a function for the message option", .{}); + return globalObject.throwInvalidArguments("websocket expects a function for the message option", .{}); } const message = message_.withAsyncContextIfNeeded(globalObject); handler.onMessage = message; @@ -4170,7 +4147,7 @@ pub const WebSocketServer = struct { if (try object.getTruthy(globalObject, "open")) |open_| { if (!open_.isCallable(vm)) { - return globalObject.throwInvalidArguments2("websocket expects a function for the open option", .{}); + return globalObject.throwInvalidArguments("websocket expects a function for the open option", .{}); } const open = open_.withAsyncContextIfNeeded(globalObject); handler.onOpen = open; @@ -4180,7 +4157,7 @@ pub const WebSocketServer = struct { if (try object.getTruthy(globalObject, "close")) |close_| { if (!close_.isCallable(vm)) { - return globalObject.throwInvalidArguments2("websocket expects a function for the close option", .{}); + return globalObject.throwInvalidArguments("websocket expects a function for the close option", .{}); } const close = close_.withAsyncContextIfNeeded(globalObject); handler.onClose = close; @@ -4190,7 +4167,7 @@ pub const WebSocketServer = struct { if (try object.getTruthy(globalObject, "drain")) |drain_| { if (!drain_.isCallable(vm)) { - return globalObject.throwInvalidArguments2("websocket expects a function for the drain option", .{}); + return globalObject.throwInvalidArguments("websocket expects a function for the drain option", .{}); } const drain = drain_.withAsyncContextIfNeeded(globalObject); handler.onDrain = drain; @@ -4200,7 +4177,7 @@ pub const WebSocketServer = struct { if (try object.getTruthy(globalObject, "onError")) |onError_| { if (!onError_.isCallable(vm)) { - return globalObject.throwInvalidArguments2("websocket expects a function for the onError option", .{}); + return globalObject.throwInvalidArguments("websocket expects a function for the onError option", .{}); } const onError = onError_.withAsyncContextIfNeeded(globalObject); handler.onError = onError; @@ -4209,7 +4186,7 @@ pub const WebSocketServer = struct { if (try object.getTruthy(globalObject, "ping")) |cb| { if (!cb.isCallable(vm)) { - return globalObject.throwInvalidArguments2("websocket expects a function for the ping option", .{}); + return globalObject.throwInvalidArguments("websocket expects a function for the ping option", .{}); } handler.onPing = cb; cb.ensureStillAlive(); @@ -4218,7 +4195,7 @@ pub const WebSocketServer = struct { if (try object.getTruthy(globalObject, "pong")) |cb| { if (!cb.isCallable(vm)) { - return globalObject.throwInvalidArguments2("websocket expects a function for the pong option", .{}); + return globalObject.throwInvalidArguments("websocket expects a function for the pong option", .{}); } handler.onPong = cb; cb.ensureStillAlive(); @@ -4228,7 +4205,7 @@ pub const WebSocketServer = struct { if (valid) return handler; - return globalObject.throwInvalidArguments2("WebSocketServer expects a message handler", .{}); + return globalObject.throwInvalidArguments("WebSocketServer expects a message handler", .{}); } pub fn protect(this: Handler) void { @@ -4328,10 +4305,10 @@ pub const WebSocketServer = struct { server.compression |= if (compression.toBoolean()) uws.SHARED_COMPRESSOR else 0; } else if (compression.isString()) { server.compression |= CompressTable.getWithEql(compression.getZigString(globalObject), ZigString.eqlComptime) orelse { - return globalObject.throwInvalidArguments2("WebSocketServer expects a valid compress option, either disable \"shared\" \"dedicated\" \"3KB\" \"4KB\" \"8KB\" \"16KB\" \"32KB\" \"64KB\" \"128KB\" or \"256KB\"", .{}); + return globalObject.throwInvalidArguments("WebSocketServer expects a valid compress option, either disable \"shared\" \"dedicated\" \"3KB\" \"4KB\" \"8KB\" \"16KB\" \"32KB\" \"64KB\" \"128KB\" or \"256KB\"", .{}); }; } else { - return globalObject.throwInvalidArguments2("websocket expects a valid compress option, either disable \"shared\" \"dedicated\" \"3KB\" \"4KB\" \"8KB\" \"16KB\" \"32KB\" \"64KB\" \"128KB\" or \"256KB\"", .{}); + return globalObject.throwInvalidArguments("websocket expects a valid compress option, either disable \"shared\" \"dedicated\" \"3KB\" \"4KB\" \"8KB\" \"16KB\" \"32KB\" \"64KB\" \"128KB\" or \"256KB\"", .{}); } } @@ -4340,10 +4317,10 @@ pub const WebSocketServer = struct { server.compression |= if (compression.toBoolean()) uws.SHARED_DECOMPRESSOR else 0; } else if (compression.isString()) { server.compression |= DecompressTable.getWithEql(compression.getZigString(globalObject), ZigString.eqlComptime) orelse { - return globalObject.throwInvalidArguments2("websocket expects a valid decompress option, either \"disable\" \"shared\" \"dedicated\" \"3KB\" \"4KB\" \"8KB\" \"16KB\" \"32KB\" \"64KB\" \"128KB\" or \"256KB\"", .{}); + return globalObject.throwInvalidArguments("websocket expects a valid decompress option, either \"disable\" \"shared\" \"dedicated\" \"3KB\" \"4KB\" \"8KB\" \"16KB\" \"32KB\" \"64KB\" \"128KB\" or \"256KB\"", .{}); }; } else { - return globalObject.throwInvalidArguments2("websocket expects a valid decompress option, either \"disable\" \"shared\" \"dedicated\" \"3KB\" \"4KB\" \"8KB\" \"16KB\" \"32KB\" \"64KB\" \"128KB\" or \"256KB\"", .{}); + return globalObject.throwInvalidArguments("websocket expects a valid decompress option, either \"disable\" \"shared\" \"dedicated\" \"3KB\" \"4KB\" \"8KB\" \"16KB\" \"32KB\" \"64KB\" \"128KB\" or \"256KB\"", .{}); } } } @@ -4352,7 +4329,7 @@ pub const WebSocketServer = struct { if (try object.get(globalObject, "maxPayloadLength")) |value| { if (!value.isUndefinedOrNull()) { if (!value.isAnyInt()) { - return globalObject.throwInvalidArguments2("websocket expects maxPayloadLength to be an integer", .{}); + return globalObject.throwInvalidArguments("websocket expects maxPayloadLength to be an integer", .{}); } server.maxPayloadLength = @truncate(@max(value.toInt64(), 0)); } @@ -4361,12 +4338,12 @@ pub const WebSocketServer = struct { if (try object.get(globalObject, "idleTimeout")) |value| { if (!value.isUndefinedOrNull()) { if (!value.isAnyInt()) { - return globalObject.throwInvalidArguments2("websocket expects idleTimeout to be an integer", .{}); + return globalObject.throwInvalidArguments("websocket expects idleTimeout to be an integer", .{}); } var idleTimeout: u16 = @truncate(@max(value.toInt64(), 0)); if (idleTimeout > 960) { - return globalObject.throwInvalidArguments2("websocket expects idleTimeout to be 960 or less", .{}); + return globalObject.throwInvalidArguments("websocket expects idleTimeout to be 960 or less", .{}); } else if (idleTimeout > 0) { // uws does not allow idleTimeout to be between (0, 8), // since its timer is not that accurate, therefore round up. @@ -4379,7 +4356,7 @@ pub const WebSocketServer = struct { if (try object.get(globalObject, "backpressureLimit")) |value| { if (!value.isUndefinedOrNull()) { if (!value.isAnyInt()) { - return globalObject.throwInvalidArguments2("websocket expects backpressureLimit to be an integer", .{}); + return globalObject.throwInvalidArguments("websocket expects backpressureLimit to be an integer", .{}); } server.backpressureLimit = @truncate(@max(value.toInt64(), 0)); @@ -4389,7 +4366,7 @@ pub const WebSocketServer = struct { if (try object.get(globalObject, "closeOnBackpressureLimit")) |value| { if (!value.isUndefinedOrNull()) { if (!value.isBoolean()) { - return globalObject.throwInvalidArguments2("websocket expects closeOnBackpressureLimit to be a boolean", .{}); + return globalObject.throwInvalidArguments("websocket expects closeOnBackpressureLimit to be a boolean", .{}); } server.closeOnBackpressureLimit = value.toBoolean(); @@ -4399,7 +4376,7 @@ pub const WebSocketServer = struct { if (try object.get(globalObject, "sendPings")) |value| { if (!value.isUndefinedOrNull()) { if (!value.isBoolean()) { - return globalObject.throwInvalidArguments2("websocket expects sendPings to be a boolean", .{}); + return globalObject.throwInvalidArguments("websocket expects sendPings to be a boolean", .{}); } server.sendPingsAutomatically = value.toBoolean(); @@ -4409,7 +4386,7 @@ pub const WebSocketServer = struct { if (try object.get(globalObject, "publishToSelf")) |value| { if (!value.isUndefinedOrNull()) { if (!value.isBoolean()) { - return globalObject.throwInvalidArguments2("websocket expects publishToSelf to be a boolean", .{}); + return globalObject.throwInvalidArguments("websocket expects publishToSelf to be a boolean", .{}); } server.handler.flags.publish_to_self = value.toBoolean(); @@ -5479,8 +5456,7 @@ pub const ServerWebSocket = struct { } if (!args.ptr[0].isNumber()) { - globalThis.throwInvalidArguments("close requires a numeric code or undefined", .{}); - return .zero; + return globalThis.throwInvalidArguments("close requires a numeric code or undefined", .{}); } break :brk args.ptr[0].coerce(i32, globalThis); @@ -5760,8 +5736,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp } if (arguments.ptr[0].isEmptyOrUndefinedOrNull()) { - globalThis.throwInvalidArguments("subscriberCount requires a topic name as a string", .{}); - return .zero; + return globalThis.throwInvalidArguments("subscriberCount requires a topic name as a string", .{}); } var topic = arguments.ptr[0].toSlice(globalThis, bun.default_allocator); @@ -5866,8 +5841,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp optional: ?JSValue, ) bun.JSError!JSValue { if (this.config.websocket == null) { - globalThis.throwInvalidArguments("To enable websocket support, set the \"websocket\" object in Bun.serve({})", .{}); - return error.JSError; + return globalThis.throwInvalidArguments("To enable websocket support, set the \"websocket\" object in Bun.serve({})", .{}); } if (this.flags.terminated) { @@ -5875,8 +5849,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp } var request = object.as(Request) orelse { - globalThis.throwInvalidArguments("upgrade requires a Request object", .{}); - return error.JSError; + return globalThis.throwInvalidArguments("upgrade requires a Request object", .{}); }; var upgrader = request.request_context.get(RequestContext) orelse return JSC.jsBoolean(false); @@ -5947,8 +5920,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp } if (!opts.isObject()) { - globalThis.throwInvalidArguments("upgrade options must be an object", .{}); - return error.JSError; + return globalThis.throwInvalidArguments("upgrade options must be an object", .{}); } if (opts.fastGet(globalThis, .data)) |headers_value| { @@ -5974,7 +5946,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp break :brk null; } orelse { if (!globalThis.hasException()) { - globalThis.throwInvalidArguments("upgrade options.headers must be a Headers or an object", .{}); + return globalThis.throwInvalidArguments("upgrade options.headers must be a Headers or an object", .{}); } return error.JSError; }; diff --git a/src/bun.js/base.zig b/src/bun.js/base.zig index 20af22def78144..c8bf5f4ea21e95 100644 --- a/src/bun.js/base.zig +++ b/src/bun.js/base.zig @@ -957,11 +957,7 @@ pub fn DOMCall( arguments_ptr: [*]const JSC.JSValue, arguments_len: usize, ) callconv(JSC.conv) JSValue { - return @field(Container, functionName)( - globalObject, - thisValue, - arguments_ptr[0..arguments_len], - ); + return JSC.toJSHostValue(globalObject, @field(Container, functionName)(globalObject, thisValue, arguments_ptr[0..arguments_len])); } pub const fastpath = @field(Container, functionName ++ "WithoutTypeChecks"); @@ -1035,23 +1031,20 @@ pub fn wrapInstanceMethod( }, JSC.Node.StringOrBuffer => { const arg = iter.nextEat() orelse { - globalThis.throwInvalidArguments("expected string or buffer", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected string or buffer", .{}); }; args[i] = JSC.Node.StringOrBuffer.fromJS(globalThis, iter.arena.allocator(), arg) orelse { - globalThis.throwInvalidArguments("expected string or buffer", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected string or buffer", .{}); }; }, ?JSC.Node.StringOrBuffer => { if (iter.nextEat()) |arg| { if (!arg.isEmptyOrUndefinedOrNull()) { args[i] = JSC.Node.StringOrBuffer.fromJS(globalThis, iter.arena.allocator(), arg) orelse { - globalThis.throwInvalidArguments("expected string or buffer", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected string or buffer", .{}); }; } else { args[i] = null; @@ -1063,22 +1056,19 @@ pub fn wrapInstanceMethod( JSC.ArrayBuffer => { if (iter.nextEat()) |arg| { args[i] = arg.asArrayBuffer(globalThis) orelse { - globalThis.throwInvalidArguments("expected TypedArray", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected TypedArray", .{}); }; } else { - globalThis.throwInvalidArguments("expected TypedArray", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected TypedArray", .{}); } }, ?JSC.ArrayBuffer => { if (iter.nextEat()) |arg| { args[i] = arg.asArrayBuffer(globalThis) orelse { - globalThis.throwInvalidArguments("expected TypedArray", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected TypedArray", .{}); }; } else { args[i] = null; @@ -1086,15 +1076,13 @@ pub fn wrapInstanceMethod( }, ZigString => { var string_value = eater(&iter) orelse { - globalThis.throwInvalidArguments("Missing argument", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Missing argument", .{}); }; if (string_value.isUndefinedOrNull()) { - globalThis.throwInvalidArguments("Expected string", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Expected string", .{}); } args[i] = string_value.getZigString(globalThis); @@ -1110,31 +1098,26 @@ pub fn wrapInstanceMethod( }, *Response => { args[i] = (eater(&iter) orelse { - globalThis.throwInvalidArguments("Missing Response object", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Missing Response object", .{}); }).as(Response) orelse { - globalThis.throwInvalidArguments("Expected Response object", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Expected Response object", .{}); }; }, *Request => { args[i] = (eater(&iter) orelse { - globalThis.throwInvalidArguments("Missing Request object", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Missing Request object", .{}); }).as(Request) orelse { - globalThis.throwInvalidArguments("Expected Request object", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Expected Request object", .{}); }; }, JSValue => { const val = eater(&iter) orelse { - globalThis.throwInvalidArguments("Missing argument", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Missing argument", .{}); }; args[i] = val; }, @@ -1190,14 +1173,12 @@ pub fn wrapStaticMethod( }, JSC.Node.StringOrBuffer => { const arg = iter.nextEat() orelse { - globalThis.throwInvalidArguments("expected string or buffer", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected string or buffer", .{}); }; args[i] = JSC.Node.StringOrBuffer.fromJS(globalThis, iter.arena.allocator(), arg) orelse { - globalThis.throwInvalidArguments("expected string or buffer", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected string or buffer", .{}); }; }, ?JSC.Node.StringOrBuffer => { @@ -1207,9 +1188,8 @@ pub fn wrapStaticMethod( break :brk null; } - globalThis.throwInvalidArguments("expected string or buffer", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected string or buffer", .{}); }; } else { args[i] = null; @@ -1218,35 +1198,30 @@ pub fn wrapStaticMethod( JSC.Node.BlobOrStringOrBuffer => { if (iter.nextEat()) |arg| { args[i] = JSC.Node.BlobOrStringOrBuffer.fromJS(globalThis, iter.arena.allocator(), arg) orelse { - globalThis.throwInvalidArguments("expected blob, string or buffer", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected blob, string or buffer", .{}); }; } else { - globalThis.throwInvalidArguments("expected blob, string or buffer", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected blob, string or buffer", .{}); } }, JSC.ArrayBuffer => { if (iter.nextEat()) |arg| { args[i] = arg.asArrayBuffer(globalThis) orelse { - globalThis.throwInvalidArguments("expected TypedArray", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected TypedArray", .{}); }; } else { - globalThis.throwInvalidArguments("expected TypedArray", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected TypedArray", .{}); } }, ?JSC.ArrayBuffer => { if (iter.nextEat()) |arg| { args[i] = arg.asArrayBuffer(globalThis) orelse { - globalThis.throwInvalidArguments("expected TypedArray", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("expected TypedArray", .{}); }; } else { args[i] = null; @@ -1254,15 +1229,13 @@ pub fn wrapStaticMethod( }, ZigString => { var string_value = eater(&iter) orelse { - globalThis.throwInvalidArguments("Missing argument", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Missing argument", .{}); }; if (string_value.isUndefinedOrNull()) { - globalThis.throwInvalidArguments("Expected string", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Expected string", .{}); } args[i] = string_value.getZigString(globalThis); @@ -1278,31 +1251,26 @@ pub fn wrapStaticMethod( }, *Response => { args[i] = (eater(&iter) orelse { - globalThis.throwInvalidArguments("Missing Response object", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Missing Response object", .{}); }).as(Response) orelse { - globalThis.throwInvalidArguments("Expected Response object", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Expected Response object", .{}); }; }, *Request => { args[i] = (eater(&iter) orelse { - globalThis.throwInvalidArguments("Missing Request object", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Missing Request object", .{}); }).as(Request) orelse { - globalThis.throwInvalidArguments("Expected Request object", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Expected Request object", .{}); }; }, JSValue => { const val = eater(&iter) orelse { - globalThis.throwInvalidArguments("Missing argument", .{}); iter.deinit(); - return JSC.JSValue.zero; + return globalThis.throwInvalidArguments("Missing argument", .{}); }; args[i] = val; }, diff --git a/src/bun.js/bindings/bindings.zig b/src/bun.js/bindings/bindings.zig index a615d3f6141b53..552187638ba375 100644 --- a/src/bun.js/bindings/bindings.zig +++ b/src/bun.js/bindings/bindings.zig @@ -2979,14 +2979,7 @@ pub const JSGlobalObject = opaque { return @enumFromInt(@intFromPtr(globalThis)); } - /// Deprecated: use `throwInvalidArguments2` - pub fn throwInvalidArguments(this: *JSGlobalObject, comptime fmt: [:0]const u8, args: anytype) void { - const err = JSC.toInvalidArguments(fmt, args, this); - this.vm().throwError(this, err); - } - - /// New system for throwing errors: returning bun.JSError - pub fn throwInvalidArguments2(this: *JSGlobalObject, comptime fmt: [:0]const u8, args: anytype) bun.JSError { + pub fn throwInvalidArguments(this: *JSGlobalObject, comptime fmt: [:0]const u8, args: anytype) bun.JSError { const err = JSC.toInvalidArguments(fmt, args, this); return this.vm().throwError2(this, err); } @@ -5532,8 +5525,7 @@ pub const JSValue = enum(i64) { comptime StringMap: anytype, ) JSError!Enum { if (!this.isString()) { - globalThis.throwInvalidArguments(property_name ++ " must be a string", .{}); - return error.JSError; + return globalThis.throwInvalidArguments(property_name ++ " must be a string", .{}); } return StringMap.fromJS(globalThis, this) orelse { @@ -5555,7 +5547,7 @@ pub const JSValue = enum(i64) { pub const label = property_name ++ " must be one of " ++ list; }.label; if (!globalThis.hasException()) - globalThis.throwInvalidArguments(one_of, .{}); + return globalThis.throwInvalidArguments(one_of, .{}); return error.JSError; }; } @@ -5609,7 +5601,7 @@ pub const JSValue = enum(i64) { pub fn coerceToArray(prop: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8) JSError!?JSValue { if (!prop.jsTypeLoose().isArray()) { - return globalThis.throwInvalidArguments2(property_name ++ " must be an array", .{}); + return globalThis.throwInvalidArguments(property_name ++ " must be an array", .{}); } if (prop.getLength(globalThis) == 0) { @@ -5638,8 +5630,7 @@ pub const JSValue = enum(i64) { pub fn getObject(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8) JSError!?JSValue { if (try this.getOptional(globalThis, property_name, JSValue)) |prop| { if (!prop.jsTypeLoose().isObject()) { - globalThis.throwInvalidArguments(property_name ++ " must be an object", .{}); - return error.JSError; + return globalThis.throwInvalidArguments(property_name ++ " must be an object", .{}); } return prop; @@ -5651,8 +5642,7 @@ pub const JSValue = enum(i64) { pub fn getOwnObject(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8) JSError!?JSValue { if (getOwnTruthy(this, globalThis, property_name)) |prop| { if (!prop.jsTypeLoose().isObject()) { - globalThis.throwInvalidArguments(property_name ++ " must be an object", .{}); - return error.JSError; + return globalThis.throwInvalidArguments(property_name ++ " must be an object", .{}); } return prop; @@ -5664,8 +5654,7 @@ pub const JSValue = enum(i64) { pub fn getFunction(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8) JSError!?JSValue { if (try this.getOptional(globalThis, property_name, JSValue)) |prop| { if (!prop.isCell() or !prop.isCallable(globalThis.vm())) { - globalThis.throwInvalidArguments(property_name ++ " must be a function", .{}); - return error.JSError; + return globalThis.throwInvalidArguments(property_name ++ " must be a function", .{}); } return prop; @@ -5677,8 +5666,7 @@ pub const JSValue = enum(i64) { pub fn getOwnFunction(this: JSValue, globalThis: *JSGlobalObject, comptime property_name: []const u8) JSError!?JSValue { if (getOwnTruthy(this, globalThis, property_name)) |prop| { if (!prop.isCell() or !prop.isCallable(globalThis.vm())) { - globalThis.throwInvalidArguments(property_name ++ " must be a function", .{}); - return error.JSError; + return globalThis.throwInvalidArguments(property_name ++ " must be a function", .{}); } return prop; diff --git a/src/bun.js/javascript.zig b/src/bun.js/javascript.zig index 783d5e693c3c4e..c79fdd44953f73 100644 --- a/src/bun.js/javascript.zig +++ b/src/bun.js/javascript.zig @@ -4549,7 +4549,7 @@ pub fn Bun__setSyntheticAllocationLimitForTesting(globalObject: *JSC.JSGlobalObj } if (!args[0].isNumber()) { - return globalObject.throwInvalidArguments2("setSyntheticAllocationLimitForTesting expects a number", .{}); + return globalObject.throwInvalidArguments("setSyntheticAllocationLimitForTesting expects a number", .{}); } const limit: usize = @intCast(@max(args[0].coerceToInt64(globalObject), 1024 * 1024)); diff --git a/src/bun.js/node/node_fs.zig b/src/bun.js/node/node_fs.zig index 97037a12910270..ec043e44ce1d6e 100644 --- a/src/bun.js/node/node_fs.zig +++ b/src/bun.js/node/node_fs.zig @@ -1283,11 +1283,11 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Rename { const old_path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("oldPath must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("oldPath must be a string or TypedArray", .{}); }; const new_path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("newPath must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("newPath must be a string or TypedArray", .{}); }; return Rename{ .old_path = old_path, .new_path = new_path }; @@ -1314,7 +1314,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Truncate { const path = try PathOrFileDescriptor.fromJS(ctx, arguments, bun.default_allocator) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; const len: JSC.WebCore.Blob.SizeType = brk: { @@ -1356,17 +1356,17 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Writev { const fd_value = arguments.nextEat() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }; const fd = try JSC.Node.fileDescriptorFromJS(ctx, fd_value) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; const buffers = try JSC.Node.VectorArrayBuffer.fromJS( ctx, arguments.protectEatNext() orelse { - return ctx.throwInvalidArguments2("Expected an ArrayBufferView[]", .{}); + return ctx.throwInvalidArguments("Expected an ArrayBufferView[]", .{}); }, arguments.arena.allocator(), ); @@ -1378,7 +1378,7 @@ pub const Arguments = struct { if (pos_value.isNumber()) { position = pos_value.to(u52); } else { - return ctx.throwInvalidArguments2("position must be a number", .{}); + return ctx.throwInvalidArguments("position must be a number", .{}); } } } @@ -1413,17 +1413,17 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Readv { const fd_value = arguments.nextEat() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }; const fd = try JSC.Node.fileDescriptorFromJS(ctx, fd_value) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; const buffers = try JSC.Node.VectorArrayBuffer.fromJS( ctx, arguments.protectEatNext() orelse { - return ctx.throwInvalidArguments2("Expected an ArrayBufferView[]", .{}); + return ctx.throwInvalidArguments("Expected an ArrayBufferView[]", .{}); }, arguments.arena.allocator(), ); @@ -1435,7 +1435,7 @@ pub const Arguments = struct { if (pos_value.isNumber()) { position = pos_value.to(u52); } else { - return ctx.throwInvalidArguments2("position must be a number", .{}); + return ctx.throwInvalidArguments("position must be a number", .{}); } } } @@ -1462,9 +1462,9 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!FTruncate { const fd = try JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; arguments.eat(); @@ -1502,13 +1502,13 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Chown { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); const uid: uid_t = brk: { const uid_value = arguments.next() orelse break :brk { - return ctx.throwInvalidArguments2("uid is required", .{}); + return ctx.throwInvalidArguments("uid is required", .{}); }; arguments.eat(); @@ -1521,7 +1521,7 @@ pub const Arguments = struct { const gid: gid_t = brk: { const gid_value = arguments.next() orelse break :brk { - return ctx.throwInvalidArguments2("gid is required", .{}); + return ctx.throwInvalidArguments("gid is required", .{}); }; arguments.eat(); @@ -1547,14 +1547,14 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Fchown { const fd = try JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; const uid: uid_t = brk: { const uid_value = arguments.next() orelse break :brk { - return ctx.throwInvalidArguments2("uid is required", .{}); + return ctx.throwInvalidArguments("uid is required", .{}); }; arguments.eat(); @@ -1563,7 +1563,7 @@ pub const Arguments = struct { const gid: gid_t = brk: { const gid_value = arguments.next() orelse break :brk { - return ctx.throwInvalidArguments2("gid is required", .{}); + return ctx.throwInvalidArguments("gid is required", .{}); }; arguments.eat(); @@ -1595,22 +1595,22 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Lutimes { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); const atime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("atime is required", .{}); + return ctx.throwInvalidArguments("atime is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("atime must be a number or a Date", .{}); + return ctx.throwInvalidArguments("atime must be a number or a Date", .{}); }; arguments.eat(); const mtime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("mtime is required", .{}); + return ctx.throwInvalidArguments("mtime is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("mtime must be a number or a Date", .{}); + return ctx.throwInvalidArguments("mtime must be a number or a Date", .{}); }; arguments.eat(); @@ -1637,14 +1637,14 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Chmod { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); const mode: Mode = try JSC.Node.modeFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("mode is required", .{}); + return ctx.throwInvalidArguments("mode is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("mode must be a string or integer", .{}); + return ctx.throwInvalidArguments("mode must be a string or integer", .{}); }; arguments.eat(); @@ -1663,17 +1663,17 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!FChmod { const fd = try JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; arguments.eat(); const mode: Mode = try JSC.Node.modeFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("mode is required", .{}); + return ctx.throwInvalidArguments("mode is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("mode must be a string or integer", .{}); + return ctx.throwInvalidArguments("mode must be a string or integer", .{}); }; arguments.eat(); @@ -1703,7 +1703,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Stat { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); @@ -1741,9 +1741,9 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Fstat { const fd = try JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; const big_int = brk: { @@ -1787,11 +1787,11 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Link { const old_path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("oldPath must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("oldPath must be a string or TypedArray", .{}); }; const new_path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("newPath must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("newPath must be a string or TypedArray", .{}); }; return Link{ .old_path = old_path, .new_path = new_path }; @@ -1831,11 +1831,11 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Symlink { const old_path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("oldPath must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("oldPath must be a string or TypedArray", .{}); }; const new_path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("newPath must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("newPath must be a string or TypedArray", .{}); }; const link_type: LinkType = if (!Environment.isWindows) @@ -1857,8 +1857,7 @@ pub const Arguments = struct { if (str.eqlComptime("dir")) break :link_type .dir; if (str.eqlComptime("file")) break :link_type .file; if (str.eqlComptime("junction")) break :link_type .junction; - ctx.throwInvalidArguments("Symlink type must be one of \"dir\", \"file\", or \"junction\". Received \"{}\"", .{str}); - return error.JSError; + return ctx.throwInvalidArguments("Symlink type must be one of \"dir\", \"file\", or \"junction\". Received \"{}\"", .{str}); } // not a string. fallthrough to auto detect. @@ -1897,7 +1896,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Readlink { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); @@ -1939,7 +1938,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Realpath { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); @@ -1988,7 +1987,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Unlink { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); @@ -2023,7 +2022,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!RmDir { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); @@ -2079,7 +2078,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: *JSC.JSGlobalObject, arguments: *ArgumentsSlice) bun.JSError!Mkdir { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); @@ -2128,7 +2127,7 @@ pub const Arguments = struct { const prefix_value = arguments.next() orelse return MkdirTemp{}; const prefix = StringOrBuffer.fromJS(ctx, bun.default_allocator, prefix_value) orelse { - return ctx.throwInvalidArguments2("prefix must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("prefix must be a string or TypedArray", .{}); }; errdefer prefix.deinit(); @@ -2188,7 +2187,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Readdir { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); @@ -2239,9 +2238,9 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Close { const fd = try JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; return Close{ .fd = fd }; @@ -2267,7 +2266,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Open { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); @@ -2327,23 +2326,23 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Futimes { const fd = try JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; arguments.eat(); const atime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("atime is required", .{}); + return ctx.throwInvalidArguments("atime is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("atime must be a number or a Date", .{}); + return ctx.throwInvalidArguments("atime must be a number or a Date", .{}); }; arguments.eat(); const mtime = JSC.Node.timeLikeFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("mtime is required", .{}); + return ctx.throwInvalidArguments("mtime is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("mtime must be a number or a Date", .{}); + return ctx.throwInvalidArguments("mtime must be a number or a Date", .{}); }; arguments.eat(); @@ -2402,15 +2401,15 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Write { const fd = try JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; arguments.eat(); const buffer_value = arguments.next(); const buffer = StringOrBuffer.fromJS(ctx, bun.default_allocator, buffer_value orelse { - return ctx.throwInvalidArguments2("data is required", .{}); + return ctx.throwInvalidArguments("data is required", .{}); }) orelse { _ = ctx.throwInvalidArgumentTypeValue("buffer", "string or TypedArray", buffer_value.?); return error.JSError; @@ -2497,15 +2496,15 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Read { const fd = try JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; arguments.eat(); const buffer_value = arguments.next(); const buffer = Buffer.fromJS(ctx, buffer_value orelse { - return ctx.throwInvalidArguments2("buffer is required", .{}); + return ctx.throwInvalidArguments("buffer is required", .{}); }) orelse { _ = ctx.throwInvalidArgumentTypeValue("buffer", "TypedArray", buffer_value.?); return error.JSError; @@ -2524,8 +2523,7 @@ pub const Arguments = struct { args.offset = current.to(u52); if (arguments.remaining.len < 1) { - ctx.throwInvalidArguments("length is required", .{}); - return error.JSError; + return ctx.throwInvalidArguments("length is required", .{}); } const arg_length = arguments.next().?; @@ -2603,7 +2601,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!ReadFile { const path = try PathOrFileDescriptor.fromJS(ctx, arguments, bun.default_allocator) orelse { - return ctx.throwInvalidArguments2("path must be a string or a file descriptor", .{}); + return ctx.throwInvalidArguments("path must be a string or a file descriptor", .{}); }; errdefer path.deinit(); @@ -2619,7 +2617,7 @@ pub const Arguments = struct { if (try arg.getTruthy(ctx, "flag")) |flag_| { flag = try FileSystemFlags.fromJS(ctx, flag_) orelse { - return ctx.throwInvalidArguments2("Invalid flag", .{}); + return ctx.throwInvalidArguments("Invalid flag", .{}); }; } } @@ -2664,12 +2662,12 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!WriteFile { const path = try PathOrFileDescriptor.fromJS(ctx, arguments, bun.default_allocator) orelse { - return ctx.throwInvalidArguments2("path must be a string or a file descriptor", .{}); + return ctx.throwInvalidArguments("path must be a string or a file descriptor", .{}); }; errdefer path.deinit(); const data_value = arguments.nextEat() orelse { - return ctx.throwInvalidArguments2("data is required", .{}); + return ctx.throwInvalidArguments("data is required", .{}); }; var encoding = Encoding.buffer; @@ -2689,20 +2687,20 @@ pub const Arguments = struct { if (try arg.getTruthy(ctx, "flag")) |flag_| { flag = try FileSystemFlags.fromJS(ctx, flag_) orelse { - return ctx.throwInvalidArguments2("Invalid flag", .{}); + return ctx.throwInvalidArguments("Invalid flag", .{}); }; } if (try arg.getTruthy(ctx, "mode")) |mode_| { mode = try JSC.Node.modeFromJS(ctx, mode_) orelse { - return ctx.throwInvalidArguments2("Invalid mode", .{}); + return ctx.throwInvalidArguments("Invalid mode", .{}); }; } } } const data = try StringOrBuffer.fromJSWithEncodingMaybeAsync(ctx, bun.default_allocator, data_value, encoding, arguments.will_be_async) orelse { - return ctx.throwInvalidArguments2("data must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("data must be a string or TypedArray", .{}); }; // Note: Signal is not implemented @@ -2732,7 +2730,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!OpenDir { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); @@ -2751,7 +2749,7 @@ pub const Arguments = struct { if (try arg.get(ctx, "bufferSize")) |buffer_size_| { buffer_size = buffer_size_.toInt32(); if (buffer_size < 0) { - return ctx.throwInvalidArguments2("bufferSize must be > 0", .{}); + return ctx.throwInvalidArguments("bufferSize must be > 0", .{}); } } } @@ -2811,7 +2809,7 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Access { const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("path must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("path must be a string or TypedArray", .{}); }; errdefer path.deinit(); @@ -2821,7 +2819,7 @@ pub const Arguments = struct { arguments.eat(); if (arg.isString()) { mode = try FileSystemFlags.fromJS(ctx, arg) orelse { - return ctx.throwInvalidArguments2("Invalid mode", .{}); + return ctx.throwInvalidArguments("Invalid mode", .{}); }; } } @@ -2843,9 +2841,9 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!FdataSync { const fd = try JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; arguments.eat(); @@ -2875,12 +2873,12 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!CopyFile { const src = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("src must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("src must be a string or TypedArray", .{}); }; errdefer src.deinit(); const dest = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("dest must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("dest must be a string or TypedArray", .{}); }; errdefer dest.deinit(); @@ -2922,12 +2920,12 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Cp { const src = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("src must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("src must be a string or TypedArray", .{}); }; errdefer src.deinit(); const dest = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("dest must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("dest must be a string or TypedArray", .{}); }; errdefer dest.deinit(); @@ -2997,9 +2995,9 @@ pub const Arguments = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Fsync { const fd = try JSC.Node.fileDescriptorFromJS(ctx, arguments.next() orelse { - return ctx.throwInvalidArguments2("file descriptor is required", .{}); + return ctx.throwInvalidArguments("file descriptor is required", .{}); }) orelse { - return ctx.throwInvalidArguments2("file descriptor must be a number", .{}); + return ctx.throwInvalidArguments("file descriptor must be a number", .{}); }; arguments.eat(); diff --git a/src/bun.js/node/node_fs_stat_watcher.zig b/src/bun.js/node/node_fs_stat_watcher.zig index 6a774e38f9971d..55418ffca86b14 100644 --- a/src/bun.js/node/node_fs_stat_watcher.zig +++ b/src/bun.js/node/node_fs_stat_watcher.zig @@ -237,7 +237,7 @@ pub const StatWatcher = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Arguments { const vm = ctx.vm(); const path = try PathLike.fromJSWithAllocator(ctx, arguments, bun.default_allocator) orelse { - return ctx.throwInvalidArguments2("filename must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("filename must be a string or TypedArray", .{}); }; var listener: JSC.JSValue = .zero; @@ -256,7 +256,7 @@ pub const StatWatcher = struct { if (try options_or_callable.get(ctx, "interval")) |interval_| { if (!interval_.isNumber() and !interval_.isAnyInt()) { - return ctx.throwInvalidArguments2("interval must be a number", .{}); + return ctx.throwInvalidArguments("interval must be a number", .{}); } interval = interval_.coerce(i32, ctx); } @@ -270,7 +270,7 @@ pub const StatWatcher = struct { } if (listener == .zero) { - return ctx.throwInvalidArguments2("Expected \"listener\" callback", .{}); + return ctx.throwInvalidArguments("Expected \"listener\" callback", .{}); } return Arguments{ diff --git a/src/bun.js/node/node_fs_watcher.zig b/src/bun.js/node/node_fs_watcher.zig index d9f294aaf04ad7..f2ccb8258cda0a 100644 --- a/src/bun.js/node/node_fs_watcher.zig +++ b/src/bun.js/node/node_fs_watcher.zig @@ -344,7 +344,7 @@ pub const FSWatcher = struct { pub fn fromJS(ctx: JSC.C.JSContextRef, arguments: *ArgumentsSlice) bun.JSError!Arguments { const vm = ctx.vm(); const path = try PathLike.fromJS(ctx, arguments) orelse { - return ctx.throwInvalidArguments2("filename must be a string or TypedArray", .{}); + return ctx.throwInvalidArguments("filename must be a string or TypedArray", .{}); }; var should_deinit_path = true; defer if (should_deinit_path) path.deinit(); @@ -361,14 +361,14 @@ pub const FSWatcher = struct { if (options_or_callable.isObject()) { if (try options_or_callable.getTruthy(ctx, "persistent")) |persistent_| { if (!persistent_.isBoolean()) { - return ctx.throwInvalidArguments2("persistent must be a boolean", .{}); + return ctx.throwInvalidArguments("persistent must be a boolean", .{}); } persistent = persistent_.toBoolean(); } if (try options_or_callable.getTruthy(ctx, "verbose")) |verbose_| { if (!verbose_.isBoolean()) { - return ctx.throwInvalidArguments2("verbose must be a boolean", .{}); + return ctx.throwInvalidArguments("verbose must be a boolean", .{}); } verbose = verbose_.toBoolean(); } @@ -379,7 +379,7 @@ pub const FSWatcher = struct { if (try options_or_callable.getTruthy(ctx, "recursive")) |recursive_| { if (!recursive_.isBoolean()) { - return ctx.throwInvalidArguments2("recursive must be a boolean", .{}); + return ctx.throwInvalidArguments("recursive must be a boolean", .{}); } recursive = recursive_.toBoolean(); } @@ -391,26 +391,26 @@ pub const FSWatcher = struct { signal_.ensureStillAlive(); signal = signal_obj; } else { - return ctx.throwInvalidArguments2("signal is not of type AbortSignal", .{}); + return ctx.throwInvalidArguments("signal is not of type AbortSignal", .{}); } } // listener if (arguments.nextEat()) |callable| { if (!callable.isCell() or !callable.isCallable(vm)) { - return ctx.throwInvalidArguments2("Expected \"listener\" callback to be a function", .{}); + return ctx.throwInvalidArguments("Expected \"listener\" callback to be a function", .{}); } listener = callable; } } else { if (!options_or_callable.isCell() or !options_or_callable.isCallable(vm)) { - return ctx.throwInvalidArguments2("Expected \"listener\" callback to be a function", .{}); + return ctx.throwInvalidArguments("Expected \"listener\" callback to be a function", .{}); } listener = options_or_callable; } } if (listener == .zero) { - return ctx.throwInvalidArguments2("Expected \"listener\" callback", .{}); + return ctx.throwInvalidArguments("Expected \"listener\" callback", .{}); } should_deinit_path = false; diff --git a/src/bun.js/node/node_net_binding.zig b/src/bun.js/node/node_net_binding.zig index 696cea44bd1a23..6a3a50350c34a0 100644 --- a/src/bun.js/node/node_net_binding.zig +++ b/src/bun.js/node/node_net_binding.zig @@ -26,13 +26,11 @@ pub fn setDefaultAutoSelectFamily(global: *JSC.JSGlobalObject) JSC.JSValue { fn setter(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { const arguments = callframe.arguments_old(1); if (arguments.len < 1) { - globalThis.throw("missing argument", .{}); - return .undefined; + return globalThis.throw2("missing argument", .{}); } const arg = arguments.slice()[0]; if (!arg.isBoolean()) { - globalThis.throwInvalidArguments("autoSelectFamilyDefault", .{}); - return .undefined; + return globalThis.throwInvalidArguments("autoSelectFamilyDefault", .{}); } const value = arg.toBoolean(); autoSelectFamilyDefault = value; @@ -61,13 +59,11 @@ pub fn setDefaultAutoSelectFamilyAttemptTimeout(global: *JSC.JSGlobalObject) JSC fn setter(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { const arguments = callframe.arguments_old(1); if (arguments.len < 1) { - globalThis.throw("missing argument", .{}); - return .undefined; + return globalThis.throw2("missing argument", .{}); } const arg = arguments.slice()[0]; if (!arg.isInt32AsAnyInt()) { - globalThis.throwInvalidArguments("autoSelectFamilyAttemptTimeoutDefault", .{}); - return .undefined; + return globalThis.throwInvalidArguments("autoSelectFamilyAttemptTimeoutDefault", .{}); } const value: u32 = @max(10, arg.coerceToInt32(globalThis)); autoSelectFamilyAttemptTimeoutDefault = value; diff --git a/src/bun.js/node/types.zig b/src/bun.js/node/types.zig index 08d38ca328496d..0078f691842209 100644 --- a/src/bun.js/node/types.zig +++ b/src/bun.js/node/types.zig @@ -397,7 +397,7 @@ pub const BlobOrStringOrBuffer = union(enum) { return .{ .blob = any_blob.toBlob(global) }; } - return global.throwInvalidArguments2("Only buffered Request/Response bodies are supported for now.", .{}); + return global.throwInvalidArguments("Only buffered Request/Response bodies are supported for now.", .{}); } if (value.as(JSC.WebCore.Response)) |response| { @@ -409,7 +409,7 @@ pub const BlobOrStringOrBuffer = union(enum) { return .{ .blob = any_blob.toBlob(global) }; } - return global.throwInvalidArguments2("Only buffered Request/Response bodies are supported for now.", .{}); + return global.throwInvalidArguments("Only buffered Request/Response bodies are supported for now.", .{}); } } }, @@ -990,8 +990,7 @@ pub const PathLike = union(enum) { var str: bun.String = domurl.fileSystemPath(); defer str.deref(); if (str.isEmpty()) { - ctx.throwInvalidArguments("URL must be a non-empty \"file:\" path", .{}); - return error.JSError; + return ctx.throwInvalidArguments("URL must be a non-empty \"file:\" path", .{}); } arguments.eat(); @@ -1031,15 +1030,13 @@ pub const PathLike = union(enum) { pub const Valid = struct { pub fn fileDescriptor(fd: i64, ctx: JSC.C.JSContextRef) bun.JSError!void { if (fd < 0) { - ctx.throwInvalidArguments("Invalid file descriptor, must not be negative number", .{}); - return error.JSError; + return ctx.throwInvalidArguments("Invalid file descriptor, must not be negative number", .{}); } const fd_t = if (Environment.isWindows) bun.windows.libuv.uv_file else bun.FileDescriptorInt; if (fd > std.math.maxInt(fd_t)) { - ctx.throwInvalidArguments("Invalid file descriptor, must not be greater than {d}", .{std.math.maxInt(fd_t)}); - return error.JSError; + return ctx.throwInvalidArguments("Invalid file descriptor, must not be greater than {d}", .{std.math.maxInt(fd_t)}); } } @@ -1079,8 +1076,7 @@ pub const Valid = struct { const slice = buffer.slice(); switch (slice.len) { 0 => { - ctx.throwInvalidArguments("Invalid path buffer: can't be empty", .{}); - return error.JSError; + return ctx.throwInvalidArguments("Invalid path buffer: can't be empty", .{}); }, else => { var system_error = bun.sys.Error.fromCode(.NAMETOOLONG, .open).toSystemError(); @@ -1104,7 +1100,7 @@ pub const VectorArrayBuffer = struct { pub fn fromJS(globalObject: *JSC.JSGlobalObject, val: JSC.JSValue, allocator: std.mem.Allocator) bun.JSError!VectorArrayBuffer { if (!val.jsType().isArrayLike()) { - return globalObject.throwInvalidArguments2("Expected ArrayBufferView[]", .{}); + return globalObject.throwInvalidArguments("Expected ArrayBufferView[]", .{}); } var bufferlist = std.ArrayList(bun.PlatformIOVec).init(allocator); @@ -1116,11 +1112,11 @@ pub const VectorArrayBuffer = struct { const element = val.getIndex(globalObject, @as(u32, @truncate(i))); if (!element.isCell()) { - return globalObject.throwInvalidArguments2("Expected ArrayBufferView[]", .{}); + return globalObject.throwInvalidArguments("Expected ArrayBufferView[]", .{}); } const array_buffer = element.asArrayBuffer(globalObject) orelse { - return globalObject.throwInvalidArguments2("Expected ArrayBufferView[]", .{}); + return globalObject.throwInvalidArguments("Expected ArrayBufferView[]", .{}); }; const buf = array_buffer.byteSlice(); @@ -1474,11 +1470,11 @@ pub const FileSystemFlags = enum(Mode) { if (jsType.isStringLike()) { const str = val.getZigString(ctx); if (str.isEmpty()) { - return ctx.throwInvalidArguments2("Expected flags to be a non-empty string. Learn more at https://nodejs.org/api/fs.html#fs_file_system_flags", .{}); + return ctx.throwInvalidArguments("Expected flags to be a non-empty string. Learn more at https://nodejs.org/api/fs.html#fs_file_system_flags", .{}); } // it's definitely wrong when the string is super long else if (str.len > 12) { - return ctx.throwInvalidArguments2("Invalid flag '{any}'. Learn more at https://nodejs.org/api/fs.html#fs_file_system_flags", .{str}); + return ctx.throwInvalidArguments("Invalid flag '{any}'. Learn more at https://nodejs.org/api/fs.html#fs_file_system_flags", .{str}); } const flags = brk: { @@ -1502,7 +1498,7 @@ pub const FileSystemFlags = enum(Mode) { break :brk map.getWithEql(str, JSC.ZigString.eqlComptime); } orelse { - return ctx.throwInvalidArguments2("Invalid flag '{any}'. Learn more at https://nodejs.org/api/fs.html#fs_file_system_flags", .{str}); + return ctx.throwInvalidArguments("Invalid flag '{any}'. Learn more at https://nodejs.org/api/fs.html#fs_file_system_flags", .{str}); }; return @as(FileSystemFlags, @enumFromInt(@as(Mode, @intCast(flags)))); @@ -1740,7 +1736,7 @@ pub fn StatType(comptime Big: bool) type { pub fn constructor(globalObject: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!*This { if (Big) { - return globalObject.throwInvalidArguments2("BigIntStats is not a constructor", .{}); + return globalObject.throwInvalidArguments("BigIntStats is not a constructor", .{}); } // dev, mode, nlink, uid, gid, rdev, blksize, ino, size, blocks, atimeMs, mtimeMs, ctimeMs, birthtimeMs @@ -2079,21 +2075,25 @@ pub const Process = struct { return bun.String.toJSArray(globalObject, args_list.items); } - pub fn getCwd(globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { + pub fn getCwd(globalObject: *JSC.JSGlobalObject) callconv(JSC.conv) JSC.JSValue { + return JSC.toJSHostValue(globalObject, getCwd_(globalObject)); + } + fn getCwd_(globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { var buf: bun.PathBuffer = undefined; switch (Path.getCwd(&buf)) { .result => |r| return JSC.ZigString.init(r).withEncoding().toJS(globalObject), .err => |e| { - globalObject.throwValue(e.toJSC(globalObject)); - return .zero; + return globalObject.throwValue2(e.toJSC(globalObject)); }, } } - pub fn setCwd(globalObject: *JSC.JSGlobalObject, to: *JSC.ZigString) callconv(.C) JSC.JSValue { + pub fn setCwd(globalObject: *JSC.JSGlobalObject, to: *JSC.ZigString) callconv(JSC.conv) JSC.JSValue { + return JSC.toJSHostValue(globalObject, setCwd_(globalObject, to)); + } + fn setCwd_(globalObject: *JSC.JSGlobalObject, to: *JSC.ZigString) bun.JSError!JSC.JSValue { if (to.len == 0) { - globalObject.throwInvalidArguments("Expected path to be a non-empty string", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected path to be a non-empty string", .{}); } var buf: bun.PathBuffer = undefined; diff --git a/src/bun.js/test/expect.zig b/src/bun.js/test/expect.zig index eb2973b9313ab7..642c5ec36dc2da 100644 --- a/src/bun.js/test/expect.zig +++ b/src/bun.js/test/expect.zig @@ -516,8 +516,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toBe() takes 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBe() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -583,8 +582,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toHaveLength() takes 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toHaveLength() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -658,8 +656,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toBeOneOf() takes 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeOneOf() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -744,8 +741,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toContain() takes 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toContain() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -842,8 +838,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toContainKey() takes 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toContainKey() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -855,8 +850,7 @@ pub const Expect = struct { const not = this.flags.not; if (!value.isObject()) { - globalThis.throwInvalidArguments("Expected value must be an object\nReceived: {}", .{value.toFmt(&formatter)}); - return .zero; + return globalThis.throwInvalidArguments("Expected value must be an object\nReceived: {}", .{value.toFmt(&formatter)}); } var pass = value.hasOwnPropertyValue(globalThis, expected); @@ -898,8 +892,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toContainKeys() takes 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toContainKeys() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -971,8 +964,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalObject.throwInvalidArguments("toContainAllKeys() takes 1 argument", .{}); - return .zero; + return globalObject.throwInvalidArguments("toContainAllKeys() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -1039,8 +1031,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toContainAnyKeys() takes 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toContainAnyKeys() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -1107,8 +1098,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalObject.throwInvalidArguments("toContainValue() takes 1 argument", .{}); - return .zero; + return globalObject.throwInvalidArguments("toContainValue() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -1164,8 +1154,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalObject.throwInvalidArguments("toContainValues() takes 1 argument", .{}); - return .zero; + return globalObject.throwInvalidArguments("toContainValues() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -1231,8 +1220,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalObject.throwInvalidArguments("toContainAllValues() takes 1 argument", .{}); - return .zero; + return globalObject.throwInvalidArguments("toContainAllValues() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -1304,8 +1292,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalObject.throwInvalidArguments("toContainAnyValues() takes 1 argument", .{}); - return .zero; + return globalObject.throwInvalidArguments("toContainAnyValues() takes 1 argument", .{}); } incrementExpectCallCounter(); @@ -1371,8 +1358,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toContainEqual() takes 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toContainEqual() takes 1 argument", .{}); } active_test_expectation_counter.actual += 1; @@ -1662,8 +1648,7 @@ pub const Expect = struct { const arguments: []const JSValue = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toEqual() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toEqual() requires 1 argument", .{}); } incrementExpectCallCounter(); @@ -1704,8 +1689,7 @@ pub const Expect = struct { const arguments: []const JSValue = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toStrictEqual() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toStrictEqual() requires 1 argument", .{}); } incrementExpectCallCounter(); @@ -1741,8 +1725,7 @@ pub const Expect = struct { const arguments: []const JSValue = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toHaveProperty() requires at least 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toHaveProperty() requires at least 1 argument", .{}); } incrementExpectCallCounter(); @@ -1890,8 +1873,7 @@ pub const Expect = struct { const arguments: []const JSValue = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toBeGreaterThan() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeGreaterThan() requires 1 argument", .{}); } incrementExpectCallCounter(); @@ -1953,8 +1935,7 @@ pub const Expect = struct { const arguments: []const JSValue = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toBeGreaterThanOrEqual() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeGreaterThanOrEqual() requires 1 argument", .{}); } incrementExpectCallCounter(); @@ -2016,8 +1997,7 @@ pub const Expect = struct { const arguments: []const JSValue = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toBeLessThan() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeLessThan() requires 1 argument", .{}); } incrementExpectCallCounter(); @@ -2079,8 +2059,7 @@ pub const Expect = struct { const arguments: []const JSValue = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toBeLessThanOrEqual() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeLessThanOrEqual() requires 1 argument", .{}); } incrementExpectCallCounter(); @@ -2142,8 +2121,7 @@ pub const Expect = struct { const arguments = thisArguments.ptr[0..thisArguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toBeCloseTo() requires at least 1 argument. Expected value must be a number", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeCloseTo() requires at least 1 argument. Expected value must be a number", .{}); } const expected_ = arguments[0]; @@ -2930,8 +2908,7 @@ pub const Expect = struct { const arguments = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toBeArrayOfSize() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeArrayOfSize() requires 1 argument", .{}); } const value: JSValue = try this.getValue(globalThis, thisValue, "toBeArrayOfSize", ""); @@ -3001,8 +2978,7 @@ pub const Expect = struct { const arguments = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toBeTypeOf() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeTypeOf() requires 1 argument", .{}); } const value: JSValue = try this.getValue(globalThis, thisValue, "toBeTypeOf", ""); @@ -3011,8 +2987,7 @@ pub const Expect = struct { expected.ensureStillAlive(); if (!expected.isString()) { - globalThis.throwInvalidArguments("toBeTypeOf() requires a string argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeTypeOf() requires a string argument", .{}); } const expected_type = expected.toBunString(globalThis); @@ -3020,8 +2995,7 @@ pub const Expect = struct { incrementExpectCallCounter(); const typeof = expected_type.inMap(JSTypeOfMap) orelse { - globalThis.throwInvalidArguments("toBeTypeOf() requires a valid type string argument ('function', 'object', 'bigint', 'boolean', 'number', 'string', 'symbol', 'undefined')", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeTypeOf() requires a valid type string argument ('function', 'object', 'bigint', 'boolean', 'number', 'string', 'symbol', 'undefined')", .{}); }; const not = this.flags.not; @@ -3312,8 +3286,7 @@ pub const Expect = struct { const arguments = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toBeWithin() requires 2 arguments", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeWithin() requires 2 arguments", .{}); } const value: JSValue = try this.getValue(globalThis, thisValue, "toBeWithin", "start, end"); @@ -3375,8 +3348,7 @@ pub const Expect = struct { const arguments: []const JSValue = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toEqualIgnoringWhitespace() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toEqualIgnoringWhitespace() requires 1 argument", .{}); } incrementExpectCallCounter(); @@ -3593,8 +3565,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toInclude() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toInclude() requires 1 argument", .{}); } const expected = arguments[0]; @@ -3650,8 +3621,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 2) { - globalThis.throwInvalidArguments("toIncludeRepeated() requires 2 arguments", .{}); - return .zero; + return globalThis.throwInvalidArguments("toIncludeRepeated() requires 2 arguments", .{}); } incrementExpectCallCounter(); @@ -3761,8 +3731,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toSatisfy() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toSatisfy() requires 1 argument", .{}); } incrementExpectCallCounter(); @@ -3819,8 +3788,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toStartWith() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toStartWith() requires 1 argument", .{}); } const expected = arguments[0]; @@ -3876,8 +3844,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("toEndWith() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toEndWith() requires 1 argument", .{}); } const expected = arguments[0]; @@ -3933,8 +3900,7 @@ pub const Expect = struct { const arguments: []const JSValue = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toBeInstanceOf() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toBeInstanceOf() requires 1 argument", .{}); } incrementExpectCallCounter(); @@ -3982,8 +3948,7 @@ pub const Expect = struct { const arguments: []const JSValue = _arguments.ptr[0.._arguments.len]; if (arguments.len < 1) { - globalThis.throwInvalidArguments("toMatch() requires 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toMatch() requires 1 argument", .{}); } incrementExpectCallCounter(); @@ -4088,8 +4053,7 @@ pub const Expect = struct { } if (arguments.len < 1 or !arguments[0].isUInt32AsAnyInt()) { - globalThis.throwInvalidArguments("toHaveBeenCalledTimes() requires 1 non-negative integer argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toHaveBeenCalledTimes() requires 1 non-negative integer argument", .{}); } const times = arguments[0].coerce(i32, globalThis); @@ -4320,8 +4284,7 @@ pub const Expect = struct { const nthCallNum = if (arguments.len > 0 and arguments[0].isUInt32AsAnyInt()) arguments[0].coerce(i32, globalThis) else 0; if (nthCallNum < 1) { - globalThis.throwInvalidArguments("toHaveBeenNthCalledWith() requires a positive integer argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("toHaveBeenNthCalledWith() requires a positive integer argument", .{}); } const totalCalls = calls.getLength(globalThis); @@ -4399,8 +4362,7 @@ pub const Expect = struct { const return_count: i32 = if (known_index) |index| index else brk: { if (arguments.len < 1 or !arguments[0].isUInt32AsAnyInt()) { - globalThis.throwInvalidArguments(name ++ "() requires 1 non-negative integer argument", .{}); - return .zero; + return globalThis.throwInvalidArguments(name ++ "() requires 1 non-negative integer argument", .{}); } break :brk arguments[0].coerce(i32, globalThis); @@ -4545,8 +4507,7 @@ pub const Expect = struct { if (!matcher_fn.jsType().isFunction()) { const type_name = if (matcher_fn.isNull()) bun.String.static("null") else bun.String.init(matcher_fn.jsTypeString(globalThis).getZigString(globalThis)); - globalThis.throwInvalidArguments("expect.extend: `{s}` is not a valid matcher. Must be a function, is \"{s}\"", .{ matcher_name, type_name }); - return .zero; + return globalThis.throwInvalidArguments("expect.extend: `{s}` is not a valid matcher. Must be a function, is \"{s}\"", .{ matcher_name, type_name }); } // Mutate the Expect/ExpectStatic prototypes/constructor with new instances of JSCustomExpectMatcherFunction. @@ -4819,8 +4780,7 @@ pub const Expect = struct { const arguments = arguments_.slice(); if (arguments.len < 1) { - globalThis.throwInvalidArguments("expect.assertions() takes 1 argument", .{}); - return .zero; + return globalThis.throwInvalidArguments("expect.assertions() takes 1 argument", .{}); } const expected: JSValue = arguments[0]; diff --git a/src/bun.js/webcore.zig b/src/bun.js/webcore.zig index 3aa760f2a142a0..e899de489de879 100644 --- a/src/bun.js/webcore.zig +++ b/src/bun.js/webcore.zig @@ -545,27 +545,20 @@ pub const Crypto = struct { return .zero; } - pub fn timingSafeEqual( - _: *@This(), - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, - ) bun.JSError!JSC.JSValue { + pub fn timingSafeEqual(_: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { const arguments = callframe.arguments_old(2).slice(); if (arguments.len < 2) { - globalThis.throwInvalidArguments("Expected 2 typed arrays but got nothing", .{}); - return .undefined; + return globalThis.throwInvalidArguments("Expected 2 typed arrays but got nothing", .{}); } const array_buffer_a = arguments[0].asArrayBuffer(globalThis) orelse { - globalThis.throwInvalidArguments("Expected typed array but got {s}", .{@tagName(arguments[0].jsType())}); - return .undefined; + return globalThis.throwInvalidArguments("Expected typed array but got {s}", .{@tagName(arguments[0].jsType())}); }; const a = array_buffer_a.byteSlice(); const array_buffer_b = arguments[1].asArrayBuffer(globalThis) orelse { - globalThis.throwInvalidArguments("Expected typed array but got {s}", .{@tagName(arguments[1].jsType())}); - return .undefined; + return globalThis.throwInvalidArguments("Expected typed array but got {s}", .{@tagName(arguments[1].jsType())}); }; const b = array_buffer_b.byteSlice(); @@ -602,13 +595,11 @@ pub const Crypto = struct { ) bun.JSError!JSC.JSValue { const arguments = callframe.arguments_old(1).slice(); if (arguments.len == 0) { - globalThis.throwInvalidArguments("Expected typed array but got nothing", .{}); - return .undefined; + return globalThis.throwInvalidArguments("Expected typed array but got nothing", .{}); } var array_buffer = arguments[0].asArrayBuffer(globalThis) orelse { - globalThis.throwInvalidArguments("Expected typed array but got {s}", .{@tagName(arguments[0].jsType())}); - return .undefined; + return globalThis.throwInvalidArguments("Expected typed array but got {s}", .{@tagName(arguments[0].jsType())}); }; const slice = array_buffer.byteSlice(); diff --git a/src/bun.js/webcore/ObjectURLRegistry.zig b/src/bun.js/webcore/ObjectURLRegistry.zig index 7f83f8f96c0063..846c1c04343bd9 100644 --- a/src/bun.js/webcore/ObjectURLRegistry.zig +++ b/src/bun.js/webcore/ObjectURLRegistry.zig @@ -99,7 +99,7 @@ fn Bun__createObjectURL_(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Call return globalObject.throwNotEnoughArguments("createObjectURL", 1, arguments.len); } const blob = arguments.ptr[0].as(JSC.WebCore.Blob) orelse { - return globalObject.throwInvalidArguments2("createObjectURL expects a Blob object", .{}); + return globalObject.throwInvalidArguments("createObjectURL expects a Blob object", .{}); }; const registry = ObjectURLRegistry.singleton(); const uuid = registry.register(globalObject.bunVM(), blob); @@ -117,7 +117,7 @@ fn Bun__revokeObjectURL_(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Call return globalObject.throwNotEnoughArguments("revokeObjectURL", 1, arguments.len); } if (!arguments.ptr[0].isString()) { - return globalObject.throwInvalidArguments2("revokeObjectURL expects a string", .{}); + return globalObject.throwInvalidArguments("revokeObjectURL expects a string", .{}); } const str = arguments.ptr[0].toBunString(globalObject); if (!str.hasPrefixComptime("blob:")) { diff --git a/src/bun.js/webcore/blob.zig b/src/bun.js/webcore/blob.zig index e828b96017b862..a475d6b968dd4a 100644 --- a/src/bun.js/webcore/blob.zig +++ b/src/bun.js/webcore/blob.zig @@ -983,19 +983,16 @@ pub const Blob = struct { } var data = args.nextEat() orelse { - globalThis.throwInvalidArguments("Bun.write(pathOrFdOrBlob, blob) expects a Blob-y thing to write", .{}); - return .zero; + return globalThis.throwInvalidArguments("Bun.write(pathOrFdOrBlob, blob) expects a Blob-y thing to write", .{}); }; if (data.isEmptyOrUndefinedOrNull()) { - globalThis.throwInvalidArguments("Bun.write(pathOrFdOrBlob, blob) expects a Blob-y thing to write", .{}); - return .zero; + return globalThis.throwInvalidArguments("Bun.write(pathOrFdOrBlob, blob) expects a Blob-y thing to write", .{}); } if (path_or_blob == .blob) { if (path_or_blob.blob.store == null) { - globalThis.throwInvalidArguments("Blob is detached", .{}); - return .zero; + return globalThis.throwInvalidArguments("Blob is detached", .{}); } else { // TODO only reset last_modified on success paths instead of // resetting last_modified at the beginning for better performance. @@ -1036,8 +1033,7 @@ pub const Blob = struct { path_or_blob.blob.store.?.data == .file and path_or_blob.blob.store.?.data.file.pathlike == .fd) { - globalThis.throwInvalidArguments("Cannot create a directory for a file descriptor", .{}); - return .zero; + return globalThis.throwInvalidArguments("Cannot create a directory for a file descriptor", .{}); } } @@ -1134,8 +1130,7 @@ pub const Blob = struct { } else path_or_blob.blob.dupe(); if (destination_blob.store == null) { - globalThis.throwInvalidArguments("Writing to an empty blob is not implemented yet", .{}); - return .zero; + return globalThis.throwInvalidArguments("Writing to an empty blob is not implemented yet", .{}); } // TODO: implement a writeev() fast path @@ -1210,11 +1205,7 @@ pub const Blob = struct { false, ) catch |err| { if (err == error.InvalidArguments) { - globalThis.throwInvalidArguments( - "Expected an Array", - .{}, - ); - return .zero; + return globalThis.throwInvalidArguments("Expected an Array", .{}); } globalThis.throwOutOfMemory(); @@ -1428,7 +1419,7 @@ pub const Blob = struct { }, }; } - pub fn JSDOMFile__construct_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!?*Blob { + pub fn JSDOMFile__construct_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*Blob { JSC.markBinding(@src()); const allocator = bun.default_allocator; var blob: Blob = undefined; @@ -1436,27 +1427,21 @@ pub const Blob = struct { const args = arguments.slice(); if (args.len < 2) { - globalThis.throwInvalidArguments("new File(bits, name) expects at least 2 arguments", .{}); - return null; + return globalThis.throwInvalidArguments("new File(bits, name) expects at least 2 arguments", .{}); } { const name_value_str = bun.String.tryFromJS(args[1], globalThis) orelse { if (!globalThis.hasException()) { - globalThis.throwInvalidArguments("new File(bits, name) expects string as the second argument", .{}); + return globalThis.throwInvalidArguments("new File(bits, name) expects string as the second argument", .{}); } - return null; + return error.JSError; }; defer name_value_str.deref(); blob = get(globalThis, args[0], false, true) catch |err| switch (err) { - error.JSError => return null, - error.OutOfMemory => { - globalThis.throwOutOfMemory(); - return null; - }, + error.JSError, error.OutOfMemory => |e| return e, error.InvalidArguments => { - globalThis.throwInvalidArguments("new Blob() expects an Array", .{}); - return null; + return globalThis.throwInvalidArguments("new Blob() expects an Array", .{}); }, }; @@ -1570,8 +1555,7 @@ pub const Blob = struct { defer args.deinit(); var path = (try JSC.Node.PathOrFileDescriptor.fromJS(globalObject, &args, bun.default_allocator)) orelse { - globalObject.throwInvalidArguments("Expected file path string or file descriptor", .{}); - return .zero; + return globalObject.throwInvalidArguments("Expected file path string or file descriptor", .{}); }; defer path.deinitAndUnprotect(); @@ -3267,8 +3251,7 @@ pub const Blob = struct { var arguments = arguments_.ptr[0..arguments_.len]; if (arguments.len > 0) { if (!arguments[0].isNumber() and !arguments[0].isUndefinedOrNull()) { - globalThis.throwInvalidArguments("chunkSize must be a number", .{}); - return JSValue.jsUndefined(); + return globalThis.throwInvalidArguments("chunkSize must be a number", .{}); } recommended_chunk_size = @as(SizeType, @intCast(@max(0, @as(i52, @truncate(arguments[0].toInt64()))))); @@ -3471,15 +3454,15 @@ pub const Blob = struct { var arguments = arguments_.ptr[0..arguments_.len]; if (!arguments.ptr[0].isEmptyOrUndefinedOrNull() and !arguments.ptr[0].isObject()) { - return globalThis.throwInvalidArguments2("options must be an object or undefined", .{}); + return globalThis.throwInvalidArguments("options must be an object or undefined", .{}); } var store = this.store orelse { - return globalThis.throwInvalidArguments2("Blob is detached", .{}); + return globalThis.throwInvalidArguments("Blob is detached", .{}); }; if (store.data != .file) { - return globalThis.throwInvalidArguments2("Blob is read-only", .{}); + return globalThis.throwInvalidArguments("Blob is read-only", .{}); } if (Environment.isWindows) { @@ -3954,7 +3937,7 @@ pub const Blob = struct { else => { blob = get(globalThis, args[0], false, true) catch |err| switch (err) { error.OutOfMemory, error.JSError => |e| return e, - error.InvalidArguments => return globalThis.throwInvalidArguments2("new Blob() expects an Array", .{}), + error.InvalidArguments => return globalThis.throwInvalidArguments("new Blob() expects an Array", .{}), }; if (args.len > 1) { diff --git a/src/bun.js/webcore/body.zig b/src/bun.js/webcore/body.zig index 10923cbeb5a398..2af66da2321bef 100644 --- a/src/bun.js/webcore/body.zig +++ b/src/bun.js/webcore/body.zig @@ -638,10 +638,10 @@ pub const Body = struct { .Blob = Blob.get(globalThis, value, true, false) catch |err| { if (!globalThis.hasException()) { if (err == error.InvalidArguments) { - return globalThis.throwInvalidArguments2("Expected an Array", .{}); + return globalThis.throwInvalidArguments("Expected an Array", .{}); } - return globalThis.throwInvalidArguments2("Invalid Body object", .{}); + return globalThis.throwInvalidArguments("Invalid Body object", .{}); } return error.JSError; diff --git a/src/bun.js/webcore/encoding.zig b/src/bun.js/webcore/encoding.zig index f3846d35f14917..3403a473773752 100644 --- a/src/bun.js/webcore/encoding.zig +++ b/src/bun.js/webcore/encoding.zig @@ -771,8 +771,7 @@ pub const TextDecoder = struct { break :input_slice array_buffer.slice(); } - globalThis.throwInvalidArguments("TextDecoder.decode expects an ArrayBuffer or TypedArray", .{}); - return .zero; + return globalThis.throwInvalidArguments("TextDecoder.decode expects an ArrayBuffer or TypedArray", .{}); }; const stream = stream: { @@ -794,11 +793,11 @@ pub const TextDecoder = struct { }; } - pub fn decodeWithoutTypeChecks(this: *TextDecoder, globalThis: *JSC.JSGlobalObject, uint8array: *JSC.JSUint8Array) JSValue { + pub fn decodeWithoutTypeChecks(this: *TextDecoder, globalThis: *JSC.JSGlobalObject, uint8array: *JSC.JSUint8Array) bun.JSError!JSValue { return this.decodeSlice(globalThis, uint8array.slice(), false); } - fn decodeSlice(this: *TextDecoder, globalThis: *JSC.JSGlobalObject, buffer_slice: []const u8, comptime flush: bool) JSValue { + fn decodeSlice(this: *TextDecoder, globalThis: *JSC.JSGlobalObject, buffer_slice: []const u8, comptime flush: bool) bun.JSError!JSValue { switch (this.encoding) { EncodingLabel.latin1 => { if (strings.isAllASCII(buffer_slice)) { @@ -810,10 +809,7 @@ pub const TextDecoder = struct { // // It's not clear why we couldn't jusst use Latin1 here, but tests failures proved it necessary. const out_length = strings.elementLengthLatin1IntoUTF16([]const u8, buffer_slice); - const bytes = globalThis.allocator().alloc(u16, out_length) catch { - globalThis.throwOutOfMemory(); - return .zero; - }; + const bytes = try globalThis.allocator().alloc(u16, out_length); const out = strings.copyLatin1IntoUTF16([]u16, bytes, []const u8, buffer_slice); return ZigString.toExternalU16(bytes.ptr, out.written, globalThis); @@ -827,10 +823,7 @@ pub const TextDecoder = struct { if (this.buffered.len > 0) { defer this.buffered.len = 0; - const joined = bun.default_allocator.alloc(u8, maybe_without_bom.len + this.buffered.len) catch { - globalThis.throwOutOfMemory(); - return .zero; - }; + const joined = try bun.default_allocator.alloc(u8, maybe_without_bom.len + this.buffered.len); @memcpy(joined[0..this.buffered.len], this.buffered.slice()); @memcpy(joined[this.buffered.len..][0..maybe_without_bom.len], maybe_without_bom); break :input .{ joined, true }; @@ -845,13 +838,13 @@ pub const TextDecoder = struct { if (comptime fail_if_invalid) { if (err == error.InvalidByteSequence) { globalThis.ERR_ENCODING_INVALID_ENCODED_DATA("Invalid byte sequence", .{}).throw(); - return .zero; + return error.JSError; } } bun.assert(err == error.OutOfMemory); globalThis.throwOutOfMemory(); - return .zero; + return error.JSError; }, }; @@ -881,23 +874,19 @@ pub const TextDecoder = struct { else buffer_slice; - var decoded, const saw_error = this.decodeUTF16(input, utf16_encoding == .@"UTF-16BE", flush) catch { - globalThis.throwOutOfMemory(); - return .zero; - }; + var decoded, const saw_error = try this.decodeUTF16(input, utf16_encoding == .@"UTF-16BE", flush); if (saw_error and this.fatal) { decoded.deinit(bun.default_allocator); globalThis.ERR_ENCODING_INVALID_ENCODED_DATA("The encoded data was not valid {s} data", .{@tagName(utf16_encoding)}).throw(); - return .zero; + return error.JSError; } var output = bun.String.fromUTF16(decoded.items); return output.toJS(globalThis); }, else => { - globalThis.throwInvalidArguments("TextDecoder.decode set to unsupported encoding", .{}); - return .zero; + return globalThis.throwInvalidArguments("TextDecoder.decode set to unsupported encoding", .{}); }, } } @@ -917,27 +906,27 @@ pub const TextDecoder = struct { if (EncodingLabel.which(str.slice())) |label| { decoder.encoding = label; } else { - return globalThis.throwInvalidArguments2("Unsupported encoding label \"{s}\"", .{str.slice()}); + return globalThis.throwInvalidArguments("Unsupported encoding label \"{s}\"", .{str.slice()}); } } else if (arguments[0].isUndefined()) { // default to utf-8 decoder.encoding = EncodingLabel.@"UTF-8"; } else { - return globalThis.throwInvalidArguments2("TextDecoder(encoding) label is invalid", .{}); + return globalThis.throwInvalidArguments("TextDecoder(encoding) label is invalid", .{}); } if (arguments.len >= 2) { const options = arguments[1]; if (!options.isObject()) { - return globalThis.throwInvalidArguments2("TextDecoder(options) is invalid", .{}); + return globalThis.throwInvalidArguments("TextDecoder(options) is invalid", .{}); } if (try options.get(globalThis, "fatal")) |fatal| { if (fatal.isBoolean()) { decoder.fatal = fatal.asBoolean(); } else { - return globalThis.throwInvalidArguments2("TextDecoder(options) fatal is invalid. Expected boolean value", .{}); + return globalThis.throwInvalidArguments("TextDecoder(options) fatal is invalid. Expected boolean value", .{}); } } @@ -945,7 +934,7 @@ pub const TextDecoder = struct { if (ignoreBOM.isBoolean()) { decoder.ignore_bom = ignoreBOM.asBoolean(); } else { - return globalThis.throwInvalidArguments2("TextDecoder(options) ignoreBOM is invalid. Expected boolean value", .{}); + return globalThis.throwInvalidArguments("TextDecoder(options) ignoreBOM is invalid. Expected boolean value", .{}); } } } diff --git a/src/bun.js/webcore/response.zig b/src/bun.js/webcore/response.zig index ded1d5c7d9bc2b..9be1fd22a2db76 100644 --- a/src/bun.js/webcore/response.zig +++ b/src/bun.js/webcore/response.zig @@ -523,7 +523,7 @@ pub const Response = struct { break :brk try Init.init(globalThis, arguments[1]) orelse unreachable; } if (!globalThis.hasException()) { - return globalThis.throwInvalidArguments2("Failed to construct 'Response': The provided body value is not of type 'ResponseInit'", .{}); + return globalThis.throwInvalidArguments("Failed to construct 'Response': The provided body value is not of type 'ResponseInit'", .{}); } return error.JSError; }); @@ -1929,9 +1929,8 @@ pub const Fetch = struct { const url = ZigURL.parse(url_str.toOwnedSlice(bun.default_allocator) catch bun.outOfMemory()); if (!url.isHTTP() and !url.isHTTPS()) { - globalObject.throwInvalidArguments("URL must be HTTP or HTTPS", .{}); bun.default_allocator.free(url.href); - return .zero; + return globalObject.throwInvalidArguments("URL must be HTTP or HTTPS", .{}); } if (url.hostname.len == 0) { @@ -1941,9 +1940,8 @@ pub const Fetch = struct { } if (!url.hasValidPort()) { - globalObject.throwInvalidArguments("Invalid port", .{}); bun.default_allocator.free(url.href); - return .zero; + return globalObject.throwInvalidArguments("Invalid port", .{}); } bun.http.AsyncHTTP.preconnect(url, true); diff --git a/src/deps/c_ares.zig b/src/deps/c_ares.zig index 2d6fe20a44da4f..4ea51414279c7d 100644 --- a/src/deps/c_ares.zig +++ b/src/deps/c_ares.zig @@ -1558,17 +1558,13 @@ comptime { const Bun__canonicalizeIP = JSC.toJSHostFunction(Bun__canonicalizeIP_); @export(Bun__canonicalizeIP, .{ .name = "Bun__canonicalizeIP" }); } -pub fn Bun__canonicalizeIP_( - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { +pub fn Bun__canonicalizeIP_(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { JSC.markBinding(@src()); const arguments = callframe.arguments_old(1); if (arguments.len == 0) { - globalThis.throwInvalidArguments("canonicalizeIP() expects a string but received no arguments.", .{}); - return .zero; + return globalThis.throwInvalidArguments("canonicalizeIP() expects a string but received no arguments.", .{}); } // windows uses 65 bytes for ipv6 addresses and linux/macos uses 46 const INET6_ADDRSTRLEN = if (comptime bun.Environment.isWindows) 65 else 46; @@ -1608,8 +1604,8 @@ pub fn Bun__canonicalizeIP_( return JSC.ZigString.init(ip_addr[0..size]).toJS(globalThis); } else { if (!globalThis.hasException()) - globalThis.throwInvalidArguments("address must be a string", .{}); - return .zero; + return globalThis.throwInvalidArguments("address must be a string", .{}); + return error.JSError; } } diff --git a/src/logger.zig b/src/logger.zig index d3ff0999cacd66..3755bf16000614 100644 --- a/src/logger.zig +++ b/src/logger.zig @@ -658,7 +658,7 @@ pub const Log = struct { } if (!value.isString()) { - return globalThis.throwInvalidArguments2("Expected logLevel to be a string", .{}); + return globalThis.throwInvalidArguments("Expected logLevel to be a string", .{}); } return Map.fromJS(globalThis, value); diff --git a/src/options.zig b/src/options.zig index c091601d8b04ee..2681887caa18ee 100644 --- a/src/options.zig +++ b/src/options.zig @@ -397,7 +397,7 @@ pub const Target = enum { pub fn fromJS(global: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError!?Target { if (!value.isString()) { - return global.throwInvalidArguments2("target must be a string", .{}); + return global.throwInvalidArguments("target must be a string", .{}); } return Map.fromJS(global, value); } @@ -614,11 +614,11 @@ pub const Format = enum { if (format.isUndefinedOrNull()) return null; if (!format.isString()) { - return global.throwInvalidArguments2("format must be a string", .{}); + return global.throwInvalidArguments("format must be a string", .{}); } return Map.fromJS(global, format) orelse { - return global.throwInvalidArguments2("Invalid format - must be esm, cjs, or iife", .{}); + return global.throwInvalidArguments("Invalid format - must be esm, cjs, or iife", .{}); }; } @@ -730,7 +730,7 @@ pub const Loader = enum(u8) { if (loader.isUndefinedOrNull()) return null; if (!loader.isString()) { - return global.throwInvalidArguments2("loader must be a string", .{}); + return global.throwInvalidArguments("loader must be a string", .{}); } var zig_str = JSC.ZigString.init(""); @@ -738,7 +738,7 @@ pub const Loader = enum(u8) { if (zig_str.len == 0) return null; return fromString(zig_str.slice()) orelse { - return global.throwInvalidArguments2("invalid loader - must be js, jsx, tsx, ts, css, file, toml, wasm, bunsh, or json", .{}); + return global.throwInvalidArguments("invalid loader - must be js, jsx, tsx, ts, css, file, toml, wasm, bunsh, or json", .{}); }; } diff --git a/src/shell/interpreter.zig b/src/shell/interpreter.zig index 48971859d7283e..35e48af852d1d3 100644 --- a/src/shell/interpreter.zig +++ b/src/shell/interpreter.zig @@ -732,8 +732,7 @@ pub const ParsedShellScript = struct { const value1 = callframe.argument(0); if (!value1.isObject()) { - globalThis.throwInvalidArguments("env must be an object", .{}); - return .undefined; + return globalThis.throwInvalidArguments("env must be an object", .{}); } var object_iter = JSC.JSPropertyIterator(.{ @@ -1784,8 +1783,7 @@ pub const Interpreter = struct { pub fn setEnv(this: *ThisInterpreter, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { const value1 = callframe.argument(0); if (!value1.isObject()) { - globalThis.throwInvalidArguments("env must be an object", .{}); - return .undefined; + return globalThis.throwInvalidArguments("env must be an object", .{}); } var object_iter = JSC.JSPropertyIterator(.{ @@ -4960,23 +4958,11 @@ pub const Interpreter = struct { } else if (this.base.interpreter.jsobjs[val.idx].as(JSC.WebCore.Blob)) |blob__| { const blob = blob__.dupe(); if (this.node.redirect.stdin) { - if (!spawn_args.stdio[stdin_no].extractBlob(global, .{ - .Blob = blob, - }, stdin_no)) { - return; - } + spawn_args.stdio[stdin_no].extractBlob(global, .{ .Blob = blob }, stdin_no) catch return; } else if (this.node.redirect.stdout) { - if (!spawn_args.stdio[stdin_no].extractBlob(global, .{ - .Blob = blob, - }, stdout_no)) { - return; - } + spawn_args.stdio[stdin_no].extractBlob(global, .{ .Blob = blob }, stdout_no) catch return; } else if (this.node.redirect.stderr) { - if (!spawn_args.stdio[stdin_no].extractBlob(global, .{ - .Blob = blob, - }, stderr_no)) { - return; - } + spawn_args.stdio[stdin_no].extractBlob(global, .{ .Blob = blob }, stderr_no) catch return; } } else if (JSC.WebCore.ReadableStream.fromJS(this.base.interpreter.jsobjs[val.idx], global)) |rstream| { _ = rstream; @@ -4984,26 +4970,17 @@ pub const Interpreter = struct { } else if (this.base.interpreter.jsobjs[val.idx].as(JSC.WebCore.Response)) |req| { req.getBodyValue().toBlobIfPossible(); if (this.node.redirect.stdin) { - if (!spawn_args.stdio[stdin_no].extractBlob(global, req.getBodyValue().useAsAnyBlob(), stdin_no)) { - return; - } + spawn_args.stdio[stdin_no].extractBlob(global, req.getBodyValue().useAsAnyBlob(), stdin_no) catch return; } if (this.node.redirect.stdout) { - if (!spawn_args.stdio[stdout_no].extractBlob(global, req.getBodyValue().useAsAnyBlob(), stdout_no)) { - return; - } + spawn_args.stdio[stdout_no].extractBlob(global, req.getBodyValue().useAsAnyBlob(), stdout_no) catch return; } if (this.node.redirect.stderr) { - if (!spawn_args.stdio[stderr_no].extractBlob(global, req.getBodyValue().useAsAnyBlob(), stderr_no)) { - return; - } + spawn_args.stdio[stderr_no].extractBlob(global, req.getBodyValue().useAsAnyBlob(), stderr_no) catch return; } } else { const jsval = this.base.interpreter.jsobjs[val.idx]; - global.throw( - "Unknown JS value used in shell: {}", - .{jsval.fmtString(global)}, - ); + global.throw("Unknown JS value used in shell: {}", .{jsval.fmtString(global)}); return; } }, diff --git a/src/shell/shell.zig b/src/shell/shell.zig index fad6a4ffad9250..33a34d6a273398 100644 --- a/src/shell/shell.zig +++ b/src/shell/shell.zig @@ -98,7 +98,7 @@ pub const ShellErr = union(enum) { // this.bunVM().allocator.free(JSC.ZigString.untagged(str._unsafe_ptr_do_not_use)[0..str.len]); }, .invalid_arguments => { - return globalThis.throwInvalidArguments2("{s}", .{this.invalid_arguments.val}); + return globalThis.throwInvalidArguments("{s}", .{this.invalid_arguments.val}); }, .todo => { return globalThis.throwTODO(this.todo); diff --git a/src/sql/postgres.zig b/src/sql/postgres.zig index e5d236afaf67e5..09b2cdf61f7b57 100644 --- a/src/sql/postgres.zig +++ b/src/sql/postgres.zig @@ -1398,8 +1398,7 @@ pub const PostgresSQLConnection = struct { else if (tls_object.isObject()) (JSC.API.ServerConfig.SSLConfig.fromJS(vm, globalObject, tls_object) catch return .zero) orelse .{} else { - globalObject.throwInvalidArguments("tls must be a boolean or an object", .{}); - return .zero; + return globalObject.throwInvalidArguments("tls must be a boolean or an object", .{}); }; if (globalObject.hasException()) { diff --git a/src/url.zig b/src/url.zig index bd8d1b3e9d589a..3e7260aa8ac811 100644 --- a/src/url.zig +++ b/src/url.zig @@ -997,8 +997,7 @@ pub const FormData = struct { }; if (input_value.isEmptyOrUndefinedOrNull()) { - globalThis.throwInvalidArguments("input must not be empty", .{}); - return .zero; + return globalThis.throwInvalidArguments("input must not be empty", .{}); } if (!boundary_value.isEmptyOrUndefinedOrNull()) { @@ -1011,8 +1010,7 @@ pub const FormData = struct { encoding = .{ .Multipart = boundary_slice.slice() }; } } else { - globalThis.throwInvalidArguments("boundary must be a string or ArrayBufferView", .{}); - return .zero; + return globalThis.throwInvalidArguments("boundary must be a string or ArrayBufferView", .{}); } } var input_slice = JSC.ZigString.Slice{}; @@ -1027,8 +1025,7 @@ pub const FormData = struct { } else if (input_value.as(JSC.WebCore.Blob)) |blob| { input = blob.sharedView(); } else { - globalThis.throwInvalidArguments("input must be a string or ArrayBufferView", .{}); - return .zero; + return globalThis.throwInvalidArguments("input must be a string or ArrayBufferView", .{}); } return FormData.toJS(globalThis, input, encoding) catch |err| return globalThis.throwError(err, "while parsing FormData"); From 372f1da55459be97cd04d9ad891956215664d5de Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Wed, 20 Nov 2024 20:50:46 -0800 Subject: [PATCH 2/2] windows --- src/bun.js/node/types.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/bun.js/node/types.zig b/src/bun.js/node/types.zig index 0078f691842209..52ff09cd61a9b6 100644 --- a/src/bun.js/node/types.zig +++ b/src/bun.js/node/types.zig @@ -2075,7 +2075,7 @@ pub const Process = struct { return bun.String.toJSArray(globalObject, args_list.items); } - pub fn getCwd(globalObject: *JSC.JSGlobalObject) callconv(JSC.conv) JSC.JSValue { + pub fn getCwd(globalObject: *JSC.JSGlobalObject) callconv(.C) JSC.JSValue { return JSC.toJSHostValue(globalObject, getCwd_(globalObject)); } fn getCwd_(globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { @@ -2088,7 +2088,7 @@ pub const Process = struct { } } - pub fn setCwd(globalObject: *JSC.JSGlobalObject, to: *JSC.ZigString) callconv(JSC.conv) JSC.JSValue { + pub fn setCwd(globalObject: *JSC.JSGlobalObject, to: *JSC.ZigString) callconv(.C) JSC.JSValue { return JSC.toJSHostValue(globalObject, setCwd_(globalObject, to)); } fn setCwd_(globalObject: *JSC.JSGlobalObject, to: *JSC.ZigString) bun.JSError!JSC.JSValue {