From 2d441d868b54d1503489a809ebd4676eed5179ee Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Mon, 2 Dec 2024 14:19:18 -0800 Subject: [PATCH] zig: make throw use JSError (#15444) --- src/bake/DevServer.zig | 2 +- src/bake/FrameworkRouter.zig | 5 +- src/bake/bake.zig | 2 +- src/bake/production.zig | 15 +- src/bun.js/BuildMessage.zig | 2 +- src/bun.js/ResolveMessage.zig | 2 +- src/bun.js/api/BunObject.zig | 211 +++++---------- src/bun.js/api/JSBundler.zig | 7 +- src/bun.js/api/JSTranspiler.zig | 75 ++--- src/bun.js/api/bun/dns_resolver.zig | 114 +++----- src/bun.js/api/bun/h2_frame_parser.zig | 331 +++++++++-------------- src/bun.js/api/bun/socket.zig | 187 ++++--------- src/bun.js/api/bun/spawn/stdio.zig | 5 +- src/bun.js/api/bun/subprocess.zig | 29 +- src/bun.js/api/bun/udp_socket.zig | 48 +--- src/bun.js/api/bun/x509.zig | 9 +- src/bun.js/api/ffi.zig | 40 +-- src/bun.js/api/filesystem_router.zig | 21 +- src/bun.js/api/glob.zig | 26 +- src/bun.js/api/html_rewriter.zig | 9 +- src/bun.js/api/server.zig | 160 ++++------- src/bun.js/base.zig | 15 +- src/bun.js/bindings/bindings.zig | 102 +++---- src/bun.js/node/node_cluster_binding.zig | 3 +- src/bun.js/node/node_crypto_binding.zig | 3 +- src/bun.js/node/node_fs.zig | 5 +- src/bun.js/node/node_fs_binding.zig | 9 +- src/bun.js/node/node_net_binding.zig | 4 +- src/bun.js/node/node_os.zig | 34 +-- src/bun.js/node/node_zlib_binding.zig | 30 +- src/bun.js/node/types.zig | 42 +-- src/bun.js/node/util/parse_args.zig | 18 +- src/bun.js/node/util/validators.zig | 9 +- src/bun.js/test/expect.zig | 298 +++++++------------- src/bun.js/test/jest.zig | 25 +- src/bun.js/webcore.zig | 36 +-- src/bun.js/webcore/blob.zig | 27 +- src/bun.js/webcore/body.zig | 4 +- src/bun.js/webcore/encoding.zig | 6 +- src/bun.js/webcore/request.zig | 31 +-- src/bun.js/webcore/response.zig | 15 +- src/bun.js/webcore/streams.zig | 105 +++---- src/cli/pack_command.zig | 36 +-- src/codegen/generate-classes.ts | 2 +- src/codegen/generate-node-errors.ts | 8 +- src/css/css_internals.zig | 33 +-- src/css/values/color_js.zig | 74 ++--- src/fd.zig | 5 +- src/install/dependency.zig | 4 +- src/install/install.zig | 18 +- src/install/npm.zig | 12 +- src/install/semver.zig | 12 +- src/patch.zig | 19 +- src/resolver/resolver.zig | 3 +- src/shell/interpreter.zig | 28 +- src/shell/shell.zig | 93 +++---- src/sql/postgres.zig | 33 +-- src/sql/postgres/postgres_types.zig | 3 +- 58 files changed, 872 insertions(+), 1632 deletions(-) diff --git a/src/bake/DevServer.zig b/src/bake/DevServer.zig index 63026dab4f0d8c..a6f3cd4e653144 100644 --- a/src/bake/DevServer.zig +++ b/src/bake/DevServer.zig @@ -314,7 +314,7 @@ pub fn init(options: Options) bun.JSOOM!*DevServer { dev.framework = dev.framework.resolve(&dev.server_bundler.resolver, &dev.client_bundler.resolver, options.arena) catch { if (dev.framework.is_built_in_react) try bake.Framework.addReactInstallCommandNote(&dev.log); - return global.throwValue2(dev.log.toJSAggregateError(global, "Framework is missing required files!")); + return global.throwValue(dev.log.toJSAggregateError(global, "Framework is missing required files!")); }; errdefer dev.route_lookup.clearAndFree(allocator); diff --git a/src/bake/FrameworkRouter.zig b/src/bake/FrameworkRouter.zig index b26bf3eda71ce5..f9c7a24d90e23b 100644 --- a/src/bake/FrameworkRouter.zig +++ b/src/bake/FrameworkRouter.zig @@ -1144,7 +1144,7 @@ pub const JSFrameworkRouter = struct { }), ); } - return global.throwValue2(global.createAggregateErrorWithArray( + return global.throwValue(global.createAggregateErrorWithArray( bun.String.static("Errors scanning routes"), arr, )); @@ -1255,8 +1255,7 @@ pub const JSFrameworkRouter = struct { var log = TinyLog.empty; const parsed = style.parse(filepath.slice(), std.fs.path.extension(filepath.slice()), &log, true, alloc) catch |err| switch (err) { error.InvalidRoutePattern => { - global.throw("{s} ({d}:{d})", .{ log.msg.slice(), log.cursor_at, log.cursor_len }); - return error.JSError; + return global.throw("{s} ({d}:{d})", .{ log.msg.slice(), log.cursor_at, log.cursor_len }); }, else => |e| return e, } orelse diff --git a/src/bake/bake.zig b/src/bake/bake.zig index fc684376bd5ee6..7159b6d3e0a3e6 100644 --- a/src/bake/bake.zig +++ b/src/bake/bake.zig @@ -141,7 +141,7 @@ pub const SplitBundlerOptions = struct { _ = val; }, .rejected => |err| { - return global.throwValue2(err); + return global.throwValue(err); }, } } diff --git a/src/bake/production.zig b/src/bake/production.zig index 295931103e4a2a..a8fadb8d59ccc9 100644 --- a/src/bake/production.zig +++ b/src/bake/production.zig @@ -420,7 +420,7 @@ pub fn buildWithVm(ctx: bun.CLI.Command.Context, cwd: []const u8, vm: *VirtualMa params_buf.append(ctx.allocator, route.part.param) catch unreachable; }, .catch_all, .catch_all_optional => { - global.throw("catch-all routes are not supported in static site generation", .{}); + return global.throw("catch-all routes are not supported in static site generation", .{}); }, else => {}, } @@ -439,7 +439,7 @@ pub fn buildWithVm(ctx: bun.CLI.Command.Context, cwd: []const u8, vm: *VirtualMa params_buf.append(ctx.allocator, parent.part.param) catch unreachable; }, .catch_all, .catch_all_optional => { - global.throw("catch-all routes are not supported in static site generation", .{}); + return global.throw("catch-all routes are not supported in static site generation", .{}); }, else => {}, } @@ -532,8 +532,7 @@ pub fn buildWithVm(ctx: bun.CLI.Command.Context, cwd: []const u8, vm: *VirtualMa Output.flush(); }, .rejected => |err| { - vm.global.throwValue(err); - return error.JSError; + return vm.global.throwValue(err); }, } } @@ -550,8 +549,7 @@ fn loadModule(vm: *VirtualMachine, global: *JSC.JSGlobalObject, key: JSValue) !J return BakeGetModuleNamespace(global, key); }, .rejected => |err| { - vm.global.throwValue(err); - return error.JSError; + return vm.global.throwValue(err); }, } } @@ -616,11 +614,10 @@ export fn BakeProdResolve(global: *JSC.JSGlobalObject, a_str: bun.String, specif defer referrer.deinit(); if (bun.resolver.isPackagePath(specifier.slice())) { - global.throw("Non-relative import {} from {} are not allowed in production assets. This is a bug in Bun's bundler", .{ + return global.throw("Non-relative import {} from {} are not allowed in production assets. This is a bug in Bun's bundler", .{ bun.fmt.quote(specifier.slice()), bun.fmt.quote(referrer.slice()), - }); - return bun.String.dead; + }) catch bun.String.dead; } if (Environment.allow_assert) diff --git a/src/bun.js/BuildMessage.zig b/src/bun.js/BuildMessage.zig index d7d40455b0976b..f69a581cadecca 100644 --- a/src/bun.js/BuildMessage.zig +++ b/src/bun.js/BuildMessage.zig @@ -20,7 +20,7 @@ pub const BuildMessage = struct { pub usingnamespace JSC.Codegen.JSBuildMessage; pub fn constructor(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*BuildMessage { - return globalThis.throw2("BuildMessage is not constructable", .{}); + return globalThis.throw("BuildMessage is not constructable", .{}); } pub fn getNotes(this: *BuildMessage, globalThis: *JSC.JSGlobalObject) JSC.JSValue { diff --git a/src/bun.js/ResolveMessage.zig b/src/bun.js/ResolveMessage.zig index 7c62e7f7d61d38..a46ed1af370a54 100644 --- a/src/bun.js/ResolveMessage.zig +++ b/src/bun.js/ResolveMessage.zig @@ -19,7 +19,7 @@ pub const ResolveMessage = struct { pub usingnamespace JSC.Codegen.JSResolveMessage; pub fn constructor(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*ResolveMessage { - return globalThis.throw2("ResolveMessage is not constructable", .{}); + return globalThis.throw("ResolveMessage is not constructable", .{}); } pub fn getCode(this: *ResolveMessage, globalObject: *JSC.JSGlobalObject) JSC.JSValue { diff --git a/src/bun.js/api/BunObject.zig b/src/bun.js/api/BunObject.zig index 668e58788c633b..ec7cd1db4e7c27 100644 --- a/src/bun.js/api/BunObject.zig +++ b/src/bun.js/api/BunObject.zig @@ -262,8 +262,7 @@ const Shell = @import("../../shell/shell.zig"); pub fn shellEscape(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { const arguments = callframe.arguments_old(1); if (arguments.len < 1) { - globalThis.throw("shell escape expected at least 1 argument", .{}); - return .zero; + return globalThis.throw("shell escape expected at least 1 argument", .{}); } const jsval = arguments.ptr[0]; @@ -277,8 +276,7 @@ pub fn shellEscape(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b if (bun.shell.needsEscapeBunstr(bunstr)) { const result = try bun.shell.escapeBunStr(bunstr, &outbuf, true); if (!result) { - globalThis.throw("String has invalid utf-16: {s}", .{bunstr.byteSlice()}); - return .zero; + return globalThis.throw("String has invalid utf-16: {s}", .{bunstr.byteSlice()}); } var str = bun.String.createUTF8(outbuf.items[0..]); return str.transferToJS(globalThis); @@ -293,8 +291,7 @@ pub fn braces(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JS defer arguments.deinit(); const brace_str_js = arguments.nextEat() orelse { - globalThis.throw("braces: expected at least 1 argument, got 0", .{}); - return .zero; + return globalThis.throw("braces: expected at least 1 argument, got 0", .{}); }; const brace_str = brace_str_js.toBunString(globalThis); defer brace_str.deref(); @@ -381,8 +378,7 @@ pub fn which(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); defer arguments.deinit(); const path_arg = arguments.nextEat() orelse { - globalThis.throw("which: expected 1 argument, got 0", .{}); - return .zero; + return globalThis.throw("which: expected 1 argument, got 0", .{}); }; var path_str: ZigString.Slice = ZigString.Slice.empty; @@ -404,8 +400,7 @@ pub fn which(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE } if (bin_str.len >= bun.MAX_PATH_BYTES) { - globalThis.throw("bin path is too long", .{}); - return .zero; + return globalThis.throw("bin path is too long", .{}); } if (bin_str.len == 0) { @@ -591,8 +586,7 @@ pub fn registerMacro(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFram if (!arguments[1].isCell() or !arguments[1].isCallable(globalObject.vm())) { // TODO: add "toTypeOf" helper - globalObject.throw("Macro must be a function", .{}); - return .zero; + return globalObject.throw("Macro must be a function", .{}); } const get_or_put_result = VirtualMachine.get().macros.getOrPut(id) catch unreachable; @@ -735,8 +729,7 @@ pub fn openInEditor(globalThis: js.JSContextRef, callframe: *JSC.CallFrame) bun. editor_choice = edit.editor; if (editor_choice == null) { edit.* = prev; - globalThis.throw("Could not find editor \"{s}\"", .{sliced.slice()}); - return .zero; + return globalThis.throw("Could not find editor \"{s}\"", .{sliced.slice()}); } else if (edit.name.ptr == edit.path.ptr) { edit.name = arguments.arena.allocator().dupe(u8, edit.path) catch unreachable; edit.path = edit.path; @@ -757,21 +750,18 @@ pub fn openInEditor(globalThis: js.JSContextRef, callframe: *JSC.CallFrame) bun. const editor = editor_choice orelse edit.editor orelse brk: { edit.autoDetectEditor(VirtualMachine.get().bundler.env); if (edit.editor == null) { - globalThis.throw("Failed to auto-detect editor", .{}); - return .zero; + return globalThis.throw("Failed to auto-detect editor", .{}); } break :brk edit.editor.?; }; if (path.len == 0) { - globalThis.throw("No file path specified", .{}); - return .zero; + return globalThis.throw("No file path specified", .{}); } editor.open(edit.path, path, line, column, arguments.arena.allocator()) catch |err| { - globalThis.throw("Opening editor failed {s}", .{@errorName(err)}); - return .zero; + return globalThis.throw("Opening editor failed {s}", .{@errorName(err)}); }; return .undefined; @@ -838,8 +828,7 @@ pub fn sleepSync(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b // The argument must be a number if (!arg.isNumber()) { - globalObject.throwInvalidArgumentType("sleepSync", "milliseconds", "number"); - return .zero; + return globalObject.throwInvalidArgumentType("sleepSync", "milliseconds", "number"); } //NOTE: if argument is > max(i32) then it will be truncated @@ -939,8 +928,7 @@ fn doResolveWithArgs(ctx: js.JSContextRef, specifier: bun.String, from: bun.Stri } if (!errorable.success) { - ctx.throwValue(bun.cast(JSC.JSValueRef, errorable.result.err.ptr.?).?.value()); - return error.JSError; + return ctx.throwValue(bun.cast(JSC.JSValueRef, errorable.result.err.ptr.?).?.value()); } if (query_string.len > 0) { @@ -1426,7 +1414,7 @@ pub const Crypto = struct { const slice = arguments[4].toSlice(globalThis, bun.default_allocator); defer slice.deinit(); const name = slice.slice(); - globalThis.ERR_CRYPTO_INVALID_DIGEST("Unsupported algorithm \"{s}\"", .{name}).throw(); + return globalThis.ERR_CRYPTO_INVALID_DIGEST("Unsupported algorithm \"{s}\"", .{name}).throw(); } return error.JSError; }; @@ -1587,15 +1575,13 @@ pub const Crypto = struct { if (value.isObject()) { if (try value.getTruthy(globalObject, "algorithm")) |algorithm_value| { if (!algorithm_value.isString()) { - globalObject.throwInvalidArgumentType("hash", "algorithm", "string"); - return error.JSError; + return globalObject.throwInvalidArgumentType("hash", "algorithm", "string"); } const algorithm_string = algorithm_value.getZigString(globalObject); switch (PasswordObject.Algorithm.label.getWithEql(algorithm_string, JSC.ZigString.eqlComptime) orelse { - globalObject.throwInvalidArgumentType("hash", "algorithm", unknown_password_algorithm_message); - return error.JSError; + return globalObject.throwInvalidArgumentType("hash", "algorithm", unknown_password_algorithm_message); }) { .bcrypt => { var algorithm = PasswordObject.Algorithm.Value{ @@ -1604,8 +1590,7 @@ pub const Crypto = struct { if (try value.getTruthy(globalObject, "cost")) |rounds_value| { if (!rounds_value.isNumber()) { - globalObject.throwInvalidArgumentType("hash", "cost", "number"); - return error.JSError; + return globalObject.throwInvalidArgumentType("hash", "cost", "number"); } const rounds = rounds_value.coerce(i32, globalObject); @@ -1624,8 +1609,7 @@ pub const Crypto = struct { if (try value.getTruthy(globalObject, "timeCost")) |time_value| { if (!time_value.isNumber()) { - globalObject.throwInvalidArgumentType("hash", "timeCost", "number"); - return error.JSError; + return globalObject.throwInvalidArgumentType("hash", "timeCost", "number"); } const time_cost = time_value.coerce(i32, globalObject); @@ -1639,8 +1623,7 @@ pub const Crypto = struct { if (try value.getTruthy(globalObject, "memoryCost")) |memory_value| { if (!memory_value.isNumber()) { - globalObject.throwInvalidArgumentType("hash", "memoryCost", "number"); - return error.JSError; + return globalObject.throwInvalidArgumentType("hash", "memoryCost", "number"); } const memory_cost = memory_value.coerce(i32, globalObject); @@ -1658,15 +1641,13 @@ pub const Crypto = struct { unreachable; } else { - globalObject.throwInvalidArgumentType("hash", "options.algorithm", "string"); - return error.JSError; + return globalObject.throwInvalidArgumentType("hash", "options.algorithm", "string"); } } else if (value.isString()) { const algorithm_string = value.getZigString(globalObject); switch (PasswordObject.Algorithm.label.getWithEql(algorithm_string, JSC.ZigString.eqlComptime) orelse { - globalObject.throwInvalidArgumentType("hash", "algorithm", unknown_password_algorithm_message); - return error.JSError; + return globalObject.throwInvalidArgumentType("hash", "algorithm", unknown_password_algorithm_message); }) { .bcrypt => { return PasswordObject.Algorithm.Value{ @@ -1690,8 +1671,7 @@ pub const Crypto = struct { }, } } else { - globalObject.throwInvalidArgumentType("hash", "algorithm", "string"); - return error.JSError; + return globalObject.throwInvalidArgumentType("hash", "algorithm", "string"); } unreachable; @@ -1998,12 +1978,8 @@ pub const Crypto = struct { this.deinit(); } }; - pub fn hash( - globalObject: *JSC.JSGlobalObject, - password: []const u8, - algorithm: PasswordObject.Algorithm.Value, - comptime sync: bool, - ) JSC.JSValue { + + pub fn hash(globalObject: *JSC.JSGlobalObject, password: []const u8, algorithm: PasswordObject.Algorithm.Value, comptime sync: bool) bun.JSError!JSC.JSValue { assert(password.len > 0); // caller must check if (comptime sync) { @@ -2011,8 +1987,7 @@ pub const Crypto = struct { switch (value) { .err => { const error_instance = value.toErrorInstance(globalObject); - globalObject.throwValue(error_instance); - return .zero; + return globalObject.throwValue(error_instance); }, .hash => |h| { return JSC.ZigString.init(h).toJS(globalObject); @@ -2037,13 +2012,7 @@ pub const Crypto = struct { return promise.value(); } - pub fn verify( - globalObject: *JSC.JSGlobalObject, - password: []const u8, - prev_hash: []const u8, - algorithm: ?PasswordObject.Algorithm, - comptime sync: bool, - ) JSC.JSValue { + pub fn verify(globalObject: *JSC.JSGlobalObject, password: []const u8, prev_hash: []const u8, algorithm: ?PasswordObject.Algorithm, comptime sync: bool) bun.JSError!JSC.JSValue { assert(password.len > 0); // caller must check if (comptime sync) { @@ -2051,8 +2020,7 @@ pub const Crypto = struct { switch (value) { .err => { const error_instance = value.toErrorInstance(globalObject); - globalObject.throwValue(error_instance); - return .zero; + return globalObject.throwValue(error_instance); }, .pass => |pass| { return JSC.JSValue.jsBoolean(pass); @@ -2095,7 +2063,7 @@ pub const Crypto = struct { const password_to_hash = JSC.Node.StringOrBuffer.fromJSToOwnedSlice(globalObject, arguments[0], bun.default_allocator) catch { if (!globalObject.hasException()) { - globalObject.throwInvalidArgumentType("hash", "password", "string or TypedArray"); + return globalObject.throwInvalidArgumentType("hash", "password", "string or TypedArray"); } return error.JSError; }; @@ -2125,7 +2093,7 @@ pub const Crypto = struct { var string_or_buffer = JSC.Node.StringOrBuffer.fromJS(globalObject, bun.default_allocator, arguments[0]) orelse { if (!globalObject.hasException()) { - globalObject.throwInvalidArgumentType("hash", "password", "string or TypedArray"); + return globalObject.throwInvalidArgumentType("hash", "password", "string or TypedArray"); } return error.JSError; }; @@ -2238,28 +2206,27 @@ pub const Crypto = struct { if (arguments.len > 2 and !arguments[2].isEmptyOrUndefinedOrNull()) { if (!arguments[2].isString()) { - globalObject.throwInvalidArgumentType("verify", "algorithm", "string"); - return error.JSError; + return globalObject.throwInvalidArgumentType("verify", "algorithm", "string"); } const algorithm_string = arguments[2].getZigString(globalObject); algorithm = PasswordObject.Algorithm.label.getWithEql(algorithm_string, JSC.ZigString.eqlComptime) orelse { if (!globalObject.hasException()) { - globalObject.throwInvalidArgumentType("verify", "algorithm", unknown_password_algorithm_message); + return globalObject.throwInvalidArgumentType("verify", "algorithm", unknown_password_algorithm_message); } return error.JSError; }; } const owned_password = JSC.Node.StringOrBuffer.fromJSToOwnedSlice(globalObject, arguments[0], bun.default_allocator) catch { - if (!globalObject.hasException()) globalObject.throwInvalidArgumentType("verify", "password", "string or TypedArray"); + if (!globalObject.hasException()) return globalObject.throwInvalidArgumentType("verify", "password", "string or TypedArray"); return error.JSError; }; const owned_hash = JSC.Node.StringOrBuffer.fromJSToOwnedSlice(globalObject, arguments[1], bun.default_allocator) catch { bun.default_allocator.free(owned_password); - if (!globalObject.hasException()) globalObject.throwInvalidArgumentType("verify", "hash", "string or TypedArray"); + if (!globalObject.hasException()) return globalObject.throwInvalidArgumentType("verify", "hash", "string or TypedArray"); return error.JSError; }; @@ -2289,15 +2256,14 @@ pub const Crypto = struct { if (arguments.len > 2 and !arguments[2].isEmptyOrUndefinedOrNull()) { if (!arguments[2].isString()) { - globalObject.throwInvalidArgumentType("verify", "algorithm", "string"); - return .zero; + return globalObject.throwInvalidArgumentType("verify", "algorithm", "string"); } const algorithm_string = arguments[2].getZigString(globalObject); algorithm = PasswordObject.Algorithm.label.getWithEql(algorithm_string, JSC.ZigString.eqlComptime) orelse { if (!globalObject.hasException()) { - globalObject.throwInvalidArgumentType("verify", "algorithm", unknown_password_algorithm_message); + return globalObject.throwInvalidArgumentType("verify", "algorithm", unknown_password_algorithm_message); } return .zero; }; @@ -2305,7 +2271,7 @@ pub const Crypto = struct { var password = JSC.Node.StringOrBuffer.fromJS(globalObject, bun.default_allocator, arguments[0]) orelse { if (!globalObject.hasException()) { - globalObject.throwInvalidArgumentType("verify", "password", "string or TypedArray"); + return globalObject.throwInvalidArgumentType("verify", "password", "string or TypedArray"); } return .zero; }; @@ -2313,7 +2279,7 @@ pub const Crypto = struct { var hash_ = JSC.Node.StringOrBuffer.fromJS(globalObject, bun.default_allocator, arguments[1]) orelse { password.deinit(); if (!globalObject.hasException()) { - globalObject.throwInvalidArgumentType("verify", "hash", "string or TypedArray"); + return globalObject.throwInvalidArgumentType("verify", "hash", "string or TypedArray"); } return .zero; }; @@ -2349,7 +2315,7 @@ pub const Crypto = struct { pub const hash = JSC.wrapStaticMethod(CryptoHasher, "hash_", false); fn throwHmacConsumed(globalThis: *JSC.JSGlobalObject) bun.JSError { - return globalThis.throw2("HMAC has been consumed and is no longer usable", .{}); + return globalThis.throw("HMAC has been consumed and is no longer usable", .{}); } pub fn getByteLength(this: *CryptoHasher, globalThis: *JSC.JSGlobalObject) JSC.JSValue { @@ -2385,16 +2351,14 @@ pub const Crypto = struct { 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.throw("Bun.file() is not supported here yet (it needs an async version)", .{}); } const len = evp.hash(globalThis.bunVM().rareData().boringEngine(), input.slice(), &output_digest_buf) orelse { const err = BoringSSL.ERR_get_error(); const instance = createCryptoError(globalThis, err); BoringSSL.ERR_clear_error(); - globalThis.throwValue(instance); - return .zero; + return globalThis.throwValue(instance); }; return encoding.encodeWithMaxSize(globalThis, BoringSSL.EVP_MAX_MD_SIZE, output_digest_buf[0..len]); } @@ -2405,8 +2369,7 @@ pub const Crypto = struct { 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.throw("Bun.file() is not supported here yet (it needs an async version)", .{}); } if (output) |output_buf| { @@ -2422,8 +2385,7 @@ pub const Crypto = struct { const err = BoringSSL.ERR_get_error(); const instance = createCryptoError(globalThis, err); BoringSSL.ERR_clear_error(); - globalThis.throwValue(instance); - return .zero; + return globalThis.throwValue(instance); }; if (output) |output_buf| { @@ -2450,8 +2412,7 @@ pub const Crypto = struct { 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 error.JSError; + return globalThis.ERR_INVALID_ARG_VALUE("Unknown encoding: {s}", .{str.slice()}).throw(); }; return hashToEncoding(globalThis, &evp, input, encoding); @@ -2502,7 +2463,7 @@ pub const Crypto = struct { const chosen_algorithm = try algorithm_name.toEnumFromMap(globalThis, "algorithm", EVP.Algorithm, EVP.Algorithm.map); if (chosen_algorithm == .ripemd160) { // crashes at runtime. - return globalThis.throw2("ripemd160 is not supported", .{}); + return globalThis.throw("ripemd160 is not supported", .{}); } break :brk .{ @@ -2512,7 +2473,7 @@ pub const Crypto = struct { if (err != 0) { const instance = createCryptoError(globalThis, err); BoringSSL.ERR_clear_error(); - return globalThis.throwValue2(instance); + return globalThis.throwValue(instance); } else { return globalThis.throwTODO("HMAC is not supported for this algorithm yet"); } @@ -2551,7 +2512,7 @@ pub const Crypto = struct { }; defer buffer.deinit(); if (buffer == .blob and buffer.blob.isBunFile()) { - return globalThis.throw2("Bun.file() is not supported here yet (it needs an async version)", .{}); + return globalThis.throw("Bun.file() is not supported here yet (it needs an async version)", .{}); } switch (this.*) { @@ -2561,7 +2522,7 @@ pub const Crypto = struct { if (err != 0) { const instance = createCryptoError(globalThis, err); BoringSSL.ERR_clear_error(); - return globalThis.throwValue2(instance); + return globalThis.throwValue(instance); } }, .hmac => |inner| { @@ -2574,7 +2535,7 @@ pub const Crypto = struct { if (err != 0) { const instance = createCryptoError(globalThis, err); BoringSSL.ERR_clear_error(); - return globalThis.throwValue2(instance); + return globalThis.throwValue(instance); } }, .zig => |*inner| { @@ -2604,7 +2565,7 @@ pub const Crypto = struct { .hmac = hmac.copy() catch { const err = createCryptoError(globalObject, BoringSSL.ERR_get_error()); BoringSSL.ERR_clear_error(); - return globalObject.throwValue2(err); + return globalObject.throwValue(err); }, }; }, @@ -2621,8 +2582,7 @@ pub const Crypto = struct { 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 error.JSError; + return globalThis.ERR_INVALID_ARG_VALUE("Unknown encoding: {s}", .{str.slice()}).throw(); }; return this.digestToEncoding(globalThis, encoding); @@ -2746,8 +2706,7 @@ pub const Crypto = struct { 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 error.JSError; + return globalThis.ERR_INVALID_ARG_VALUE("Unknown encoding: {s}", .{str.slice()}).throw(); }; if (encoding == .buffer) { @@ -2764,12 +2723,11 @@ pub const Crypto = struct { return hashByNameInnerToBytes(globalThis, Algorithm, input, null); } - fn hashByNameInnerToString(globalThis: *JSGlobalObject, comptime Algorithm: type, input: JSC.Node.BlobOrStringOrBuffer, encoding: JSC.Node.Encoding) JSC.JSValue { + fn hashByNameInnerToString(globalThis: *JSGlobalObject, comptime Algorithm: type, input: JSC.Node.BlobOrStringOrBuffer, encoding: JSC.Node.Encoding) 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.throw("Bun.file() is not supported here yet (it needs an async version)", .{}); } var h = Algorithm.init(.{}); @@ -2785,8 +2743,7 @@ pub const Crypto = struct { 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.throw("Bun.file() is not supported here yet (it needs an async version)", .{}); } var h = Algorithm.init(.{}); @@ -2893,16 +2850,11 @@ pub const Crypto = struct { return JSC.JSValue.jsNumber(@as(u16, Hasher.digest)); } - fn hashToEncoding( - globalThis: *JSGlobalObject, - input: JSC.Node.BlobOrStringOrBuffer, - encoding: JSC.Node.Encoding, - ) JSC.JSValue { + fn hashToEncoding(globalThis: *JSGlobalObject, input: JSC.Node.BlobOrStringOrBuffer, encoding: JSC.Node.Encoding) bun.JSError!JSC.JSValue { var output_digest_buf: Hasher.Digest = undefined; 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.throw("Bun.file() is not supported here yet (it needs an async version)", .{}); } if (comptime @typeInfo(@TypeOf(Hasher.hash)).Fn.params.len == 3) { @@ -2947,7 +2899,7 @@ pub const Crypto = struct { defer input.deinit(); if (input == .blob and input.blob.isBunFile()) { - return globalThis.throw2("Bun.file() is not supported here yet (it needs an async version)", .{}); + return globalThis.throw("Bun.file() is not supported here yet (it needs an async version)", .{}); } if (output) |string_or_buffer| { @@ -2955,8 +2907,7 @@ pub const Crypto = struct { 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 error.JSError; + return globalThis.ERR_INVALID_ARG_VALUE("Unknown encoding: {s}", .{str.slice()}).throw(); }; return hashToEncoding(globalThis, input, encoding); @@ -2985,8 +2936,7 @@ pub const Crypto = struct { pub fn update(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { if (this.digested) { - globalThis.ERR_INVALID_STATE(name ++ " hasher already digested, create a new instance to update", .{}).throw(); - return .zero; + return globalThis.ERR_INVALID_STATE(name ++ " hasher already digested, create a new instance to update", .{}).throw(); } const thisValue = callframe.this(); const input = callframe.argument(0); @@ -2996,8 +2946,7 @@ pub const Crypto = struct { defer buffer.deinit(); if (buffer == .blob and buffer.blob.isBunFile()) { - globalThis.throw("Bun.file() is not supported here yet (it needs an async version)", .{}); - return .zero; + return globalThis.throw("Bun.file() is not supported here yet (it needs an async version)", .{}); } this.hashing.update(buffer.slice()); return thisValue; @@ -3009,16 +2958,14 @@ pub const Crypto = struct { output: ?JSC.Node.StringOrBuffer, ) 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; + return globalThis.ERR_INVALID_STATE(name ++ " hasher already digested, create a new instance to digest again", .{}).throw(); } 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 error.JSError; + return globalThis.ERR_INVALID_ARG_VALUE("Unknown encoding: {s}", .{str.slice()}).throw(); }; return this.digestToEncoding(globalThis, encoding); @@ -3198,8 +3145,7 @@ pub export fn Bun__escapeHTML16(globalObject: *JSC.JSGlobalObject, input_value: assert(len > 0); const input_slice = ptr[0..len]; const escaped = strings.escapeHTMLForUTF16Input(globalObject.bunVM().allocator, input_slice) catch { - globalObject.vm().throwError(globalObject, bun.String.static("Out of memory").toJS(globalObject)); - return .zero; + return globalObject.throwValue(bun.String.static("Out of memory").toJS(globalObject)) catch .zero; }; return switch (escaped) { @@ -3217,8 +3163,7 @@ pub export fn Bun__escapeHTML8(globalObject: *JSC.JSGlobalObject, input_value: J const allocator = if (input_slice.len <= 32) stack_allocator.get() else stack_allocator.fallback_allocator; const escaped = strings.escapeHTMLForLatin1Input(allocator, input_slice) catch { - globalObject.vm().throwError(globalObject, bun.String.static("Out of memory").toJS(globalObject)); - return .zero; + return globalObject.throwValue(bun.String.static("Out of memory").toJS(globalObject)) catch .zero; }; switch (escaped) { @@ -3330,8 +3275,7 @@ pub fn mmapFile(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. .result => |map| map, .err => |err| { - globalThis.throwValue(err.toJSC(globalThis)); - return .zero; + return globalThis.throwValue(err.toJSC(globalThis)); }, }; @@ -3613,19 +3557,16 @@ const TOMLObject = struct { defer input_slice.deinit(); var source = logger.Source.initPathString("input.toml", input_slice.slice()); const parse_result = TOMLParser.parse(&source, &log, allocator, false) catch { - globalThis.throwValue(log.toJS(globalThis, default_allocator, "Failed to parse toml")); - return .zero; + return globalThis.throwValue(log.toJS(globalThis, default_allocator, "Failed to parse toml")); }; // for now... const buffer_writer = js_printer.BufferWriter.init(allocator) catch { - globalThis.throwValue(log.toJS(globalThis, default_allocator, "Failed to print toml")); - return .zero; + return globalThis.throwValue(log.toJS(globalThis, default_allocator, "Failed to print toml")); }; var writer = js_printer.BufferPrinter.init(buffer_writer); _ = js_printer.printJSON(*js_printer.BufferPrinter, &writer, parse_result, &source, .{}) catch { - globalThis.throwValue(log.toJS(globalThis, default_allocator, "Failed to print toml")); - return .zero; + return globalThis.throwValue(log.toJS(globalThis, default_allocator, "Failed to print toml")); }; const slice = writer.ctx.buffer.slice(); @@ -4489,8 +4430,7 @@ pub const JSZlib = struct { }) catch |err| { list.deinit(allocator); if (err == error.InvalidArgument) { - globalThis.throw("Zlib error: Invalid argument", .{}); - return .zero; + return globalThis.throw("Zlib error: Invalid argument", .{}); } return globalThis.throwError(err, "Zlib error") catch return .zero; @@ -4498,8 +4438,7 @@ pub const JSZlib = struct { reader.readAll() catch { defer reader.deinit(); - globalThis.throwValue(ZigString.init(reader.errorMessage() orelse "Zlib returned an error").toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(ZigString.init(reader.errorMessage() orelse "Zlib returned an error").toErrorInstance(globalThis)); }; reader.list = .{ .items = reader.list.items }; reader.list.capacity = reader.list.items.len; @@ -4538,8 +4477,7 @@ pub const JSZlib = struct { } list.deinit(allocator); - globalThis.throw("libdeflate returned an error: {s}", .{@tagName(result.status)}); - return .zero; + return globalThis.throw("libdeflate returned an error: {s}", .{@tagName(result.status)}); } var array_buffer = JSC.ArrayBuffer.fromBytes(list.items, .Uint8Array); @@ -4599,8 +4537,7 @@ pub const JSZlib = struct { }) catch |err| { defer list.deinit(allocator); if (err == error.InvalidArgument) { - globalThis.throw("Zlib error: Invalid argument", .{}); - return .zero; + return globalThis.throw("Zlib error: Invalid argument", .{}); } return globalThis.throwError(err, "Zlib error"); @@ -4608,8 +4545,7 @@ pub const JSZlib = struct { reader.readAll() catch { defer reader.deinit(); - globalThis.throwValue(ZigString.init(reader.errorMessage() orelse "Zlib returned an error").toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(ZigString.init(reader.errorMessage() orelse "Zlib returned an error").toErrorInstance(globalThis)); }; reader.list = .{ .items = reader.list.toOwnedSlice(allocator) catch @panic("TODO") }; reader.list.capacity = reader.list.items.len; @@ -4642,8 +4578,7 @@ pub const JSZlib = struct { } list.deinit(allocator); - globalThis.throw("libdeflate error: {s}", .{@tagName(result.status)}); - return .zero; + return globalThis.throw("libdeflate error: {s}", .{@tagName(result.status)}); } var array_buffer = JSC.ArrayBuffer.fromBytes(list.items, .Uint8Array); diff --git a/src/bun.js/api/JSBundler.zig b/src/bun.js/api/JSBundler.zig index 36f9b0533e17e4..f2f0fc131da100 100644 --- a/src/bun.js/api/JSBundler.zig +++ b/src/bun.js/api/JSBundler.zig @@ -159,14 +159,14 @@ pub const JSBundler = struct { plugin_result = val; }, .rejected => |err| { - return globalThis.throwValue2(err); + return globalThis.throwValue(err); }, } } } if (plugin_result.toError()) |err| { - return globalThis.throwValue2(err); + return globalThis.throwValue(err); } else if (globalThis.hasException()) { return error.JSError; } @@ -784,10 +784,9 @@ pub const JSBundler = struct { export fn JSBundlerPlugin__onDefer(load: *Load, global: *JSC.JSGlobalObject) JSValue { return JSC.toJSHostValue(global, load.onDefer(global)); } - fn onDefer(this: *Load, globalObject: *JSC.JSGlobalObject) bun.JSError!JSValue { if (this.called_defer) { - return globalObject.throw2("Can't call .defer() more than once within an onLoad plugin", .{}); + return globalObject.throw("Can't call .defer() more than once within an onLoad plugin", .{}); } this.called_defer = true; diff --git a/src/bun.js/api/JSTranspiler.zig b/src/bun.js/api/JSTranspiler.zig index 2716bc3968f5a5..e13490d4974b3a 100644 --- a/src/bun.js/api/JSTranspiler.zig +++ b/src/bun.js/api/JSTranspiler.zig @@ -727,7 +727,7 @@ pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b const allocator = getAllocator(globalThis); if ((transpiler_options.log.warnings + transpiler_options.log.errors) > 0) { - return globalThis.throwValue2(transpiler_options.log.toJS(globalThis, allocator, "Failed to create transpiler")); + return globalThis.throwValue(transpiler_options.log.toJS(globalThis, allocator, "Failed to create transpiler")); } var log = try allocator.create(logger.Log); @@ -739,7 +739,7 @@ pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b JavaScript.VirtualMachine.get().bundler.env, ) catch |err| { if ((log.warnings + log.errors) > 0) { - return globalThis.throwValue2(log.toJS(globalThis, allocator, "Failed to create transpiler")); + return globalThis.throwValue(log.toJS(globalThis, allocator, "Failed to create transpiler")); } return globalThis.throwError(err, "Error creating transpiler"); @@ -749,7 +749,7 @@ pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b bundler.options.env.behavior = .disable; bundler.configureDefines() catch |err| { if ((log.warnings + log.errors) > 0) { - return globalThis.throwValue2(log.toJS(globalThis, allocator, "Failed to load define")); + return globalThis.throwValue(log.toJS(globalThis, allocator, "Failed to load define")); } return globalThis.throwError(err, "Failed to load define"); }; @@ -789,9 +789,7 @@ pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b return transpiler; } -pub fn finalize( - this: *Transpiler, -) callconv(.C) void { +pub fn finalize(this: *Transpiler) callconv(.C) void { this.bundler.log.deinit(); this.scan_pass_result.named_imports.deinit(this.scan_pass_result.import_records.allocator); this.scan_pass_result.import_records.deinit(); @@ -832,23 +830,17 @@ fn getParseResult(this: *Transpiler, allocator: std.mem.Allocator, code: []const return this.bundler.parse(parse_options, null); } -pub fn scan( - this: *Transpiler, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { +pub fn scan(this: *Transpiler, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { JSC.markBinding(@src()); const arguments = callframe.arguments_old(3); var args = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); defer args.deinit(); const code_arg = args.next() orelse { - globalThis.throwInvalidArgumentType("scan", "code", "string or Uint8Array"); - return .zero; + return globalThis.throwInvalidArgumentType("scan", "code", "string or Uint8Array"); }; const code_holder = JSC.Node.StringOrBuffer.fromJS(globalThis, args.arena.allocator(), code_arg) orelse { - globalThis.throwInvalidArgumentType("scan", "code", "string or Uint8Array"); - return .zero; + return globalThis.throwInvalidArgumentType("scan", "code", "string or Uint8Array"); }; defer code_holder.deinit(); const code = code_holder.slice(); @@ -886,17 +878,14 @@ pub fn scan( var parse_result = getParseResult(this, arena.allocator(), code, loader, Bundler.MacroJSValueType.zero) orelse { if ((this.bundler.log.warnings + this.bundler.log.errors) > 0) { - globalThis.throwValue(this.bundler.log.toJS(globalThis, globalThis.allocator(), "Parse error")); - return .zero; + return globalThis.throwValue(this.bundler.log.toJS(globalThis, globalThis.allocator(), "Parse error")); } - globalThis.throw("Failed to parse", .{}); - return .zero; + return globalThis.throw("Failed to parse", .{}); }; if ((this.bundler.log.warnings + this.bundler.log.errors) > 0) { - globalThis.throwValue(this.bundler.log.toJS(globalThis, globalThis.allocator(), "Parse error")); - return .zero; + return globalThis.throwValue(this.bundler.log.toJS(globalThis, globalThis.allocator(), "Parse error")); } const exports_label = JSC.ZigString.static("exports"); @@ -913,23 +902,17 @@ pub fn scan( return JSC.JSValue.createObject2(globalThis, imports_label, exports_label, named_imports_value, named_exports_value); } -pub fn transform( - this: *Transpiler, - globalThis: *JSC.JSGlobalObject, - callframe: *JSC.CallFrame, -) bun.JSError!JSC.JSValue { +pub fn transform(this: *Transpiler, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { JSC.markBinding(@src()); const arguments = callframe.arguments_old(3); var args = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); defer args.arena.deinit(); const code_arg = args.next() orelse { - globalThis.throwInvalidArgumentType("transform", "code", "string or Uint8Array"); - return error.JSError; + return globalThis.throwInvalidArgumentType("transform", "code", "string or Uint8Array"); }; var code = try JSC.Node.StringOrBuffer.fromJSWithEncodingMaybeAsync(globalThis, bun.default_allocator, code_arg, .utf8, true) orelse { - globalThis.throwInvalidArgumentType("transform", "code", "string or Uint8Array"); - return error.JSError; + return globalThis.throwInvalidArgumentType("transform", "code", "string or Uint8Array"); }; errdefer code.deinit(); @@ -973,15 +956,13 @@ pub fn transformSync( var args = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); defer args.arena.deinit(); const code_arg = args.next() orelse { - globalThis.throwInvalidArgumentType("transformSync", "code", "string or Uint8Array"); - return .zero; + return globalThis.throwInvalidArgumentType("transformSync", "code", "string or Uint8Array"); }; var arena = Mimalloc.Arena.init() catch unreachable; defer arena.deinit(); const code_holder = JSC.Node.StringOrBuffer.fromJS(globalThis, arena.allocator(), code_arg) orelse { - globalThis.throwInvalidArgumentType("transformSync", "code", "string or Uint8Array"); - return .zero; + return globalThis.throwInvalidArgumentType("transformSync", "code", "string or Uint8Array"); }; defer code_holder.deinit(); const code = code_holder.slice(); @@ -1010,8 +991,7 @@ pub fn transformSync( if (arg.isObject()) { js_ctx_value = arg; } else { - globalThis.throwInvalidArgumentType("transformSync", "context", "object or loader"); - return .zero; + return globalThis.throwInvalidArgumentType("transformSync", "context", "object or loader"); } } if (js_ctx_value != .zero) { @@ -1049,23 +1029,19 @@ pub fn transformSync( if (comptime JSC.is_bindgen) Bundler.MacroJSValueType.zero else js_ctx_value, ) orelse { if ((this.bundler.log.warnings + this.bundler.log.errors) > 0) { - globalThis.throwValue(this.bundler.log.toJS(globalThis, globalThis.allocator(), "Parse error")); - return .zero; + return globalThis.throwValue(this.bundler.log.toJS(globalThis, globalThis.allocator(), "Parse error")); } - globalThis.throw("Failed to parse code", .{}); - return .zero; + return globalThis.throw("Failed to parse code", .{}); }; if ((this.bundler.log.warnings + this.bundler.log.errors) > 0) { - globalThis.throwValue(this.bundler.log.toJS(globalThis, globalThis.allocator(), "Parse error")); - return .zero; + return globalThis.throwValue(this.bundler.log.toJS(globalThis, globalThis.allocator(), "Parse error")); } var buffer_writer = this.buffer_writer orelse brk: { var writer = JSPrinter.BufferWriter.init(arena.backingAllocator()) catch { - globalThis.throw("Failed to create BufferWriter", .{}); - return .zero; + return globalThis.throw("Failed to create BufferWriter", .{}); }; writer.buffer.growIfNeeded(code.len) catch unreachable; @@ -1144,13 +1120,12 @@ pub fn scanImports(this: *Transpiler, globalThis: *JSC.JSGlobalObject, callframe defer args.deinit(); const code_arg = args.next() orelse { - globalThis.throwInvalidArgumentType("scanImports", "code", "string or Uint8Array"); - return .zero; + return globalThis.throwInvalidArgumentType("scanImports", "code", "string or Uint8Array"); }; const code_holder = JSC.Node.StringOrBuffer.fromJS(globalThis, args.arena.allocator(), code_arg) orelse { if (!globalThis.hasException()) { - globalThis.throwInvalidArgumentType("scanImports", "code", "string or Uint8Array"); + return globalThis.throwInvalidArgumentType("scanImports", "code", "string or Uint8Array"); } return .zero; }; @@ -1213,8 +1188,7 @@ pub fn scanImports(this: *Transpiler, globalThis: *JSC.JSGlobalObject, callframe ) catch |err| { defer this.scan_pass_result.reset(); if ((log.warnings + log.errors) > 0) { - globalThis.throwValue(log.toJS(globalThis, globalThis.allocator(), "Failed to scan imports")); - return .zero; + return globalThis.throwValue(log.toJS(globalThis, globalThis.allocator(), "Failed to scan imports")); } return globalThis.throwError(err, "Failed to scan imports"); @@ -1223,8 +1197,7 @@ pub fn scanImports(this: *Transpiler, globalThis: *JSC.JSGlobalObject, callframe defer this.scan_pass_result.reset(); if ((log.warnings + log.errors) > 0) { - globalThis.throwValue(log.toJS(globalThis, globalThis.allocator(), "Failed to scan imports")); - return .zero; + return globalThis.throwValue(log.toJS(globalThis, globalThis.allocator(), "Failed to scan imports")); } const named_imports_value = namedImportsToJS( diff --git a/src/bun.js/api/bun/dns_resolver.zig b/src/bun.js/api/bun/dns_resolver.zig index dfe1517aaa7d57..44a36a9e02ed2e 100644 --- a/src/bun.js/api/bun/dns_resolver.zig +++ b/src/bun.js/api/bun/dns_resolver.zig @@ -2270,16 +2270,14 @@ pub const DNSResolver = struct { } break :brk RecordType.map.getWithEql(record_type_str.getZigString(globalThis), JSC.ZigString.eqlComptime) orelse { - globalThis.throwInvalidArgumentType("resolve", "record", "one of: A, AAAA, CNAME, MX, NS, PTR, SOA, SRV, TXT"); - return .zero; + return globalThis.throwInvalidArgumentType("resolve", "record", "one of: A, AAAA, CNAME, MX, NS, PTR, SOA, SRV, TXT"); }; }; const name_value = arguments.ptr[0]; if (name_value.isEmptyOrUndefinedOrNull() or !name_value.isString()) { - globalThis.throwInvalidArgumentType("resolve", "name", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolve", "name", "string"); } const name_str = name_value.toStringOrNull(globalThis) orelse { @@ -2287,8 +2285,7 @@ pub const DNSResolver = struct { }; if (name_str.length() == 0) { - globalThis.throwInvalidArgumentType("resolve", "name", "non-empty string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolve", "name", "non-empty string"); } const name = name_str.toSliceClone(globalThis, bun.default_allocator); @@ -2339,16 +2336,14 @@ pub const DNSResolver = struct { const ip_value = arguments.ptr[0]; if (ip_value.isEmptyOrUndefinedOrNull() or !ip_value.isString()) { - globalThis.throwInvalidArgumentType("reverse", "ip", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("reverse", "ip", "string"); } const ip_str = ip_value.toStringOrNull(globalThis) orelse { return .zero; }; if (ip_str.length() == 0) { - globalThis.throwInvalidArgumentType("reverse", "ip", "non-empty string"); - return .zero; + return globalThis.throwInvalidArgumentType("reverse", "ip", "non-empty string"); } const ip_slice = ip_str.toSliceClone(globalThis, bun.default_allocator); @@ -2359,8 +2354,7 @@ pub const DNSResolver = struct { .result => |res| res, .err => |err| { defer ip_slice.deinit(); - globalThis.throwValue(err.toJS(globalThis)); - return .zero; + return globalThis.throwValue(err.toJS(globalThis)); }, }; @@ -2404,8 +2398,7 @@ pub const DNSResolver = struct { const name_value = arguments.ptr[0]; if (name_value.isEmptyOrUndefinedOrNull() or !name_value.isString()) { - globalThis.throwInvalidArgumentType("lookup", "hostname", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("lookup", "hostname", "string"); } const name_str = name_value.toStringOrNull(globalThis) orelse { @@ -2413,8 +2406,7 @@ pub const DNSResolver = struct { }; if (name_str.length() == 0) { - globalThis.throwInvalidArgumentType("lookup", "hostname", "non-empty string"); - return .zero; + return globalThis.throwInvalidArgumentType("lookup", "hostname", "non-empty string"); } var options = GetAddrInfo.Options{}; @@ -2428,8 +2420,7 @@ pub const DNSResolver = struct { } options = GetAddrInfo.Options.fromJS(arguments.ptr[1], globalThis) catch |err| { - globalThis.throw("Invalid options passed to lookup(): {s}", .{@errorName(err)}); - return .zero; + return globalThis.throw("Invalid options passed to lookup(): {s}", .{@errorName(err)}); }; } @@ -2441,7 +2432,7 @@ pub const DNSResolver = struct { return resolver.doLookup(name.slice(), port, options, globalThis); } - pub fn doLookup(this: *DNSResolver, name: []const u8, port: u16, options: GetAddrInfo.Options, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn doLookup(this: *DNSResolver, name: []const u8, port: u16, options: GetAddrInfo.Options, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { var opts = options; var backend = opts.backend; const normalized = normalizeDNSName(name, &backend); @@ -2473,8 +2464,7 @@ pub const DNSResolver = struct { const name_value = arguments.ptr[0]; if (name_value.isEmptyOrUndefinedOrNull() or !name_value.isString()) { - globalThis.throwInvalidArgumentType("resolveSrv", "hostname", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveSrv", "hostname", "string"); } const name_str = name_value.toStringOrNull(globalThis) orelse { @@ -2482,8 +2472,7 @@ pub const DNSResolver = struct { }; if (name_str.length() == 0) { - globalThis.throwInvalidArgumentType("resolveSrv", "hostname", "non-empty string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveSrv", "hostname", "non-empty string"); } const name = name_str.toSliceClone(globalThis, bun.default_allocator); @@ -2503,8 +2492,7 @@ pub const DNSResolver = struct { const name_value = arguments.ptr[0]; if (name_value.isEmptyOrUndefinedOrNull() or !name_value.isString()) { - globalThis.throwInvalidArgumentType("resolveSoa", "hostname", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveSoa", "hostname", "string"); } const name_str = name_value.toStringOrNull(globalThis) orelse { @@ -2528,8 +2516,7 @@ pub const DNSResolver = struct { const name_value = arguments.ptr[0]; if (name_value.isEmptyOrUndefinedOrNull() or !name_value.isString()) { - globalThis.throwInvalidArgumentType("resolveCaa", "hostname", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveCaa", "hostname", "string"); } const name_str = name_value.toStringOrNull(globalThis) orelse { @@ -2537,8 +2524,7 @@ pub const DNSResolver = struct { }; if (name_str.length() == 0) { - globalThis.throwInvalidArgumentType("resolveCaa", "hostname", "non-empty string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveCaa", "hostname", "non-empty string"); } const name = name_str.toSliceClone(globalThis, bun.default_allocator); @@ -2558,8 +2544,7 @@ pub const DNSResolver = struct { const name_value = arguments.ptr[0]; if (name_value.isEmptyOrUndefinedOrNull() or !name_value.isString()) { - globalThis.throwInvalidArgumentType("resolveNs", "hostname", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveNs", "hostname", "string"); } const name_str = name_value.toStringOrNull(globalThis) orelse { @@ -2583,8 +2568,7 @@ pub const DNSResolver = struct { const name_value = arguments.ptr[0]; if (name_value.isEmptyOrUndefinedOrNull() or !name_value.isString()) { - globalThis.throwInvalidArgumentType("resolvePtr", "hostname", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolvePtr", "hostname", "string"); } const name_str = name_value.toStringOrNull(globalThis) orelse { @@ -2592,8 +2576,7 @@ pub const DNSResolver = struct { }; if (name_str.length() == 0) { - globalThis.throwInvalidArgumentType("resolvePtr", "hostname", "non-empty string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolvePtr", "hostname", "non-empty string"); } const name = name_str.toSliceClone(globalThis, bun.default_allocator); @@ -2613,8 +2596,7 @@ pub const DNSResolver = struct { const name_value = arguments.ptr[0]; if (name_value.isEmptyOrUndefinedOrNull() or !name_value.isString()) { - globalThis.throwInvalidArgumentType("resolveCname", "hostname", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveCname", "hostname", "string"); } const name_str = name_value.toStringOrNull(globalThis) orelse { @@ -2622,8 +2604,7 @@ pub const DNSResolver = struct { }; if (name_str.length() == 0) { - globalThis.throwInvalidArgumentType("resolveCname", "hostname", "non-empty string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveCname", "hostname", "non-empty string"); } const name = name_str.toSliceClone(globalThis, bun.default_allocator); @@ -2643,8 +2624,7 @@ pub const DNSResolver = struct { const name_value = arguments.ptr[0]; if (name_value.isEmptyOrUndefinedOrNull() or !name_value.isString()) { - globalThis.throwInvalidArgumentType("resolveMx", "hostname", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveMx", "hostname", "string"); } const name_str = name_value.toStringOrNull(globalThis) orelse { @@ -2652,8 +2632,7 @@ pub const DNSResolver = struct { }; if (name_str.length() == 0) { - globalThis.throwInvalidArgumentType("resolveMx", "hostname", "non-empty string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveMx", "hostname", "non-empty string"); } const name = name_str.toSliceClone(globalThis, bun.default_allocator); @@ -2673,8 +2652,7 @@ pub const DNSResolver = struct { const name_value = arguments.ptr[0]; if (name_value.isEmptyOrUndefinedOrNull() or !name_value.isString()) { - globalThis.throwInvalidArgumentType("resolveNaptr", "hostname", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveNaptr", "hostname", "string"); } const name_str = name_value.toStringOrNull(globalThis) orelse { @@ -2682,8 +2660,7 @@ pub const DNSResolver = struct { }; if (name_str.length() == 0) { - globalThis.throwInvalidArgumentType("resolveNaptr", "hostname", "non-empty string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveNaptr", "hostname", "non-empty string"); } const name = name_str.toSliceClone(globalThis, bun.default_allocator); @@ -2703,8 +2680,7 @@ pub const DNSResolver = struct { const name_value = arguments.ptr[0]; if (name_value.isEmptyOrUndefinedOrNull() or !name_value.isString()) { - globalThis.throwInvalidArgumentType("resolveTxt", "hostname", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveTxt", "hostname", "string"); } const name_str = name_value.toStringOrNull(globalThis) orelse { @@ -2712,8 +2688,7 @@ pub const DNSResolver = struct { }; if (name_str.length() == 0) { - globalThis.throwInvalidArgumentType("resolveTxt", "hostname", "non-empty string"); - return .zero; + return globalThis.throwInvalidArgumentType("resolveTxt", "hostname", "non-empty string"); } const name = name_str.toSliceClone(globalThis, bun.default_allocator); @@ -2724,12 +2699,11 @@ pub const DNSResolver = struct { return resolver.doResolveCAres(c_ares.struct_ares_txt_reply, "txt", name.slice(), globalThis); } - pub fn doResolveCAres(this: *DNSResolver, comptime cares_type: type, comptime type_name: []const u8, name: []const u8, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn doResolveCAres(this: *DNSResolver, comptime cares_type: type, comptime type_name: []const u8, name: []const u8, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { var channel: *c_ares.Channel = switch (this.getChannel()) { .result => |res| res, .err => |err| { - globalThis.throwValue(err.toJS(globalThis)); - return .zero; + return globalThis.throwValue(err.toJS(globalThis)); }, }; @@ -2765,7 +2739,7 @@ pub const DNSResolver = struct { return promise; } - pub fn c_aresLookupWithNormalizedName(this: *DNSResolver, query: GetAddrInfo, globalThis: *JSC.JSGlobalObject) JSC.JSValue { + pub fn c_aresLookupWithNormalizedName(this: *DNSResolver, query: GetAddrInfo, globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { var channel: *c_ares.Channel = switch (this.getChannel()) { .result => |res| res, .err => |err| { @@ -2775,8 +2749,7 @@ pub const DNSResolver = struct { .message = bun.String.static(err.label()), }; - globalThis.throwValue(system_error.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(system_error.toErrorInstance(globalThis)) catch .zero; }, }; @@ -2828,8 +2801,7 @@ pub const DNSResolver = struct { .message = bun.String.static(err.label()), }; - globalThis.throwValue(system_error.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(system_error.toErrorInstance(globalThis)); }, }; @@ -2837,8 +2809,7 @@ pub const DNSResolver = struct { const r = c_ares.ares_get_servers_ports(channel, &servers); if (r != c_ares.ARES_SUCCESS) { const err = c_ares.Error.get(r).?; - globalThis.throwValue(globalThis.createErrorInstance("ares_get_servers_ports error: {s}", .{err.label()})); - return .zero; + return globalThis.throwValue(globalThis.createErrorInstance("ares_get_servers_ports error: {s}", .{err.label()})); } defer c_ares.ares_free_data(servers); @@ -2863,11 +2834,7 @@ pub const DNSResolver = struct { break :blk c_ares.ares_inet_ntop(family, ¤t.addr.addr4, buf[1..], @sizeOf(@TypeOf(buf)) - 1); }; if (ip == null) { - globalThis.throwValue(globalThis.createErrorInstance( - "ares_inet_ntop error: no more space to convert a network format address", - .{}, - )); - return .zero; + return globalThis.throwValue(globalThis.createErrorInstance("ares_inet_ntop error: no more space to convert a network format address", .{})); } var port = current.tcp_port; @@ -2909,29 +2876,25 @@ pub const DNSResolver = struct { const addr_value = arguments.ptr[0]; const port_value = arguments.ptr[1]; if (addr_value.isEmptyOrUndefinedOrNull() or !addr_value.isString()) { - globalThis.throwInvalidArgumentType("lookupService", "address", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("lookupService", "address", "string"); } const addr_str = addr_value.toStringOrNull(globalThis) orelse { return .zero; }; if (addr_str.length() == 0) { - globalThis.throwInvalidArgumentType("lookupService", "address", "non-empty string"); - return .zero; + return globalThis.throwInvalidArgumentType("lookupService", "address", "non-empty string"); } const addr_s = addr_str.getZigString(globalThis).slice(); const port: u16 = if (port_value.isNumber()) blk: { break :blk port_value.to(u16); } else { - globalThis.throwInvalidArgumentType("lookupService", "port", "invalid port"); - return .zero; + return globalThis.throwInvalidArgumentType("lookupService", "port", "invalid port"); }; var sa: std.posix.sockaddr.storage = std.mem.zeroes(std.posix.sockaddr.storage); if (c_ares.getSockaddr(addr_s, port, @as(*std.posix.sockaddr, @ptrCast(&sa))) != 0) { - globalThis.throwInvalidArgumentType("lookupService", "address", "invalid address"); - return .zero; + return globalThis.throwInvalidArgumentType("lookupService", "address", "invalid address"); } var vm = globalThis.bunVM(); @@ -2945,8 +2908,7 @@ pub const DNSResolver = struct { .message = bun.String.static(err.label()), }; - globalThis.throwValue(system_error.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(system_error.toErrorInstance(globalThis)); }, }; diff --git a/src/bun.js/api/bun/h2_frame_parser.zig b/src/bun.js/api/bun/h2_frame_parser.zig index 343d425d5d059a..05d30aa6137458 100644 --- a/src/bun.js/api/bun/h2_frame_parser.zig +++ b/src/bun.js/api/bun/h2_frame_parser.zig @@ -305,8 +305,7 @@ fn jsGetUnpackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Call var payload = array_buffer.byteSlice(); const settingByteSize = SettingsPayloadUnit.byteSize; if (payload.len < settingByteSize or payload.len % settingByteSize != 0) { - globalObject.throw("Expected buf to be a Buffer of at least 6 bytes and a multiple of 6 bytes", .{}); - return .zero; + return globalObject.throw("Expected buf to be a Buffer of at least 6 bytes and a multiple of 6 bytes", .{}); } var i: usize = 0; @@ -318,8 +317,7 @@ fn jsGetUnpackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Call } return settings.toJS(globalObject); } else if (!data_arg.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected buf to be a Buffer", .{}); - return .zero; + return globalObject.throw("Expected buf to be a Buffer", .{}); } else { return settings.toJS(globalObject); } @@ -328,34 +326,29 @@ fn jsGetUnpackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Call fn jsAssertSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected settings to be a object", .{}); - return .zero; + return globalObject.throw("Expected settings to be a object", .{}); } if (args_list.len > 0 and !args_list.ptr[0].isEmptyOrUndefinedOrNull()) { const options = args_list.ptr[0]; if (!options.isObject()) { - globalObject.throw("Expected settings to be a object", .{}); - return .zero; + return globalObject.throw("Expected settings to be a object", .{}); } if (try options.get(globalObject, "headerTableSize")) |headerTableSize| { if (headerTableSize.isNumber()) { const headerTableSizeValue = headerTableSize.toInt32(); if (headerTableSizeValue > MAX_HEADER_TABLE_SIZE or headerTableSizeValue < 0) { - globalObject.throw("Expected headerTableSize to be a number between 0 and 2^32-1", .{}); - return .zero; + return globalObject.throw("Expected headerTableSize to be a number between 0 and 2^32-1", .{}); } } else if (!headerTableSize.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected headerTableSize to be a number", .{}); - return .zero; + return globalObject.throw("Expected headerTableSize to be a number", .{}); } } if (try options.get(globalObject, "enablePush")) |enablePush| { if (!enablePush.isBoolean() and !enablePush.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected enablePush to be a boolean", .{}); - return .zero; + return globalObject.throw("Expected enablePush to be a boolean", .{}); } } @@ -363,12 +356,10 @@ fn jsAssertSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame if (initialWindowSize.isNumber()) { const initialWindowSizeValue = initialWindowSize.toInt32(); if (initialWindowSizeValue > MAX_HEADER_TABLE_SIZE or initialWindowSizeValue < 0) { - globalObject.throw("Expected initialWindowSize to be a number between 0 and 2^32-1", .{}); - return .zero; + return globalObject.throw("Expected initialWindowSize to be a number between 0 and 2^32-1", .{}); } } else if (!initialWindowSize.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected initialWindowSize to be a number", .{}); - return .zero; + return globalObject.throw("Expected initialWindowSize to be a number", .{}); } } @@ -376,12 +367,10 @@ fn jsAssertSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame if (maxFrameSize.isNumber()) { const maxFrameSizeValue = maxFrameSize.toInt32(); if (maxFrameSizeValue > MAX_FRAME_SIZE or maxFrameSizeValue < 16384) { - globalObject.throw("Expected maxFrameSize to be a number between 16,384 and 2^24-1", .{}); - return .zero; + return globalObject.throw("Expected maxFrameSize to be a number between 16,384 and 2^24-1", .{}); } } else if (!maxFrameSize.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected maxFrameSize to be a number", .{}); - return .zero; + return globalObject.throw("Expected maxFrameSize to be a number", .{}); } } @@ -389,12 +378,10 @@ fn jsAssertSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame if (maxConcurrentStreams.isNumber()) { const maxConcurrentStreamsValue = maxConcurrentStreams.toInt32(); if (maxConcurrentStreamsValue > MAX_HEADER_TABLE_SIZE or maxConcurrentStreamsValue < 0) { - globalObject.throw("Expected maxConcurrentStreams to be a number between 0 and 2^32-1", .{}); - return .zero; + return globalObject.throw("Expected maxConcurrentStreams to be a number between 0 and 2^32-1", .{}); } } else if (!maxConcurrentStreams.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected maxConcurrentStreams to be a number", .{}); - return .zero; + return globalObject.throw("Expected maxConcurrentStreams to be a number", .{}); } } @@ -402,12 +389,10 @@ fn jsAssertSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame if (maxHeaderListSize.isNumber()) { const maxHeaderListSizeValue = maxHeaderListSize.toInt32(); if (maxHeaderListSizeValue > MAX_HEADER_TABLE_SIZE or maxHeaderListSizeValue < 0) { - globalObject.throw("Expected maxHeaderListSize to be a number between 0 and 2^32-1", .{}); - return .zero; + return globalObject.throw("Expected maxHeaderListSize to be a number between 0 and 2^32-1", .{}); } } else if (!maxHeaderListSize.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected maxHeaderListSize to be a number", .{}); - return .zero; + return globalObject.throw("Expected maxHeaderListSize to be a number", .{}); } } @@ -415,12 +400,10 @@ fn jsAssertSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame if (maxHeaderSize.isNumber()) { const maxHeaderSizeValue = maxHeaderSize.toInt32(); if (maxHeaderSizeValue > MAX_HEADER_TABLE_SIZE or maxHeaderSizeValue < 0) { - globalObject.throw("Expected maxHeaderSize to be a number between 0 and 2^32-1", .{}); - return .zero; + return globalObject.throw("Expected maxHeaderSize to be a number between 0 and 2^32-1", .{}); } } else if (!maxHeaderSize.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected maxHeaderSize to be a number", .{}); - return .zero; + return globalObject.throw("Expected maxHeaderSize to be a number", .{}); } } } @@ -435,21 +418,18 @@ fn jsGetPackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFr const options = args_list.ptr[0]; if (!options.isObject()) { - globalObject.throw("Expected settings to be a object", .{}); - return .zero; + return globalObject.throw("Expected settings to be a object", .{}); } if (try options.get(globalObject, "headerTableSize")) |headerTableSize| { if (headerTableSize.isNumber()) { const headerTableSizeValue = headerTableSize.toInt32(); if (headerTableSizeValue > MAX_HEADER_TABLE_SIZE or headerTableSizeValue < 0) { - globalObject.throw("Expected headerTableSize to be a number between 0 and 2^32-1", .{}); - return .zero; + return globalObject.throw("Expected headerTableSize to be a number between 0 and 2^32-1", .{}); } settings.headerTableSize = @intCast(headerTableSizeValue); } else if (!headerTableSize.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected headerTableSize to be a number", .{}); - return .zero; + return globalObject.throw("Expected headerTableSize to be a number", .{}); } } @@ -457,8 +437,7 @@ fn jsGetPackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFr if (enablePush.isBoolean()) { settings.enablePush = if (enablePush.asBoolean()) 1 else 0; } else if (!enablePush.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected enablePush to be a boolean", .{}); - return .zero; + return globalObject.throw("Expected enablePush to be a boolean", .{}); } } @@ -466,13 +445,11 @@ fn jsGetPackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFr if (initialWindowSize.isNumber()) { const initialWindowSizeValue = initialWindowSize.toInt32(); if (initialWindowSizeValue > MAX_HEADER_TABLE_SIZE or initialWindowSizeValue < 0) { - globalObject.throw("Expected initialWindowSize to be a number between 0 and 2^32-1", .{}); - return .zero; + return globalObject.throw("Expected initialWindowSize to be a number between 0 and 2^32-1", .{}); } settings.initialWindowSize = @intCast(initialWindowSizeValue); } else if (!initialWindowSize.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected initialWindowSize to be a number", .{}); - return .zero; + return globalObject.throw("Expected initialWindowSize to be a number", .{}); } } @@ -480,13 +457,11 @@ fn jsGetPackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFr if (maxFrameSize.isNumber()) { const maxFrameSizeValue = maxFrameSize.toInt32(); if (maxFrameSizeValue > MAX_FRAME_SIZE or maxFrameSizeValue < 16384) { - globalObject.throw("Expected maxFrameSize to be a number between 16,384 and 2^24-1", .{}); - return .zero; + return globalObject.throw("Expected maxFrameSize to be a number between 16,384 and 2^24-1", .{}); } settings.maxFrameSize = @intCast(maxFrameSizeValue); } else if (!maxFrameSize.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected maxFrameSize to be a number", .{}); - return .zero; + return globalObject.throw("Expected maxFrameSize to be a number", .{}); } } @@ -494,13 +469,11 @@ fn jsGetPackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFr if (maxConcurrentStreams.isNumber()) { const maxConcurrentStreamsValue = maxConcurrentStreams.toInt32(); if (maxConcurrentStreamsValue > MAX_HEADER_TABLE_SIZE or maxConcurrentStreamsValue < 0) { - globalObject.throw("Expected maxConcurrentStreams to be a number between 0 and 2^32-1", .{}); - return .zero; + return globalObject.throw("Expected maxConcurrentStreams to be a number between 0 and 2^32-1", .{}); } settings.maxConcurrentStreams = @intCast(maxConcurrentStreamsValue); } else if (!maxConcurrentStreams.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected maxConcurrentStreams to be a number", .{}); - return .zero; + return globalObject.throw("Expected maxConcurrentStreams to be a number", .{}); } } @@ -508,13 +481,11 @@ fn jsGetPackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFr if (maxHeaderListSize.isNumber()) { const maxHeaderListSizeValue = maxHeaderListSize.toInt32(); if (maxHeaderListSizeValue > MAX_HEADER_TABLE_SIZE or maxHeaderListSizeValue < 0) { - globalObject.throw("Expected maxHeaderListSize to be a number between 0 and 2^32-1", .{}); - return .zero; + return globalObject.throw("Expected maxHeaderListSize to be a number between 0 and 2^32-1", .{}); } settings.maxHeaderListSize = @intCast(maxHeaderListSizeValue); } else if (!maxHeaderListSize.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected maxHeaderListSize to be a number", .{}); - return .zero; + return globalObject.throw("Expected maxHeaderListSize to be a number", .{}); } } @@ -522,13 +493,11 @@ fn jsGetPackedSettings(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFr if (maxHeaderSize.isNumber()) { const maxHeaderSizeValue = maxHeaderSize.toInt32(); if (maxHeaderSizeValue > MAX_HEADER_TABLE_SIZE or maxHeaderSizeValue < 0) { - globalObject.throw("Expected maxHeaderSize to be a number between 0 and 2^32-1", .{}); - return .zero; + return globalObject.throw("Expected maxHeaderSize to be a number between 0 and 2^32-1", .{}); } settings.maxHeaderListSize = @intCast(maxHeaderSizeValue); } else if (!maxHeaderSize.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected maxHeaderSize to be a number", .{}); - return .zero; + return globalObject.throw("Expected maxHeaderSize to be a number", .{}); } } } @@ -2336,13 +2305,11 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected encoding argument", .{}); - return .zero; + return globalObject.throw("Expected encoding argument", .{}); } this.handlers.binary_type = BinaryType.fromJSValue(globalObject, args_list.ptr[0]) orelse { const err = JSC.toInvalidArguments("Expected 'binaryType' to be 'arraybuffer', 'uint8array', 'buffer'", .{}, globalObject).asObjectRef(); - globalObject.throwValue(err); - return .zero; + return globalObject.throwValue(err); }; return .undefined; @@ -2350,18 +2317,18 @@ pub const H2FrameParser = struct { pub fn loadSettingsFromJSValue(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, options: JSC.JSValue) bun.JSError!void { if (options.isEmptyOrUndefinedOrNull() or !options.isObject()) { - return globalObject.throw2("Expected settings to be a object", .{}); + return globalObject.throw("Expected settings to be a object", .{}); } if (try options.get(globalObject, "headerTableSize")) |headerTableSize| { if (headerTableSize.isNumber()) { const headerTableSizeValue = headerTableSize.toInt32(); if (headerTableSizeValue > MAX_HEADER_TABLE_SIZE or headerTableSizeValue < 0) { - return globalObject.throw2("Expected headerTableSize to be a number between 0 and 2^32-1", .{}); + return globalObject.throw("Expected headerTableSize to be a number between 0 and 2^32-1", .{}); } this.localSettings.headerTableSize = @intCast(headerTableSizeValue); } else if (!headerTableSize.isEmptyOrUndefinedOrNull()) { - return globalObject.throw2("Expected headerTableSize to be a number", .{}); + return globalObject.throw("Expected headerTableSize to be a number", .{}); } } @@ -2369,7 +2336,7 @@ pub const H2FrameParser = struct { if (enablePush.isBoolean()) { this.localSettings.enablePush = if (enablePush.asBoolean()) 1 else 0; } else if (!enablePush.isEmptyOrUndefinedOrNull()) { - return globalObject.throw2("Expected enablePush to be a boolean", .{}); + return globalObject.throw("Expected enablePush to be a boolean", .{}); } } @@ -2377,11 +2344,11 @@ pub const H2FrameParser = struct { if (initialWindowSize.isNumber()) { const initialWindowSizeValue = initialWindowSize.toInt32(); if (initialWindowSizeValue > MAX_HEADER_TABLE_SIZE or initialWindowSizeValue < 0) { - return globalObject.throw2("Expected initialWindowSize to be a number between 0 and 2^32-1", .{}); + return globalObject.throw("Expected initialWindowSize to be a number between 0 and 2^32-1", .{}); } this.localSettings.initialWindowSize = @intCast(initialWindowSizeValue); } else if (!initialWindowSize.isEmptyOrUndefinedOrNull()) { - return globalObject.throw2("Expected initialWindowSize to be a number", .{}); + return globalObject.throw("Expected initialWindowSize to be a number", .{}); } } @@ -2389,11 +2356,11 @@ pub const H2FrameParser = struct { if (maxFrameSize.isNumber()) { const maxFrameSizeValue = maxFrameSize.toInt32(); if (maxFrameSizeValue > MAX_FRAME_SIZE or maxFrameSizeValue < 16384) { - return globalObject.throw2("Expected maxFrameSize to be a number between 16,384 and 2^24-1", .{}); + return globalObject.throw("Expected maxFrameSize to be a number between 16,384 and 2^24-1", .{}); } this.localSettings.maxFrameSize = @intCast(maxFrameSizeValue); } else if (!maxFrameSize.isEmptyOrUndefinedOrNull()) { - return globalObject.throw2("Expected maxFrameSize to be a number", .{}); + return globalObject.throw("Expected maxFrameSize to be a number", .{}); } } @@ -2401,11 +2368,11 @@ pub const H2FrameParser = struct { if (maxConcurrentStreams.isNumber()) { const maxConcurrentStreamsValue = maxConcurrentStreams.toInt32(); if (maxConcurrentStreamsValue > MAX_HEADER_TABLE_SIZE or maxConcurrentStreamsValue < 0) { - return globalObject.throw2("Expected maxConcurrentStreams to be a number between 0 and 2^32-1", .{}); + return globalObject.throw("Expected maxConcurrentStreams to be a number between 0 and 2^32-1", .{}); } this.localSettings.maxConcurrentStreams = @intCast(maxConcurrentStreamsValue); } else if (!maxConcurrentStreams.isEmptyOrUndefinedOrNull()) { - return globalObject.throw2("Expected maxConcurrentStreams to be a number", .{}); + return globalObject.throw("Expected maxConcurrentStreams to be a number", .{}); } } @@ -2413,11 +2380,11 @@ pub const H2FrameParser = struct { if (maxHeaderListSize.isNumber()) { const maxHeaderListSizeValue = maxHeaderListSize.toInt32(); if (maxHeaderListSizeValue > MAX_HEADER_TABLE_SIZE or maxHeaderListSizeValue < 0) { - return globalObject.throw2("Expected maxHeaderListSize to be a number between 0 and 2^32-1", .{}); + return globalObject.throw("Expected maxHeaderListSize to be a number between 0 and 2^32-1", .{}); } this.localSettings.maxHeaderListSize = @intCast(maxHeaderListSizeValue); } else if (!maxHeaderListSize.isEmptyOrUndefinedOrNull()) { - return globalObject.throw2("Expected maxHeaderListSize to be a number", .{}); + return globalObject.throw("Expected maxHeaderListSize to be a number", .{}); } } @@ -2425,11 +2392,11 @@ pub const H2FrameParser = struct { if (maxHeaderSize.isNumber()) { const maxHeaderSizeValue = maxHeaderSize.toInt32(); if (maxHeaderSizeValue > MAX_HEADER_TABLE_SIZE or maxHeaderSizeValue < 0) { - return globalObject.throw2("Expected maxHeaderSize to be a number between 0 and 2^32-1", .{}); + return globalObject.throw("Expected maxHeaderSize to be a number between 0 and 2^32-1", .{}); } this.localSettings.maxHeaderListSize = @intCast(maxHeaderSizeValue); } else if (!maxHeaderSize.isEmptyOrUndefinedOrNull()) { - return globalObject.throw2("Expected maxHeaderSize to be a number", .{}); + return globalObject.throw("Expected maxHeaderSize to be a number", .{}); } } return; @@ -2439,8 +2406,7 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected settings argument", .{}); - return .zero; + return globalObject.throw("Expected settings argument", .{}); } const options = args_list.ptr[0]; @@ -2470,20 +2436,17 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(3); if (args_list.len < 1) { - globalObject.throw("Expected errorCode argument", .{}); - return .zero; + return globalObject.throw("Expected errorCode argument", .{}); } const error_code_arg = args_list.ptr[0]; if (!error_code_arg.isNumber()) { - globalObject.throw("Expected errorCode to be a number", .{}); - return .zero; + return globalObject.throw("Expected errorCode to be a number", .{}); } const errorCode = error_code_arg.toInt32(); if (errorCode < 1 and errorCode > 13) { - globalObject.throw("invalid errorCode", .{}); - return .zero; + return globalObject.throw("invalid errorCode", .{}); } var lastStreamID = this.lastStreamID; @@ -2491,13 +2454,11 @@ pub const H2FrameParser = struct { const last_stream_arg = args_list.ptr[1]; if (!last_stream_arg.isEmptyOrUndefinedOrNull()) { if (!last_stream_arg.isNumber()) { - globalObject.throw("Expected lastStreamId to be a number", .{}); - return .zero; + return globalObject.throw("Expected lastStreamId to be a number", .{}); } const id = last_stream_arg.toInt32(); if (id < 0 and id > MAX_STREAM_ID) { - globalObject.throw("Expected lastStreamId to be a number between 1 and 2147483647", .{}); - return .zero; + return globalObject.throw("Expected lastStreamId to be a number between 1 and 2147483647", .{}); } lastStreamID = @intCast(id); } @@ -2521,14 +2482,12 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected payload argument", .{}); - return .zero; + return globalObject.throw("Expected payload argument", .{}); } if (this.outStandingPings >= this.maxOutstandingPings) { const exception = JSC.toTypeError(.ERR_HTTP2_PING_CANCEL, "HTTP2 ping cancelled", .{}, globalObject); - globalObject.throwValue(exception); - return .zero; + return globalObject.throwValue(exception); } if (args_list.ptr[0].asArrayBuffer(globalObject)) |array_buffer| { @@ -2537,33 +2496,28 @@ pub const H2FrameParser = struct { return .undefined; } - globalObject.throw("Expected payload to be a Buffer", .{}); - return .zero; + return globalObject.throw("Expected payload to be a Buffer", .{}); } pub fn getEndAfterHeaders(this: *H2FrameParser, globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { JSC.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected stream argument", .{}); - return .zero; + return globalObject.throw("Expected stream argument", .{}); } const stream_arg = args_list.ptr[0]; if (!stream_arg.isNumber()) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } const stream_id = stream_arg.toU32(); if (stream_id == 0) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } const stream = this.streams.getPtr(stream_id) orelse { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); }; return JSC.JSValue.jsBoolean(stream.endAfterHeaders); @@ -2573,25 +2527,21 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected stream argument", .{}); - return .zero; + return globalObject.throw("Expected stream argument", .{}); } const stream_arg = args_list.ptr[0]; if (!stream_arg.isNumber()) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } const stream_id = stream_arg.toU32(); if (stream_id == 0) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } const stream = this.streams.getPtr(stream_id) orelse { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); }; if (stream.signal) |signal_ref| { @@ -2604,25 +2554,21 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected stream argument", .{}); - return .zero; + return globalObject.throw("Expected stream argument", .{}); } const stream_arg = args_list.ptr[0]; if (!stream_arg.isNumber()) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } const stream_id = stream_arg.toU32(); if (stream_id == 0) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } var stream = this.streams.getPtr(stream_id) orelse { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); }; var state = JSC.JSValue.createEmptyObject(globalObject, 7); @@ -2641,26 +2587,22 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(2); if (args_list.len < 2) { - globalObject.throw("Expected stream and options arguments", .{}); - return .zero; + return globalObject.throw("Expected stream and options arguments", .{}); } const stream_arg = args_list.ptr[0]; const options = args_list.ptr[1]; if (!stream_arg.isNumber()) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } const stream_id = stream_arg.toU32(); if (stream_id == 0) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } var stream = this.streams.getPtr(stream_id) orelse { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); }; if (!stream.canSendData() and !stream.canReceiveData()) { @@ -2668,8 +2610,7 @@ pub const H2FrameParser = struct { } if (!options.isObject()) { - globalObject.throw("Invalid priority", .{}); - return .zero; + return globalObject.throw("Invalid priority", .{}); } var weight = stream.weight; @@ -2680,8 +2621,7 @@ pub const H2FrameParser = struct { if (js_weight.isNumber()) { const weight_u32 = js_weight.toU32(); if (weight_u32 > 255) { - globalObject.throw("Invalid weight", .{}); - return .zero; + return globalObject.throw("Invalid weight", .{}); } weight = @intCast(weight_u32); } @@ -2691,8 +2631,7 @@ pub const H2FrameParser = struct { if (js_parent.isNumber()) { parent_id = js_parent.toU32(); if (parent_id == 0 or parent_id > MAX_STREAM_ID) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } } } @@ -2740,26 +2679,22 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(2); if (args_list.len < 2) { - globalObject.throw("Expected stream and code arguments", .{}); - return .zero; + return globalObject.throw("Expected stream and code arguments", .{}); } const stream_arg = args_list.ptr[0]; const error_arg = args_list.ptr[1]; if (!stream_arg.isNumber()) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } const stream_id = stream_arg.toU32(); if (stream_id == 0 or stream_id > MAX_STREAM_ID) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } var stream = this.streams.getPtr(stream_id) orelse { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); }; if (!stream.canSendData() and !stream.canReceiveData()) { @@ -2767,14 +2702,12 @@ pub const H2FrameParser = struct { } if (!error_arg.isNumber()) { - globalObject.throw("Invalid ErrorCode", .{}); - return .zero; + return globalObject.throw("Invalid ErrorCode", .{}); } const error_code = error_arg.toU32(); if (error_code > 13) { - globalObject.throw("Invalid ErrorCode", .{}); - return .zero; + return globalObject.throw("Invalid ErrorCode", .{}); } this.endStream(stream, @enumFromInt(error_code)); @@ -2897,26 +2830,22 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected stream, headers and sensitiveHeaders arguments", .{}); - return .zero; + return globalObject.throw("Expected stream, headers and sensitiveHeaders arguments", .{}); } const stream_arg = args_list.ptr[0]; if (!stream_arg.isNumber()) { - globalObject.throw("Expected stream to be a number", .{}); - return .zero; + return globalObject.throw("Expected stream to be a number", .{}); } const stream_id = stream_arg.toU32(); if (stream_id == 0 or stream_id > MAX_STREAM_ID) { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); } var stream = this.streams.getPtr(@intCast(stream_id)) orelse { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); }; stream.waitForTrailers = false; @@ -2938,7 +2867,7 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(3); if (args_list.len < 3) { - return globalObject.throw2("Expected stream, headers and sensitiveHeaders arguments", .{}); + return globalObject.throw("Expected stream, headers and sensitiveHeaders arguments", .{}); } const stream_arg = args_list.ptr[0]; @@ -2946,24 +2875,24 @@ pub const H2FrameParser = struct { const sensitive_arg = args_list.ptr[2]; if (!stream_arg.isNumber()) { - return globalObject.throw2("Expected stream to be a number", .{}); + return globalObject.throw("Expected stream to be a number", .{}); } const stream_id = stream_arg.toU32(); if (stream_id == 0 or stream_id > MAX_STREAM_ID) { - return globalObject.throw2("Invalid stream id", .{}); + return globalObject.throw("Invalid stream id", .{}); } var stream = this.streams.getPtr(@intCast(stream_id)) orelse { - return globalObject.throw2("Invalid stream id", .{}); + return globalObject.throw("Invalid stream id", .{}); }; if (!headers_arg.isObject()) { - return globalObject.throw2("Expected headers to be an object", .{}); + return globalObject.throw("Expected headers to be an object", .{}); } if (!sensitive_arg.isObject()) { - return globalObject.throw2("Expected sensitiveHeaders to be an object", .{}); + return globalObject.throw("Expected sensitiveHeaders to be an object", .{}); } // max frame size will be always at least 16384 @@ -2986,12 +2915,12 @@ pub const H2FrameParser = struct { if (header_name.charAt(0) == ':') { const exception = JSC.toTypeError(.ERR_HTTP2_INVALID_PSEUDOHEADER, "\"{s}\" is an invalid pseudoheader or is used incorrectly", .{name}, globalObject); - return globalObject.throwValue2(exception); + return globalObject.throwValue(exception); } var js_value = try headers_arg.getTruthy(globalObject, name) orelse { const exception = JSC.toTypeError(.ERR_HTTP2_INVALID_HEADER_VALUE, "Invalid value for header \"{s}\"", .{name}, globalObject); - return globalObject.throwValue2(exception); + return globalObject.throwValue(exception); }; if (js_value.jsType().isArray()) { @@ -3000,18 +2929,18 @@ pub const H2FrameParser = struct { if (SingleValueHeaders.has(name) and value_iter.len > 1) { const exception = JSC.toTypeError(.ERR_HTTP2_INVALID_SINGLE_VALUE_HEADER, "Header field \"{s}\" must only have a single value", .{name}, globalObject); - return globalObject.throwValue2(exception); + return globalObject.throwValue(exception); } while (value_iter.next()) |item| { if (item.isEmptyOrUndefinedOrNull()) { const exception = JSC.toTypeError(.ERR_HTTP2_INVALID_HEADER_VALUE, "Invalid value for header \"{s}\"", .{name}, globalObject); - return globalObject.throwValue2(exception); + return globalObject.throwValue(exception); } const value_str = item.toStringOrNull(globalObject) orelse { const exception = JSC.toTypeError(.ERR_HTTP2_INVALID_HEADER_VALUE, "Invalid value for header \"{s}\"", .{name}, globalObject); - return globalObject.throwValue2(exception); + return globalObject.throwValue(exception); }; const never_index = try sensitive_arg.getTruthy(globalObject, "neverIndex") != null; @@ -3033,7 +2962,7 @@ pub const H2FrameParser = struct { } else { const value_str = js_value.toStringOrNull(globalObject) orelse { const exception = JSC.toTypeError(.ERR_HTTP2_INVALID_HEADER_VALUE, "Invalid value for header \"{s}\"", .{name}, globalObject); - return globalObject.throwValue2(exception); + return globalObject.throwValue(exception); }; const never_index = try sensitive_arg.getTruthy(globalObject, "neverIndex") != null; @@ -3082,17 +3011,17 @@ pub const H2FrameParser = struct { const stream_arg, const data_arg, const encoding_arg, const close_arg, const callback_arg = args.ptr; if (!stream_arg.isNumber()) { - return globalObject.throw2("Expected stream to be a number", .{}); + return globalObject.throw("Expected stream to be a number", .{}); } const stream_id = stream_arg.toU32(); if (stream_id == 0 or stream_id > MAX_STREAM_ID) { - return globalObject.throw2("Invalid stream id", .{}); + return globalObject.throw("Invalid stream id", .{}); } const close = close_arg.toBoolean(); var stream = this.streams.getPtr(@intCast(stream_id)) orelse { - return globalObject.throw2("Invalid stream id", .{}); + return globalObject.throw("Invalid stream id", .{}); }; if (!stream.canSendData()) { this.dispatchWriteCallback(callback_arg); @@ -3169,19 +3098,16 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected stream_id argument", .{}); - return .zero; + return globalObject.throw("Expected stream_id argument", .{}); } const stream_id_arg = args_list.ptr[0]; if (!stream_id_arg.isNumber()) { - globalObject.throw("Expected stream_id to be a number", .{}); - return .zero; + return globalObject.throw("Expected stream_id to be a number", .{}); } var stream = this.streams.getPtr(stream_id_arg.to(u32)) orelse { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); }; return stream.jsContext.get() orelse .undefined; @@ -3191,23 +3117,19 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(2); if (args_list.len < 2) { - globalObject.throw("Expected stream_id and context arguments", .{}); - return .zero; + return globalObject.throw("Expected stream_id and context arguments", .{}); } const stream_id_arg = args_list.ptr[0]; if (!stream_id_arg.isNumber()) { - globalObject.throw("Expected stream_id to be a number", .{}); - return .zero; + return globalObject.throw("Expected stream_id to be a number", .{}); } var stream = this.streams.getPtr(stream_id_arg.to(u32)) orelse { - globalObject.throw("Invalid stream id", .{}); - return .zero; + return globalObject.throw("Invalid stream id", .{}); }; const context_arg = args_list.ptr[1]; if (!context_arg.isObject()) { - globalObject.throw("Expected context to be an object", .{}); - return .zero; + return globalObject.throw("Expected context to be an object", .{}); } stream.setContext(context_arg, globalObject); @@ -3252,8 +3174,7 @@ pub const H2FrameParser = struct { const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected error argument", .{}); - return .zero; + return globalObject.throw("Expected error argument", .{}); } var it = StreamResumableIterator.init(this); @@ -3284,8 +3205,7 @@ pub const H2FrameParser = struct { const args_list = callframe.arguments_old(5); if (args_list.len < 4) { - globalObject.throw("Expected stream_id, stream_ctx, headers and sensitiveHeaders arguments", .{}); - return .zero; + return globalObject.throw("Expected stream_id, stream_ctx, headers and sensitiveHeaders arguments", .{}); } const stream_id_arg = args_list.ptr[0]; @@ -3295,13 +3215,11 @@ pub const H2FrameParser = struct { const sensitive_arg = args_list.ptr[3]; if (!headers_arg.isObject()) { - globalObject.throw("Expected headers to be an object", .{}); - return .zero; + return globalObject.throw("Expected headers to be an object", .{}); } if (!sensitive_arg.isObject()) { - globalObject.throw("Expected sensitiveHeaders to be an object", .{}); - return .zero; + return globalObject.throw("Expected sensitiveHeaders to be an object", .{}); } // max frame size will be always at least 16384 var buffer = shared_request_buffer[0 .. shared_request_buffer.len - FrameHeader.byteSize - 5]; @@ -3353,14 +3271,14 @@ pub const H2FrameParser = struct { if (this.isServer) { if (!ValidPseudoHeaders.has(name)) { if (!globalObject.hasException()) { - globalObject.ERR_HTTP2_INVALID_PSEUDOHEADER("\"{s}\" is an invalid pseudoheader or is used incorrectly", .{name}).throw(); + return globalObject.ERR_HTTP2_INVALID_PSEUDOHEADER("\"{s}\" is an invalid pseudoheader or is used incorrectly", .{name}).throw(); } return .zero; } } else { if (!ValidRequestPseudoHeaders.has(name)) { if (!globalObject.hasException()) { - globalObject.ERR_HTTP2_INVALID_PSEUDOHEADER("\"{s}\" is an invalid pseudoheader or is used incorrectly", .{name}).throw(); + return globalObject.ERR_HTTP2_INVALID_PSEUDOHEADER("\"{s}\" is an invalid pseudoheader or is used incorrectly", .{name}).throw(); } return .zero; } @@ -3371,7 +3289,7 @@ pub const H2FrameParser = struct { const js_value: JSC.JSValue = try headers_arg.get(globalObject, name) orelse { if (!globalObject.hasException()) { - globalObject.ERR_HTTP2_INVALID_HEADER_VALUE("Invalid value for header \"{s}\"", .{name}).throw(); + return globalObject.ERR_HTTP2_INVALID_HEADER_VALUE("Invalid value for header \"{s}\"", .{name}).throw(); } return .zero; }; @@ -3383,7 +3301,7 @@ pub const H2FrameParser = struct { if (SingleValueHeaders.has(name) and value_iter.len > 1) { if (!globalObject.hasException()) { - globalObject.ERR_HTTP2_INVALID_HEADER_VALUE("Header field \"{s}\" must only have a single value", .{name}).throw(); + return globalObject.ERR_HTTP2_INVALID_HEADER_VALUE("Header field \"{s}\" must only have a single value", .{name}).throw(); } return .zero; } @@ -3391,14 +3309,14 @@ pub const H2FrameParser = struct { while (value_iter.next()) |item| { if (item.isEmptyOrUndefinedOrNull()) { if (!globalObject.hasException()) { - globalObject.ERR_HTTP2_INVALID_HEADER_VALUE("Invalid value for header \"{s}\"", .{name}).throw(); + return globalObject.ERR_HTTP2_INVALID_HEADER_VALUE("Invalid value for header \"{s}\"", .{name}).throw(); } return .zero; } const value_str = item.toStringOrNull(globalObject) orelse { if (!globalObject.hasException()) { - globalObject.ERR_HTTP2_INVALID_HEADER_VALUE("Invalid value for header \"{s}\"", .{name}).throw(); + return globalObject.ERR_HTTP2_INVALID_HEADER_VALUE("Invalid value for header \"{s}\"", .{name}).throw(); } return .zero; }; @@ -3426,7 +3344,7 @@ pub const H2FrameParser = struct { log("single header {s}", .{name}); const value_str = js_value.toStringOrNull(globalObject) orelse { if (!globalObject.hasException()) { - globalObject.ERR_HTTP2_INVALID_HEADER_VALUE("Invalid value for header \"{s}\"", .{name}).throw(); + return globalObject.ERR_HTTP2_INVALID_HEADER_VALUE("Invalid value for header \"{s}\"", .{name}).throw(); } return .zero; }; @@ -3631,8 +3549,7 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected 1 argument", .{}); - return .zero; + return globalObject.throw("Expected 1 argument", .{}); } const buffer = args_list.ptr[0]; buffer.ensureStillAlive(); @@ -3645,8 +3562,7 @@ pub const H2FrameParser = struct { } return .undefined; } - globalObject.throw("Expected data to be a Buffer or ArrayBuffer", .{}); - return .zero; + return globalObject.throw("Expected data to be a Buffer or ArrayBuffer", .{}); } pub fn onNativeRead(this: *H2FrameParser, data: []const u8) void { @@ -3673,8 +3589,7 @@ pub const H2FrameParser = struct { JSC.markBinding(@src()); const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - globalObject.throw("Expected socket argument", .{}); - return .zero; + return globalObject.throw("Expected socket argument", .{}); } const socket_js = args_list.ptr[0]; @@ -3724,7 +3639,7 @@ pub const H2FrameParser = struct { pub fn constructor(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*H2FrameParser { const args_list = callframe.arguments_old(1); if (args_list.len < 1) { - return globalObject.throw2("Expected 1 argument", .{}); + return globalObject.throw("Expected 1 argument", .{}); } const options = args_list.ptr[0]; @@ -3733,7 +3648,7 @@ pub const H2FrameParser = struct { } const context_obj = try options.get(globalObject, "context") orelse { - return globalObject.throw2("Expected \"context\" option", .{}); + return globalObject.throw("Expected \"context\" option", .{}); }; var handler_js = JSC.JSValue.zero; if (try options.get(globalObject, "handlers")) |handlers_| { diff --git a/src/bun.js/api/bun/socket.zig b/src/bun.js/api/bun/socket.zig index 7d1b2b79be04b0..e14405120bcde8 100644 --- a/src/bun.js/api/bun/socket.zig +++ b/src/bun.js/api/bun/socket.zig @@ -572,19 +572,16 @@ pub const Listener = struct { const args = callframe.arguments_old(1); if (args.len < 1 or (this.listener == .none and this.handlers.active_connections == 0)) { - globalObject.throw("Expected 1 argument", .{}); - return .zero; + return globalObject.throw("Expected 1 argument", .{}); } const opts = args.ptr[0]; if (opts.isEmptyOrUndefinedOrNull() or opts.isBoolean() or !opts.isObject()) { - globalObject.throwValue(JSC.toInvalidArguments("Expected options object", .{}, globalObject)); - return .zero; + return globalObject.throwValue(JSC.toInvalidArguments("Expected options object", .{}, globalObject)); } const socket_obj = try opts.get(globalObject, "socket") orelse { - globalObject.throw("Expected \"socket\" object", .{}); - return .zero; + return globalObject.throw("Expected \"socket\" object", .{}); }; const handlers = try Handlers.fromJS(globalObject, socket_obj); @@ -704,8 +701,7 @@ pub const Listener = struct { } } - globalObject.throwValue(err); - return .zero; + return globalObject.throwValue(err); }; if (ssl_enabled) { @@ -801,8 +797,7 @@ pub const Listener = struct { err.put(globalObject, ZigString.static("code"), ZigString.init(@tagName(str)).toJS(globalObject)); } } - globalObject.throwValue(err); - return .zero; + return globalObject.throwValue(err); }; var socket = Listener{ @@ -852,7 +847,7 @@ pub const Listener = struct { } pub fn constructor(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*Listener { - return globalObject.throw2("Cannot construct Listener", .{}); + return globalObject.throw("Cannot construct Listener", .{}); } pub fn onNamePipeCreated(comptime ssl: bool, listener: *Listener) *NewSocket(ssl) { @@ -1201,10 +1196,9 @@ pub const Listener = struct { .syscall = bun.String.static("connect"), .code = if (port == null) bun.String.static("ENOENT") else bun.String.static("ECONNREFUSED"), }; - globalObject.throwValue(err.toErrorInstance(globalObject)); handlers.unprotect(); connection.deinit(); - return .zero; + return globalObject.throwValue(err.toErrorInstance(globalObject)); }; if (ssl_enabled) { @@ -1456,7 +1450,7 @@ fn NewSocket(comptime ssl: bool) type { } pub fn constructor(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*This { - return globalObject.throw2("Cannot construct Socket", .{}); + return globalObject.throw("Cannot construct Socket", .{}); } pub fn resumeFromJS(this: *This, _: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSValue { @@ -2040,13 +2034,11 @@ fn NewSocket(comptime ssl: bool) type { const args = callframe.arguments_old(1); if (this.socket.isDetached()) return JSValue.jsUndefined(); if (args.len == 0) { - globalObject.throw("Expected 1 argument, got 0", .{}); - return .zero; + return globalObject.throw("Expected 1 argument, got 0", .{}); } const t = args.ptr[0].coerce(i32, globalObject); if (t < 0) { - globalObject.throw("Timeout must be a positive integer", .{}); - return .zero; + return globalObject.throw("Timeout must be a positive integer", .{}); } log("timeout({d})", .{t}); @@ -2322,8 +2314,7 @@ fn NewSocket(comptime ssl: bool) type { const length_value = args[2]; if (encoding_value != .undefined and (offset_value != .undefined or length_value != .undefined)) { - globalObject.throwTODO("Support encoding with offset and length altogether. Only either encoding or offset, length is supported, but not both combinations yet.") catch {}; - return .fail; + return globalObject.throwTODO("Support encoding with offset and length altogether. Only either encoding or offset, length is supported, but not both combinations yet.") catch .fail; } var stack_fallback = std.heap.stackFallback(16 * 1024, bun.default_allocator); @@ -2334,16 +2325,14 @@ fn NewSocket(comptime ssl: bool) type { return .fail; } orelse { if (!globalObject.hasException()) { - globalObject.throwInvalidArgumentTypeValue("data", "string, buffer, or blob", args[0]) catch {}; - return .fail; + return globalObject.throwInvalidArgumentTypeValue("data", "string, buffer, or blob", args[0]) catch .fail; } return .fail; }; defer buffer.deinit(); if (buffer == .blob and buffer.blob.needsToReadFile()) { - globalObject.throw("File blob not supported yet in this function.", .{}); - return .fail; + return globalObject.throw("File blob not supported yet in this function.", .{}) catch .fail; } const label = if (comptime is_end) "end" else "write"; @@ -2351,17 +2340,11 @@ fn NewSocket(comptime ssl: bool) type { const byte_offset: usize = brk: { if (offset_value.isUndefined()) break :brk 0; if (!offset_value.isAnyInt()) { - globalObject.throwInvalidArgumentType(comptime "Socket." ++ label, "byteOffset", "integer"); - return .fail; + return globalObject.throwInvalidArgumentType(comptime "Socket." ++ label, "byteOffset", "integer") catch .fail; } const i = offset_value.toInt64(); if (i < 0) { - globalObject.throwRangeError(i, .{ - .field_name = "byteOffset", - .min = 0, - .max = JSC.MAX_SAFE_INTEGER, - }); - return .fail; + return globalObject.throwRangeError(i, .{ .field_name = "byteOffset", .min = 0, .max = JSC.MAX_SAFE_INTEGER }) catch .fail; } break :brk @intCast(i); }; @@ -2369,19 +2352,13 @@ fn NewSocket(comptime ssl: bool) type { const byte_length: usize = brk: { if (length_value.isUndefined()) break :brk buffer.slice().len; if (!length_value.isAnyInt()) { - globalObject.throwInvalidArgumentType(comptime "Socket." ++ label, "byteLength", "integer"); - return .fail; + return globalObject.throwInvalidArgumentType(comptime "Socket." ++ label, "byteLength", "integer") catch .fail; } const l = length_value.toInt64(); if (l < 0) { - globalObject.throwRangeError(l, .{ - .field_name = "byteLength", - .min = 0, - .max = JSC.MAX_SAFE_INTEGER, - }); - return .fail; + return globalObject.throwRangeError(l, .{ .field_name = "byteLength", .min = 0, .max = JSC.MAX_SAFE_INTEGER }) catch .fail; } break :brk @intCast(l); }; @@ -2389,23 +2366,13 @@ fn NewSocket(comptime ssl: bool) type { var bytes = buffer.slice(); if (byte_offset > bytes.len) { - globalObject.throwRangeError(@as(i64, @intCast(byte_offset)), .{ - .field_name = "byteOffset", - .min = 0, - .max = @intCast(bytes.len), - }); - return .fail; + return globalObject.throwRangeError(@as(i64, @intCast(byte_offset)), .{ .field_name = "byteOffset", .min = 0, .max = @intCast(bytes.len) }) catch .fail; } bytes = bytes[byte_offset..]; if (byte_length > bytes.len) { - globalObject.throwRangeError(@as(i64, @intCast(byte_length)), .{ - .field_name = "byteLength", - .min = 0, - .max = @intCast(bytes.len), - }); - return .fail; + return globalObject.throwRangeError(@as(i64, @intCast(byte_length)), .{ .field_name = "byteLength", .min = 0, .max = @intCast(bytes.len) }) catch .fail; } bytes = bytes[0..byte_length]; @@ -2586,8 +2553,7 @@ fn NewSocket(comptime ssl: bool) type { const args = callframe.arguments_old(1); if (args.len < 1) { - globalObject.throw("Expected 1 argument", .{}); - return .zero; + return globalObject.throw("Expected 1 argument", .{}); } if (this.socket.isDetached()) { @@ -2596,13 +2562,11 @@ fn NewSocket(comptime ssl: bool) type { const opts = args.ptr[0]; if (opts.isEmptyOrUndefinedOrNull() or opts.isBoolean() or !opts.isObject()) { - globalObject.throw("Expected options object", .{}); - return .zero; + return globalObject.throw("Expected options object", .{}); } const socket_obj = try opts.get(globalObject, "socket") orelse { - globalObject.throw("Expected \"socket\" option", .{}); - return .zero; + return globalObject.throw("Expected \"socket\" option", .{}); }; const handlers = try Handlers.fromJS(globalObject, socket_obj); @@ -2643,14 +2607,12 @@ fn NewSocket(comptime ssl: bool) type { const args = callframe.arguments_old(2); if (args.len < 2) { - globalObject.throw("Expected requestCert and rejectUnauthorized arguments", .{}); - return .zero; + return globalObject.throw("Expected requestCert and rejectUnauthorized arguments", .{}); } const request_cert_js = args.ptr[0]; const reject_unauthorized_js = args.ptr[1]; if (!request_cert_js.isBoolean() or !reject_unauthorized_js.isBoolean()) { - globalObject.throw("Expected requestCert and rejectUnauthorized arguments to be boolean", .{}); - return .zero; + return globalObject.throw("Expected requestCert and rejectUnauthorized arguments to be boolean", .{}); } const request_cert = request_cert_js.toBoolean(); @@ -2681,8 +2643,7 @@ fn NewSocket(comptime ssl: bool) type { const ssl_ptr = this.socket.ssl() orelse return JSValue.jsUndefined(); BoringSSL.ERR_clear_error(); if (BoringSSL.SSL_renegotiate(ssl_ptr) != 1) { - globalObject.throwValue(getSSLException(globalObject, "SSL_renegotiate error")); - return .zero; + return globalObject.throwValue(getSSLException(globalObject, "SSL_renegotiate error")); } return JSValue.jsUndefined(); } @@ -2725,8 +2686,7 @@ fn NewSocket(comptime ssl: bool) type { const args = callframe.arguments_old(1); if (args.len < 1) { - globalObject.throw("Expected session to be a string, Buffer or TypedArray", .{}); - return .zero; + return globalObject.throw("Expected session to be a string, Buffer or TypedArray", .{}); } const session_arg = args.ptr[0]; @@ -2740,13 +2700,11 @@ fn NewSocket(comptime ssl: bool) type { var tmp = @as([*c]const u8, @ptrCast(session_slice.ptr)); const session = BoringSSL.d2i_SSL_SESSION(null, &tmp, @as(c_long, @intCast(session_slice.len))) orelse return JSValue.jsUndefined(); if (BoringSSL.SSL_set_session(ssl_ptr, session) != 1) { - globalObject.throwValue(getSSLException(globalObject, "SSL_set_session error")); - return .zero; + return globalObject.throwValue(getSSLException(globalObject, "SSL_set_session error")); } return JSValue.jsUndefined(); } else { - globalObject.throw("Expected session to be a string, Buffer or TypedArray", .{}); - return .zero; + return globalObject.throw("Expected session to be a string, Buffer or TypedArray", .{}); } } @@ -2823,25 +2781,21 @@ fn NewSocket(comptime ssl: bool) type { const args = callframe.arguments_old(3); if (args.len < 2) { - globalObject.throw("Expected length and label to be provided", .{}); - return .zero; + return globalObject.throw("Expected length and label to be provided", .{}); } const length_arg = args.ptr[0]; if (!length_arg.isNumber()) { - globalObject.throw("Expected length to be a number", .{}); - return .zero; + return globalObject.throw("Expected length to be a number", .{}); } const length = length_arg.coerceToInt64(globalObject); if (length < 0) { - globalObject.throw("Expected length to be a positive number", .{}); - return .zero; + return globalObject.throw("Expected length to be a positive number", .{}); } const label_arg = args.ptr[1]; if (!label_arg.isString()) { - globalObject.throw("Expected label to be a string", .{}); - return .zero; + return globalObject.throw("Expected label to be a string", .{}); } var label = try label_arg.toSliceOrNull(globalObject); @@ -2866,13 +2820,11 @@ fn NewSocket(comptime ssl: bool) type { const result = BoringSSL.SSL_export_keying_material(ssl_ptr, buffer_ptr, buffer_size, @as([*c]const u8, @ptrCast(label_slice.ptr)), label_slice.len, @as([*c]const u8, @ptrCast(context_slice.ptr)), context_slice.len, 1); if (result != 1) { - globalObject.throwValue(getSSLException(globalObject, "Failed to export keying material")); - return .zero; + return globalObject.throwValue(getSSLException(globalObject, "Failed to export keying material")); } return buffer; } else { - globalObject.throw("Expected context to be a string, Buffer or TypedArray", .{}); - return .zero; + return globalObject.throw("Expected context to be a string, Buffer or TypedArray", .{}); } } else { const buffer_size = @as(usize, @intCast(length)); @@ -2881,8 +2833,7 @@ fn NewSocket(comptime ssl: bool) type { const result = BoringSSL.SSL_export_keying_material(ssl_ptr, buffer_ptr, buffer_size, @as([*c]const u8, @ptrCast(label_slice.ptr)), label_slice.len, null, 0, 0); if (result != 1) { - globalObject.throwValue(getSSLException(globalObject, "Failed to export keying material")); - return .zero; + return globalObject.throwValue(getSSLException(globalObject, "Failed to export keying material")); } return buffer; } @@ -3174,23 +3125,19 @@ fn NewSocket(comptime ssl: bool) type { const args = callframe.arguments_old(1); if (args.len < 1) { - globalObject.throw("Expected size to be a number", .{}); - return .zero; + return globalObject.throw("Expected size to be a number", .{}); } const arg = args.ptr[0]; if (!arg.isNumber()) { - globalObject.throw("Expected size to be a number", .{}); - return .zero; + return globalObject.throw("Expected size to be a number", .{}); } const size = args.ptr[0].coerceToInt64(globalObject); if (size < 1) { - globalObject.throw("Expected size to be greater than 1", .{}); - return .zero; + return globalObject.throw("Expected size to be greater than 1", .{}); } if (size > 16384) { - globalObject.throw("Expected size to be less than 16385", .{}); - return .zero; + return globalObject.throw("Expected size to be less than 16385", .{}); } const ssl_ptr = this.socket.ssl() orelse return JSValue.jsBoolean(false); @@ -3211,8 +3158,7 @@ fn NewSocket(comptime ssl: bool) type { if (args.len > 0) { const arg = args.ptr[0]; if (!arg.isBoolean()) { - globalObject.throw("Expected abbreviated to be a boolean", .{}); - return .zero; + return globalObject.throw("Expected abbreviated to be a boolean", .{}); } abbreviated = arg.toBoolean(); } @@ -3290,20 +3236,17 @@ fn NewSocket(comptime ssl: bool) type { } if (this.handlers.is_server) { - globalObject.throw("Cannot issue SNI from a TLS server-side socket", .{}); - return .zero; + return globalObject.throw("Cannot issue SNI from a TLS server-side socket", .{}); } const args = callframe.arguments_old(1); if (args.len < 1) { - globalObject.throw("Expected 1 argument", .{}); - return .zero; + return globalObject.throw("Expected 1 argument", .{}); } const server_name = args.ptr[0]; if (!server_name.isString()) { - globalObject.throw("Expected \"serverName\" to be a string", .{}); - return .zero; + return globalObject.throw("Expected \"serverName\" to be a string", .{}); } const slice = server_name.getZigString(globalObject).toOwnedSlice(bun.default_allocator) catch bun.outOfMemory(); @@ -3320,8 +3263,7 @@ fn NewSocket(comptime ssl: bool) type { if (ssl_ptr.isInitFinished()) { // match node.js exceptions - globalObject.throw("Already started.", .{}); - return .zero; + return globalObject.throw("Already started.", .{}); } const host__ = default_allocator.dupeZ(u8, host) catch bun.outOfMemory(); defer default_allocator.free(host__); @@ -3351,21 +3293,18 @@ fn NewSocket(comptime ssl: bool) type { const args = callframe.arguments_old(1); if (args.len < 1) { - globalObject.throw("Expected 1 arguments", .{}); - return .zero; + return globalObject.throw("Expected 1 arguments", .{}); } var success = false; const opts = args.ptr[0]; if (opts.isEmptyOrUndefinedOrNull() or opts.isBoolean() or !opts.isObject()) { - globalObject.throw("Expected options object", .{}); - return .zero; + return globalObject.throw("Expected options object", .{}); } const socket_obj = try opts.get(globalObject, "socket") orelse { - globalObject.throw("Expected \"socket\" option", .{}); - return .zero; + return globalObject.throw("Expected \"socket\" option", .{}); }; if (globalObject.hasException()) { return .zero; @@ -3403,8 +3342,7 @@ fn NewSocket(comptime ssl: bool) type { } if (ssl_opts == null) { - globalObject.throw("Expected \"tls\" option", .{}); - return .zero; + return globalObject.throw("Expected \"tls\" option", .{}); } var default_data = JSValue.zero; @@ -3490,14 +3428,12 @@ fn NewSocket(comptime ssl: bool) type { // If BoringSSL gave us an error code, let's use it. if (err != 0 and !globalObject.hasException()) { - globalObject.throwValue(BoringSSL.ERR_toJS(globalObject, err)); - return .zero; + return globalObject.throwValue(BoringSSL.ERR_toJS(globalObject, err)); } // If BoringSSL did not give us an error code, let's throw a generic error. if (!globalObject.hasException()) { - globalObject.throw("Failed to upgrade socket from TCP -> TLS. Is the TLS config correct?", .{}); - return .zero; + return globalObject.throw("Failed to upgrade socket from TCP -> TLS. Is the TLS config correct?", .{}); } return JSValue.jsUndefined(); @@ -4248,7 +4184,7 @@ pub fn jsAddServerName(global: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b if (listener.as(Listener)) |this| { return this.addServerName(global, arguments.ptr[1], arguments.ptr[2]); } - return global.throw2("Expected a Listener instance", .{}); + return global.throw("Expected a Listener instance", .{}); } pub fn jsUpgradeDuplexToTLS(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSValue { @@ -4256,25 +4192,21 @@ pub fn jsUpgradeDuplexToTLS(globalObject: *JSC.JSGlobalObject, callframe: *JSC.C const args = callframe.arguments_old(2); if (args.len < 2) { - globalObject.throw("Expected 2 arguments", .{}); - return .zero; + return globalObject.throw("Expected 2 arguments", .{}); } const duplex = args.ptr[0]; // TODO: do better type checking if (duplex.isEmptyOrUndefinedOrNull()) { - globalObject.throw("Expected a Duplex instance", .{}); - return .zero; + return globalObject.throw("Expected a Duplex instance", .{}); } const opts = args.ptr[1]; if (opts.isEmptyOrUndefinedOrNull() or opts.isBoolean() or !opts.isObject()) { - globalObject.throw("Expected options object", .{}); - return .zero; + return globalObject.throw("Expected options object", .{}); } const socket_obj = try opts.get(globalObject, "socket") orelse { - globalObject.throw("Expected \"socket\" option", .{}); - return .zero; + return globalObject.throw("Expected \"socket\" option", .{}); }; var handlers = try Handlers.fromJS(globalObject, socket_obj); @@ -4292,8 +4224,7 @@ pub fn jsUpgradeDuplexToTLS(globalObject: *JSC.JSGlobalObject, callframe: *JSC.C } } if (ssl_opts == null) { - globalObject.throw("Expected \"tls\" option", .{}); - return .zero; + return globalObject.throw("Expected \"tls\" option", .{}); } var default_data = JSValue.zero; @@ -4389,16 +4320,14 @@ pub fn jsCreateSocketPair(global: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JS JSC.markBinding(@src()); if (Environment.isWindows) { - global.throw("Not implemented on Windows", .{}); - return .zero; + return global.throw("Not implemented on Windows", .{}); } var fds_: [2]std.c.fd_t = .{ 0, 0 }; const rc = std.c.socketpair(std.posix.AF.UNIX, std.posix.SOCK.STREAM, 0, &fds_); if (rc != 0) { const err = bun.sys.Error.fromCode(bun.C.getErrno(rc), .socketpair); - global.throwValue(err.toJSC(global)); - return .zero; + return global.throwValue(err.toJSC(global)); } const array = JSC.JSValue.createEmptyArray(global, 2); diff --git a/src/bun.js/api/bun/spawn/stdio.zig b/src/bun.js/api/bun/spawn/stdio.zig index d9197ba862025d..8a989d1ab0e35d 100644 --- a/src/bun.js/api/bun/spawn/stdio.zig +++ b/src/bun.js/api/bun/spawn/stdio.zig @@ -58,9 +58,8 @@ pub const Stdio = union(enum) { }; } - pub fn throwJS(this: *const @This(), globalThis: *JSC.JSGlobalObject) JSValue { - globalThis.throw("{s}", .{this.toStr()}); - return .zero; + pub fn throwJS(this: *const @This(), globalThis: *JSC.JSGlobalObject) bun.JSError { + return globalThis.throw("{s}", .{this.toStr()}); } }; diff --git a/src/bun.js/api/bun/subprocess.zig b/src/bun.js/api/bun/subprocess.zig index eb2444fcf147cb..4ceeb63779d20e 100644 --- a/src/bun.js/api/bun/subprocess.zig +++ b/src/bun.js/api/bun/subprocess.zig @@ -383,7 +383,7 @@ pub const Subprocess = struct { } pub fn constructor(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*Subprocess { - return globalObject.throw2("Cannot construct Subprocess", .{}); + return globalObject.throw("Cannot construct Subprocess", .{}); } const Readable = union(enum) { @@ -495,7 +495,7 @@ pub const Subprocess = struct { _ = exited; // autofix switch (this.*) { // should only be reachable when the entire output is buffered. - .memfd => return this.toBufferedValue(globalThis), + .memfd => return this.toBufferedValue(globalThis) catch .zero, .fd => |fd| { return fd.toJS(globalThis); @@ -521,7 +521,7 @@ pub const Subprocess = struct { } } - pub fn toBufferedValue(this: *Readable, globalThis: *JSC.JSGlobalObject) JSValue { + pub fn toBufferedValue(this: *Readable, globalThis: *JSC.JSGlobalObject) bun.JSError!JSValue { switch (this.*) { .fd => |fd| { return fd.toJS(globalThis); @@ -594,8 +594,7 @@ pub const Subprocess = struct { .result => {}, .err => |err| { // Signal 9 should always be fine, but just in case that somehow fails. - global.throwValue(err.toJSC(global)); - return .zero; + return global.throwValue(err.toJSC(global)); }, } @@ -652,8 +651,7 @@ pub const Subprocess = struct { .result => {}, .err => |err| { // EINVAL or ENOSYS means the signal is not supported in the current platform (most likely unsupported on windows) - globalThis.throwValue(err.toJSC(globalThis)); - return .zero; + return globalThis.throwValue(err.toJSC(globalThis)); }, } @@ -710,11 +708,10 @@ pub const Subprocess = struct { IPClog("Subprocess#doSend", .{}); const ipc_data = &(this.ipc_data orelse { if (this.hasExited()) { - global.throw("Subprocess.send() cannot be used after the process has exited.", .{}); + return global.throw("Subprocess.send() cannot be used after the process has exited.", .{}); } else { - global.throw("Subprocess.send() can only be used if an IPC channel is open.", .{}); + return global.throw("Subprocess.send() can only be used if an IPC channel is open.", .{}); } - return .zero; }); if (callFrame.argumentsCount() == 0) { @@ -1814,7 +1811,7 @@ pub const Subprocess = struct { }; } else { if (!globalThis.hasException()) { - globalThis.throwInvalidArgumentType("spawn", "serialization", "string"); + return globalThis.throwInvalidArgumentType("spawn", "serialization", "string"); } return .zero; } @@ -2058,8 +2055,7 @@ pub const Subprocess = struct { }) { .err => |err| { spawn_options.deinit(); - globalThis.throwValue(err.toJSC(globalThis)); - return .zero; + return globalThis.throwValue(err.toJSC(globalThis)); }, .result => |result| result, }; @@ -2174,8 +2170,7 @@ pub const Subprocess = struct { subprocess.stdio_pipes.items[@intCast(ipc_channel)].buffer, ).asErr()) |err| { subprocess.deref(); - globalThis.throwValue(err.toJSC(globalThis)); - return .zero; + return globalThis.throwValue(err.toJSC(globalThis)); } subprocess.stdio_pipes.items[@intCast(ipc_channel)] = .unavailable; } @@ -2296,8 +2291,8 @@ pub const Subprocess = struct { const signalCode = subprocess.getSignalCode(globalThis); const exitCode = subprocess.getExitCode(globalThis); - const stdout = subprocess.stdout.toBufferedValue(globalThis); - const stderr = subprocess.stderr.toBufferedValue(globalThis); + const stdout = try subprocess.stdout.toBufferedValue(globalThis); + const stderr = try subprocess.stderr.toBufferedValue(globalThis); const resource_usage: JSValue = if (!globalThis.hasException()) subprocess.createResourceUsageObject(globalThis) else .zero; subprocess.finalize(); diff --git a/src/bun.js/api/bun/udp_socket.zig b/src/bun.js/api/bun/udp_socket.zig index 6e330048a48e0d..14297ce810d18e 100644 --- a/src/bun.js/api/bun/udp_socket.zig +++ b/src/bun.js/api/bun/udp_socket.zig @@ -270,11 +270,6 @@ pub const UDPSocket = struct { pub usingnamespace JSC.Codegen.JSUDPSocket; - pub fn constructor(globalThis: *JSGlobalObject, _: *CallFrame) ?*This { - globalThis.throw("Cannot construct UDPSocket", .{}); - return null; - } - pub fn hasPendingActivity(this: *This) callconv(.C) bool { return this.js_refcount.load(.monotonic) > 0; } @@ -314,14 +309,14 @@ pub const UDPSocket = struct { )) |socket| { this.socket = socket; } else { - return globalThis.throw2("Failed to bind socket", .{}); + return globalThis.throw("Failed to bind socket", .{}); } if (config.connect) |connect| { const ret = this.socket.connect(connect.address, connect.port); if (ret != 0) { if (JSC.Maybe(void).errnoSys(ret, .connect)) |err| { - return globalThis.throwValue2(err.toJS(globalThis)); + return globalThis.throwValue(err.toJS(globalThis)); } } this.connect_info = .{ .port = connect.port }; @@ -357,8 +352,7 @@ pub const UDPSocket = struct { pub fn sendMany(this: *This, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { if (this.closed) { - globalThis.throw("Socket is closed", .{}); - return .zero; + return globalThis.throw("Socket is closed", .{}); } const arguments = callframe.arguments_old(1); if (arguments.len != 1) { @@ -367,8 +361,7 @@ pub const UDPSocket = struct { const arg = arguments.ptr[0]; if (!arg.jsType().isArray()) { - globalThis.throwInvalidArgumentType("sendMany", "first argument", "array"); - return .zero; + return globalThis.throwInvalidArgumentType("sendMany", "first argument", "array"); } const array_len = arg.getLength(globalThis); @@ -429,20 +422,14 @@ pub const UDPSocket = struct { } const res = this.socket.send(payloads, lens, addr_ptrs); if (bun.JSC.Maybe(void).errnoSys(res, .send)) |err| { - globalThis.throwValue(err.toJS(globalThis)); - return .zero; + return globalThis.throwValue(err.toJS(globalThis)); } return JSValue.jsNumber(res); } - pub fn send( - this: *This, - globalThis: *JSGlobalObject, - callframe: *CallFrame, - ) bun.JSError!JSValue { + pub fn send(this: *This, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { if (this.closed) { - globalThis.throw("Socket is closed", .{}); - return .zero; + return globalThis.throw("Socket is closed", .{}); } const arguments = callframe.arguments_old(3); const dst: ?Destination = brk: { @@ -493,8 +480,7 @@ pub const UDPSocket = struct { const res = this.socket.send(&.{payload.ptr}, &.{payload.len}, &.{addr_ptr}); if (bun.JSC.Maybe(void).errnoSys(res, .send)) |err| { - globalThis.throwValue(err.toJS(globalThis)); - return .zero; + return globalThis.throwValue(err.toJS(globalThis)); } return JSValue.jsBoolean(res > 0); } @@ -672,13 +658,11 @@ pub const UDPSocket = struct { }; if (this.connect_info != null) { - globalThis.throw("Socket is already connected", .{}); - return .zero; + return globalThis.throw("Socket is already connected", .{}); } if (this.closed) { - globalThis.throw("Socket is closed", .{}); - return .zero; + return globalThis.throw("Socket is closed", .{}); } if (args.len < 2) { @@ -700,8 +684,7 @@ pub const UDPSocket = struct { const port: u16 = if (connect_port < 1 or connect_port > 0xffff) 0 else @as(u16, @intCast(connect_port)); if (this.socket.connect(connect_host, port) == -1) { - globalThis.throw("Failed to connect socket", .{}); - return .zero; + return globalThis.throw("Failed to connect socket", .{}); } this.connect_info = .{ .port = port, @@ -717,18 +700,15 @@ pub const UDPSocket = struct { }; if (this.connect_info == null) { - globalObject.throw("Socket is not connected", .{}); - return .zero; + return globalObject.throw("Socket is not connected", .{}); } if (this.closed) { - globalObject.throw("Socket is closed", .{}); - return .zero; + return globalObject.throw("Socket is closed", .{}); } if (this.socket.disconnect() == -1) { - globalObject.throw("Failed to disconnect socket", .{}); - return .zero; + return globalObject.throw("Failed to disconnect socket", .{}); } this.connect_info = null; diff --git a/src/bun.js/api/bun/x509.zig b/src/bun.js/api/bun/x509.zig index 18575daf44477b..c3efe966696d4b 100644 --- a/src/bun.js/api/bun/x509.zig +++ b/src/bun.js/api/bun/x509.zig @@ -436,8 +436,7 @@ fn toUpper(slice: []u8) void { pub fn toJS(cert: *BoringSSL.X509, globalObject: *JSGlobalObject) bun.JSError!JSValue { const bio = BoringSSL.BIO_new(BoringSSL.BIO_s_mem()) orelse { - globalObject.throw("Failed to create BIO", .{}); - return .zero; + return globalObject.throw("Failed to create BIO", .{}); }; defer _ = BoringSSL.BIO_free(bio); var result = JSValue.createEmptyObject(globalObject, 8); @@ -485,8 +484,7 @@ pub fn toJS(cert: *BoringSSL.X509, globalObject: *JSGlobalObject) bun.JSError!JS const size = BoringSSL.i2d_RSA_PUBKEY(rsa, null); if (size <= 0) { - globalObject.throw("Failed to get public key length", .{}); - return .zero; + return globalObject.throw("Failed to get public key length", .{}); } var buffer = JSValue.createBufferFromLength(globalObject, @as(usize, @intCast(size))); @@ -515,8 +513,7 @@ pub fn toJS(cert: *BoringSSL.X509, globalObject: *JSGlobalObject) bun.JSError!JS const form = BoringSSL.EC_KEY_get_conv_form(ec); const size = BoringSSL.EC_POINT_point2oct(group, point, form, null, 0, null); if (size <= 0) { - globalObject.throw("Failed to get public key length", .{}); - return .zero; + return globalObject.throw("Failed to get public key length", .{}); } var buffer = JSValue.createBufferFromLength(globalObject, @as(usize, @intCast(size))); diff --git a/src/bun.js/api/ffi.zig b/src/bun.js/api/ffi.zig index 7ebc432d4108f7..9dfea02f948632 100644 --- a/src/bun.js/api/ffi.zig +++ b/src/bun.js/api/ffi.zig @@ -334,8 +334,7 @@ pub const FFI = struct { pub fn compile(this: *CompileC, globalThis: *JSGlobalObject) !struct { *TCC.TCCState, []u8 } { const state = TCC.tcc_new() orelse { - globalThis.throw("TinyCC failed to initialize", .{}); - return error.JSException; + return globalThis.throw("TinyCC failed to initialize", .{}); }; TCC.tcc_set_error_func(state, this, @ptrCast(&handleCompilationError)); if (this.flags.len > 0) { @@ -367,14 +366,12 @@ pub const FFI = struct { if (sdkroot.len > 0) { const include_dir = bun.path.joinAbsStringBufZ(sdkroot, &pathbuf, &.{ "usr", "include" }, .auto); if (TCC.tcc_add_sysinclude_path(state, include_dir.ptr) == -1) { - globalThis.throw("TinyCC failed to add sysinclude path", .{}); - return error.JSException; + return globalThis.throw("TinyCC failed to add sysinclude path", .{}); } const lib_dir = bun.path.joinAbsStringBufZ(sdkroot, &pathbuf, &.{ "usr", "lib" }, .auto); if (TCC.tcc_add_library_path(state, lib_dir.ptr) == -1) { - globalThis.throw("TinyCC failed to add library path", .{}); - return error.JSException; + return globalThis.throw("TinyCC failed to add library path", .{}); } break :add_system_include_dir; } @@ -464,9 +461,9 @@ pub const FFI = struct { return error.DeferredErrors; } else { if (!globalThis.hasException()) { - globalThis.throw("TinyCC failed to compile", .{}); + return globalThis.throw("TinyCC failed to compile", .{}); } - return error.JSException; + return error.JSError; } }; @@ -503,8 +500,7 @@ pub const FFI = struct { } if (relocation_size < 0) { - globalThis.throw("Unexpected: tcc_relocate returned a negative value", .{}); - return error.JSException; + return globalThis.throw("Unexpected: tcc_relocate returned a negative value", .{}); } const bytes: []u8 = try bun.default_allocator.alloc(u8, @as(usize, @intCast(relocation_size))); @@ -528,8 +524,7 @@ pub const FFI = struct { if (TCC.tcc_get_symbol(state, duped)) |function_ptr| { function.symbol_from_dynamic_library = function_ptr; } else { - globalThis.throw("{} is missing from {s}. Was it included in the source code?", .{ bun.fmt.quote(symbol), this.source.first() }); - return error.JSException; + return globalThis.throw("{} is missing from {s}. Was it included in the source code?", .{ bun.fmt.quote(symbol), this.source.first() }); } } @@ -655,13 +650,12 @@ pub const FFI = struct { if (try generateSymbols(globalThis, &compile_c.symbols.map, symbols_object)) |val| { if (val != .zero and !globalThis.hasException()) - globalThis.throwValue(val); + return globalThis.throwValue(val); return error.JSError; } if (compile_c.symbols.map.count() == 0) { - globalThis.throw("Expected at least one exported symbol", .{}); - return error.JSError; + return globalThis.throw("Expected at least one exported symbol", .{}); } if (object.getOwn(globalThis, "library")) |library_value| { @@ -782,12 +776,9 @@ pub const FFI = struct { writer.print("{s}\n", .{deferred_error}) catch bun.outOfMemory(); } - globalThis.throw("{s}", .{combined.items}); - return error.JSError; - }, - error.JSException => { - return error.JSError; + return globalThis.throw("{s}", .{combined.items}); }, + error.JSError => |e| return e, error.OutOfMemory => |e| return e, } }; @@ -811,20 +802,17 @@ pub const FFI = struct { @errorName(err), function_name, }, globalThis); - globalThis.throwValue(ret); + return globalThis.throwValue(ret); } - return error.JSError; }; switch (function.step) { .failed => |err| { const res = ZigString.init(err.msg).toErrorInstance(globalThis); - globalThis.throwValue(res); - return error.JSError; + return globalThis.throwValue(res); }, .pending => { - globalThis.throw("Failed to compile (nothing happend!)", .{}); - return error.JSError; + return globalThis.throw("Failed to compile (nothing happend!)", .{}); }, .compiled => |*compiled| { const str = ZigString.init(bun.asByteSlice(function_name)); diff --git a/src/bun.js/api/filesystem_router.zig b/src/bun.js/api/filesystem_router.zig index ee31d5cd756148..8738fbce700cef 100644 --- a/src/bun.js/api/filesystem_router.zig +++ b/src/bun.js/api/filesystem_router.zig @@ -140,12 +140,12 @@ pub const FileSystemRouter = struct { origin_str.deinit(); arena.deinit(); globalThis.allocator().destroy(arena); - return globalThis.throwValue2(log.toJS(globalThis, globalThis.allocator(), "reading root directory")); + return globalThis.throwValue(log.toJS(globalThis, globalThis.allocator(), "reading root directory")); } orelse { origin_str.deinit(); arena.deinit(); globalThis.allocator().destroy(arena); - return globalThis.throw2("Unable to find directory: {s}", .{root_dir_path.slice()}); + return globalThis.throw("Unable to find directory: {s}", .{root_dir_path.slice()}); }; var router = Router.init(vm.bundler.fs, allocator, .{ @@ -158,7 +158,7 @@ pub const FileSystemRouter = struct { origin_str.deinit(); arena.deinit(); globalThis.allocator().destroy(arena); - return globalThis.throwValue2(log.toJS(globalThis, globalThis.allocator(), "loading routes")); + return globalThis.throwValue(log.toJS(globalThis, globalThis.allocator(), "loading routes")); }; if (try argument.get(globalThis, "origin")) |origin| { @@ -174,7 +174,7 @@ pub const FileSystemRouter = struct { origin_str.deinit(); arena.deinit(); globalThis.allocator().destroy(arena); - return globalThis.throwValue2(log.toJS(globalThis, globalThis.allocator(), "loading routes")); + return globalThis.throwValue(log.toJS(globalThis, globalThis.allocator(), "loading routes")); } var fs_router = globalThis.allocator().create(FileSystemRouter) catch unreachable; @@ -257,13 +257,11 @@ pub const FileSystemRouter = struct { bustDirCache(this, globalThis); const root_dir_info = vm.bundler.resolver.readDirInfo(this.router.config.dir) catch { - globalThis.throwValue(log.toJS(globalThis, globalThis.allocator(), "reading root directory")); - return .zero; + return globalThis.throwValue(log.toJS(globalThis, globalThis.allocator(), "reading root directory")); } orelse { - globalThis.throw("Unable to find directory: {s}", .{this.router.config.dir}); arena.deinit(); globalThis.allocator().destroy(arena); - return .zero; + return globalThis.throw("Unable to find directory: {s}", .{this.router.config.dir}); }; var router = Router.init(vm.bundler.fs, allocator, .{ @@ -272,11 +270,9 @@ pub const FileSystemRouter = struct { .asset_prefix_path = this.router.config.asset_prefix_path, }) catch unreachable; router.loadRoutes(&log, root_dir_info, Resolver, &vm.bundler.resolver, router.config.dir) catch { - globalThis.throwValue(log.toJS(globalThis, globalThis.allocator(), "loading routes")); - arena.deinit(); globalThis.allocator().destroy(arena); - return .zero; + return globalThis.throwValue(log.toJS(globalThis, globalThis.allocator(), "loading routes")); }; this.arena.deinit(); @@ -331,8 +327,7 @@ pub const FileSystemRouter = struct { } const url_path = URLPath.parse(path.slice()) catch |err| { - globalThis.throw("{s} parsing path: {s}", .{ @errorName(err), path.slice() }); - return .zero; + return globalThis.throw("{s} parsing path: {s}", .{ @errorName(err), path.slice() }); }; var params = Router.Param.List{}; defer params.deinit(globalThis.allocator()); diff --git a/src/bun.js/api/glob.zig b/src/bun.js/api/glob.zig index b7e9ce6aaffed9..85051929db4d1c 100644 --- a/src/bun.js/api/glob.zig +++ b/src/bun.js/api/glob.zig @@ -63,7 +63,7 @@ const ScanOpts = struct { .result => |cwd| cwd, .err => |err| { const errJs = err.toJSC(globalThis); - return globalThis.throwValue2(errJs); + return globalThis.throwValue(errJs); }, }; @@ -76,7 +76,7 @@ const ScanOpts = struct { }; if (cwd_str.len > bun.MAX_PATH_BYTES) { - return globalThis.throw2("{s}: invalid `cwd`, longer than {d} bytes", .{ fnName, bun.MAX_PATH_BYTES }); + return globalThis.throw("{s}: invalid `cwd`, longer than {d} bytes", .{ fnName, bun.MAX_PATH_BYTES }); } return cwd_str; @@ -103,8 +103,7 @@ const ScanOpts = struct { } return out; } - globalThis.throw("{s}: expected first argument to be an object", .{fnName}); - return error.JSError; + return globalThis.throw("{s}: expected first argument to be an object", .{fnName}); } if (try optsObj.getTruthy(globalThis, "onlyFiles")) |only_files| { @@ -125,8 +124,7 @@ const ScanOpts = struct { if (try optsObj.getTruthy(globalThis, "cwd")) |cwdVal| { if (!cwdVal.isString()) { - globalThis.throw("{s}: invalid `cwd`, not a string", .{fnName}); - return error.JSError; + return globalThis.throw("{s}: invalid `cwd`, not a string", .{fnName}); } { @@ -258,7 +256,7 @@ fn makeGlobWalker( only_files, )) { .err => |err| { - return globalThis.throwValue2(err.toJSC(globalThis)); + return globalThis.throwValue(err.toJSC(globalThis)); }, else => {}, } @@ -275,7 +273,7 @@ fn makeGlobWalker( only_files, )) { .err => |err| { - return globalThis.throwValue2(err.toJSC(globalThis)); + return globalThis.throwValue(err.toJSC(globalThis)); }, else => {}, } @@ -289,11 +287,11 @@ pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); defer arguments.deinit(); const pat_arg: JSValue = arguments.nextEat() orelse { - return globalThis.throw2("Glob.constructor: expected 1 arguments, got 0", .{}); + return globalThis.throw("Glob.constructor: expected 1 arguments, got 0", .{}); }; if (!pat_arg.isString()) { - return globalThis.throw2("Glob.constructor: first argument is not a string", .{}); + return globalThis.throw("Glob.constructor: first argument is not a string", .{}); } const pat_str: []u8 = @constCast((pat_arg.toSliceClone(globalThis) orelse return error.JSError).slice()); @@ -380,7 +378,7 @@ pub fn __scanSync(this: *Glob, globalThis: *JSGlobalObject, callframe: *JSC.Call switch (try globWalker.walk()) { .err => |err| { - return globalThis.throwValue2(err.toJSC(globalThis)); + return globalThis.throwValue(err.toJSC(globalThis)); }, .result => {}, } @@ -399,13 +397,11 @@ pub fn match(this: *Glob, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); defer arguments.deinit(); const str_arg = arguments.nextEat() orelse { - globalThis.throw("Glob.matchString: expected 1 arguments, got 0", .{}); - return .zero; + return globalThis.throw("Glob.matchString: expected 1 arguments, got 0", .{}); }; if (!str_arg.isString()) { - globalThis.throw("Glob.matchString: first argument is not a string", .{}); - return .zero; + return globalThis.throw("Glob.matchString: first argument is not a string", .{}); } var str = str_arg.toSlice(globalThis, arena.allocator()); diff --git a/src/bun.js/api/html_rewriter.zig b/src/bun.js/api/html_rewriter.zig index ef03999d237573..bab7ac3e5aec19 100644 --- a/src/bun.js/api/html_rewriter.zig +++ b/src/bun.js/api/html_rewriter.zig @@ -178,8 +178,7 @@ pub const HTMLRewriter = struct { if (out != .zero) { if (out.toError()) |err| { - global.throwValue(err); - return .zero; + return global.throwValue(err); } } @@ -1288,7 +1287,7 @@ pub const Comment = struct { var text = value.toSlice(global, bun.default_allocator); defer text.deinit(); this.comment.?.setText(text.slice()) catch { - global.throwValue(throwLOLHTMLError(global)); + global.throwValue(throwLOLHTMLError(global)) catch {}; return false; }; @@ -1412,7 +1411,7 @@ pub const EndTag = struct { var text = value.toSlice(global, bun.default_allocator); defer text.deinit(); this.end_tag.?.setName(text.slice()) catch { - global.throwValue(throwLOLHTMLError(global)); + global.throwValue(throwLOLHTMLError(global)) catch {}; return false; }; @@ -1697,7 +1696,7 @@ pub const Element = struct { defer text.deinit(); this.element.?.setTagName(text.slice()) catch { - global.throwValue(throwLOLHTMLError(global)); + global.throwValue(throwLOLHTMLError(global)) catch {}; return false; }; diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index 6ab994b9061f23..e242d90cafa029 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -101,8 +101,7 @@ const BlobFileContentResult = struct { const read = fs.readFileWithOptions(.{ .path = body.Blob.store.?.data.file.pathlike }, .sync, .null_terminated); switch (read) { .err => { - global.throwValue(read.err.toJSC(global)); - return error.JSError; + return global.throwValue(read.err.toJSC(global)); }, else => { const str = read.result.null_terminated; @@ -971,7 +970,7 @@ pub const ServerConfig = struct { result.request_cert = if (request_cert.asBoolean()) 1 else 0; any = true; } else { - return global.throw2("Expected requestCert to be a boolean", .{}); + return global.throw("Expected requestCert to be a boolean", .{}); } } @@ -980,7 +979,7 @@ pub const ServerConfig = struct { result.reject_unauthorized = if (reject_unauthorized.asBoolean()) 1 else 0; any = true; } else { - return global.throw2("Expected rejectUnauthorized to be a boolean", .{}); + return global.throw("Expected rejectUnauthorized to be a boolean", .{}); } } @@ -1137,7 +1136,7 @@ pub const ServerConfig = struct { result.low_memory_mode = low_memory_mode.toBoolean(); any = true; } else { - return global.throw2("Expected lowMemoryMode to be a boolean", .{}); + return global.throw("Expected lowMemoryMode to be a boolean", .{}); } } } @@ -4747,7 +4746,7 @@ pub const ServerWebSocket = struct { } pub fn constructor(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*ServerWebSocket { - return globalObject.throw2("Cannot construct ServerWebSocket", .{}); + return globalObject.throw("Cannot construct ServerWebSocket", .{}); } pub fn finalize(this: *ServerWebSocket) void { @@ -4763,8 +4762,7 @@ pub const ServerWebSocket = struct { const args = callframe.arguments_old(4); if (args.len < 1) { log("publish()", .{}); - globalThis.throw("publish requires at least 1 argument", .{}); - return .zero; + return globalThis.throw("publish requires at least 1 argument", .{}); } const app = this.handler.app orelse { @@ -4781,27 +4779,23 @@ pub const ServerWebSocket = struct { if (topic_value.isEmptyOrUndefinedOrNull() or !topic_value.isString()) { log("publish() topic invalid", .{}); - globalThis.throw("publish requires a topic string", .{}); - return .zero; + return globalThis.throw("publish requires a topic string", .{}); } var topic_slice = topic_value.toSlice(globalThis, bun.default_allocator); defer topic_slice.deinit(); if (topic_slice.len == 0) { - globalThis.throw("publish requires a non-empty topic", .{}); - return .zero; + return globalThis.throw("publish requires a non-empty topic", .{}); } if (!compress_value.isBoolean() and !compress_value.isUndefined() and compress_value != .zero) { - globalThis.throw("publish expects compress to be a boolean", .{}); - return .zero; + return globalThis.throw("publish expects compress to be a boolean", .{}); } const compress = args.len > 1 and compress_value.toBoolean(); if (message_value.isEmptyOrUndefinedOrNull()) { - globalThis.throw("publish requires a non-empty message", .{}); - return .zero; + return globalThis.throw("publish requires a non-empty message", .{}); } if (message_value.asArrayBuffer(globalThis)) |array_buffer| { @@ -4849,8 +4843,7 @@ pub const ServerWebSocket = struct { if (args.len < 1) { log("publish()", .{}); - globalThis.throw("publish requires at least 1 argument", .{}); - return .zero; + return globalThis.throw("publish requires at least 1 argument", .{}); } const app = this.handler.app orelse { @@ -4867,23 +4860,20 @@ pub const ServerWebSocket = struct { if (topic_value.isEmptyOrUndefinedOrNull() or !topic_value.isString()) { log("publish() topic invalid", .{}); - globalThis.throw("publishText requires a topic string", .{}); - return .zero; + return globalThis.throw("publishText requires a topic string", .{}); } var topic_slice = topic_value.toSlice(globalThis, bun.default_allocator); defer topic_slice.deinit(); if (!compress_value.isBoolean() and !compress_value.isUndefined() and compress_value != .zero) { - globalThis.throw("publishText expects compress to be a boolean", .{}); - return .zero; + return globalThis.throw("publishText expects compress to be a boolean", .{}); } const compress = args.len > 1 and compress_value.toBoolean(); if (message_value.isEmptyOrUndefinedOrNull() or !message_value.isString()) { - globalThis.throw("publishText requires a non-empty message", .{}); - return .zero; + return globalThis.throw("publishText requires a non-empty message", .{}); } var string_slice = message_value.toSlice(globalThis, bun.default_allocator); @@ -4912,8 +4902,7 @@ pub const ServerWebSocket = struct { if (args.len < 1) { log("publishBinary()", .{}); - globalThis.throw("publishBinary requires at least 1 argument", .{}); - return .zero; + return globalThis.throw("publishBinary requires at least 1 argument", .{}); } const app = this.handler.app orelse { @@ -4929,32 +4918,27 @@ pub const ServerWebSocket = struct { if (topic_value.isEmptyOrUndefinedOrNull() or !topic_value.isString()) { log("publishBinary() topic invalid", .{}); - globalThis.throw("publishBinary requires a topic string", .{}); - return .zero; + return globalThis.throw("publishBinary requires a topic string", .{}); } var topic_slice = topic_value.toSlice(globalThis, bun.default_allocator); defer topic_slice.deinit(); if (topic_slice.len == 0) { - globalThis.throw("publishBinary requires a non-empty topic", .{}); - return .zero; + return globalThis.throw("publishBinary requires a non-empty topic", .{}); } if (!compress_value.isBoolean() and !compress_value.isUndefined() and compress_value != .zero) { - globalThis.throw("publishBinary expects compress to be a boolean", .{}); - return .zero; + return globalThis.throw("publishBinary expects compress to be a boolean", .{}); } const compress = args.len > 1 and compress_value.toBoolean(); if (message_value.isEmptyOrUndefinedOrNull()) { - globalThis.throw("publishBinary requires a non-empty message", .{}); - return .zero; + return globalThis.throw("publishBinary requires a non-empty message", .{}); } const array_buffer = message_value.asArrayBuffer(globalThis) orelse { - globalThis.throw("publishBinary expects an ArrayBufferView", .{}); - return .zero; + return globalThis.throw("publishBinary expects an ArrayBufferView", .{}); }; const buffer = array_buffer.slice(); @@ -4987,8 +4971,7 @@ pub const ServerWebSocket = struct { var topic_slice = topic_str.toSlice(globalThis, bun.default_allocator); defer topic_slice.deinit(); if (topic_slice.len == 0) { - globalThis.throw("publishBinary requires a non-empty topic", .{}); - return .zero; + return globalThis.throw("publishBinary requires a non-empty topic", .{}); } const compress = true; @@ -5027,8 +5010,7 @@ pub const ServerWebSocket = struct { var topic_slice = topic_str.toSlice(globalThis, bun.default_allocator); defer topic_slice.deinit(); if (topic_slice.len == 0) { - globalThis.throw("publishBinary requires a non-empty topic", .{}); - return .zero; + return globalThis.throw("publishBinary requires a non-empty topic", .{}); } const compress = true; @@ -5087,8 +5069,7 @@ pub const ServerWebSocket = struct { const result = corker.result; if (result.isAnyError()) { - globalThis.throwValue(result); - return .zero; + return globalThis.throwValue(result); } return result; @@ -5103,8 +5084,7 @@ pub const ServerWebSocket = struct { if (args.len < 1) { log("send()", .{}); - globalThis.throw("send requires at least 1 argument", .{}); - return .zero; + return globalThis.throw("send requires at least 1 argument", .{}); } if (this.isClosed()) { @@ -5116,15 +5096,13 @@ pub const ServerWebSocket = struct { const compress_value = args.ptr[1]; if (!compress_value.isBoolean() and !compress_value.isUndefined() and compress_value != .zero) { - globalThis.throw("send expects compress to be a boolean", .{}); - return .zero; + return globalThis.throw("send expects compress to be a boolean", .{}); } const compress = args.len > 1 and compress_value.toBoolean(); if (message_value.isEmptyOrUndefinedOrNull()) { - globalThis.throw("send requires a non-empty message", .{}); - return .zero; + return globalThis.throw("send requires a non-empty message", .{}); } if (message_value.asArrayBuffer(globalThis)) |buffer| { @@ -5177,8 +5155,7 @@ pub const ServerWebSocket = struct { if (args.len < 1) { log("sendText()", .{}); - globalThis.throw("sendText requires at least 1 argument", .{}); - return .zero; + return globalThis.throw("sendText requires at least 1 argument", .{}); } if (this.isClosed()) { @@ -5190,15 +5167,13 @@ pub const ServerWebSocket = struct { const compress_value = args.ptr[1]; if (!compress_value.isBoolean() and !compress_value.isUndefined() and compress_value != .zero) { - globalThis.throw("sendText expects compress to be a boolean", .{}); - return .zero; + return globalThis.throw("sendText expects compress to be a boolean", .{}); } const compress = args.len > 1 and compress_value.toBoolean(); if (message_value.isEmptyOrUndefinedOrNull() or !message_value.isString()) { - globalThis.throw("sendText expects a string", .{}); - return .zero; + return globalThis.throw("sendText expects a string", .{}); } var string_slice = message_value.toSlice(globalThis, bun.default_allocator); @@ -5261,8 +5236,7 @@ pub const ServerWebSocket = struct { if (args.len < 1) { log("sendBinary()", .{}); - globalThis.throw("sendBinary requires at least 1 argument", .{}); - return .zero; + return globalThis.throw("sendBinary requires at least 1 argument", .{}); } if (this.isClosed()) { @@ -5274,15 +5248,13 @@ pub const ServerWebSocket = struct { const compress_value = args.ptr[1]; if (!compress_value.isBoolean() and !compress_value.isUndefined() and compress_value != .zero) { - globalThis.throw("sendBinary expects compress to be a boolean", .{}); - return .zero; + return globalThis.throw("sendBinary expects compress to be a boolean", .{}); } const compress = args.len > 1 and compress_value.toBoolean(); const buffer = message_value.asArrayBuffer(globalThis) orelse { - globalThis.throw("sendBinary requires an ArrayBufferView", .{}); - return .zero; + return globalThis.throw("sendBinary requires an ArrayBufferView", .{}); }; switch (this.websocket().send(buffer.slice(), .binary, compress, true)) { @@ -5530,11 +5502,7 @@ pub const ServerWebSocket = struct { }; } - pub fn setBinaryType( - this: *ServerWebSocket, - globalThis: *JSC.JSGlobalObject, - value: JSC.JSValue, - ) callconv(.C) bool { + pub fn setBinaryType(this: *ServerWebSocket, globalThis: *JSC.JSGlobalObject, value: JSC.JSValue) callconv(.C) bool { log("setBinaryType()", .{}); const btype = JSC.BinaryType.fromJSValue(globalThis, value) catch return false; @@ -5546,7 +5514,7 @@ pub const ServerWebSocket = struct { return true; }, else => { - globalThis.throw("binaryType must be either \"uint8array\" or \"arraybuffer\" or \"nodebuffer\"", .{}); + globalThis.throw("binaryType must be either \"uint8array\" or \"arraybuffer\" or \"nodebuffer\"", .{}) catch {}; return false; }, } @@ -5572,8 +5540,7 @@ pub const ServerWebSocket = struct { ) bun.JSError!JSValue { const args = callframe.arguments_old(1); if (args.len < 1) { - globalThis.throw("subscribe requires at least 1 argument", .{}); - return .zero; + return globalThis.throw("subscribe requires at least 1 argument", .{}); } if (this.isClosed()) { @@ -5596,8 +5563,7 @@ pub const ServerWebSocket = struct { } if (topic.len == 0) { - globalThis.throw("subscribe requires a non-empty topic name", .{}); - return .zero; + return globalThis.throw("subscribe requires a non-empty topic name", .{}); } return JSValue.jsBoolean(this.websocket().subscribe(topic.slice())); @@ -5609,8 +5575,7 @@ pub const ServerWebSocket = struct { ) bun.JSError!JSValue { const args = callframe.arguments_old(1); if (args.len < 1) { - globalThis.throw("unsubscribe requires at least 1 argument", .{}); - return .zero; + return globalThis.throw("unsubscribe requires at least 1 argument", .{}); } if (this.isClosed()) { @@ -5633,8 +5598,7 @@ pub const ServerWebSocket = struct { } if (topic.len == 0) { - globalThis.throw("unsubscribe requires a non-empty topic name", .{}); - return .zero; + return globalThis.throw("unsubscribe requires a non-empty topic name", .{}); } return JSValue.jsBoolean(this.websocket().unsubscribe(topic.slice())); @@ -5646,8 +5610,7 @@ pub const ServerWebSocket = struct { ) bun.JSError!JSValue { const args = callframe.arguments_old(1); if (args.len < 1) { - globalThis.throw("isSubscribed requires at least 1 argument", .{}); - return .zero; + return globalThis.throw("isSubscribed requires at least 1 argument", .{}); } if (this.isClosed()) { @@ -5670,8 +5633,7 @@ pub const ServerWebSocket = struct { } if (topic.len == 0) { - globalThis.throw("isSubscribed requires a non-empty topic name", .{}); - return .zero; + return globalThis.throw("isSubscribed requires a non-empty topic name", .{}); } return JSValue.jsBoolean(this.websocket().isSubscribed(topic.slice())); @@ -5797,10 +5759,9 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp JSValue.jsNull(); } - pub fn timeout(this: *ThisServer, request: *JSC.WebCore.Request, seconds: JSValue) JSC.JSValue { + pub fn timeout(this: *ThisServer, request: *JSC.WebCore.Request, seconds: JSValue) bun.JSError!JSC.JSValue { if (!seconds.isNumber()) { - this.globalThis.throw("timeout() requires a number", .{}); - return .zero; + return this.globalThis.throw("timeout() requires a number", .{}); } const value = seconds.to(c_uint); _ = request.request_context.setTimeout(value); @@ -5811,7 +5772,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp this.config.idleTimeout = @truncate(@min(seconds, 255)); } - pub fn publish(this: *ThisServer, globalThis: *JSC.JSGlobalObject, topic: ZigString, message_value: JSValue, compress_value: ?JSValue) JSValue { + pub fn publish(this: *ThisServer, globalThis: *JSC.JSGlobalObject, topic: ZigString, message_value: JSValue, compress_value: ?JSValue) bun.JSError!JSValue { if (this.config.websocket == null) return JSValue.jsNumber(0); @@ -5819,15 +5780,13 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp if (topic.len == 0) { httplog("publish() topic invalid", .{}); - globalThis.throw("publish requires a topic string", .{}); - return .zero; + return globalThis.throw("publish requires a topic string", .{}); } var topic_slice = topic.toSlice(bun.default_allocator); defer topic_slice.deinit(); if (topic_slice.len == 0) { - globalThis.throw("publish requires a non-empty topic", .{}); - return .zero; + return globalThis.throw("publish requires a non-empty topic", .{}); } const compress = (compress_value orelse JSValue.jsBoolean(true)).toBoolean(); @@ -6669,7 +6628,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp } error_instance.ensureStillAlive(); - globalThis.throwValue(error_instance); + globalThis.throwValue(error_instance) catch {}; } pub fn onListen(this: *ThisServer, socket: ?*App.ListenSocket) void { @@ -7129,7 +7088,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp app = App.create(ssl_options) orelse { if (!globalThis.hasException()) { if (!throwSSLErrorIfNecessary(globalThis)) { - globalThis.throw("Failed to create HTTP server", .{}); + globalThis.throw("Failed to create HTTP server", .{}) catch {}; } } @@ -7149,7 +7108,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp app.addServerNameWithOptions(server_name, ssl_options) catch { if (!globalThis.hasException()) { if (!throwSSLErrorIfNecessary(globalThis)) { - globalThis.throw("Failed to add serverName: {s}", .{server_name}); + globalThis.throw("Failed to add serverName: {s}", .{server_name}) catch {}; } } @@ -7180,7 +7139,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp app.addServerNameWithOptions(sni_servername, sni_ssl_config.asUSockets()) catch { if (!globalThis.hasException()) { if (!throwSSLErrorIfNecessary(globalThis)) { - globalThis.throw("Failed to add serverName: {s}", .{sni_servername}); + globalThis.throw("Failed to add serverName: {s}", .{sni_servername}) catch {}; } } @@ -7203,7 +7162,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp } else { app = App.create(.{}) orelse { if (!globalThis.hasException()) { - globalThis.throw("Failed to create HTTP server", .{}); + globalThis.throw("Failed to create HTTP server", .{}) catch {}; } this.deinit(); return; @@ -7386,19 +7345,16 @@ extern fn Bun__addInspector(bool, *anyopaque, *JSC.JSGlobalObject) void; const assert = bun.assert; -pub export fn Server__setIdleTimeout( - server: JSC.JSValue, - seconds: JSC.JSValue, - globalThis: *JSC.JSGlobalObject, -) void { +pub export fn Server__setIdleTimeout(server: JSC.JSValue, seconds: JSC.JSValue, globalThis: *JSC.JSGlobalObject) void { + Server__setIdleTimeout_(server, seconds, globalThis) catch return; +} +pub fn Server__setIdleTimeout_(server: JSC.JSValue, seconds: JSC.JSValue, globalThis: *JSC.JSGlobalObject) bun.JSError!void { if (!server.isObject()) { - globalThis.throw("Failed to set timeout: The 'this' value is not a Server.", .{}); - return; + return globalThis.throw("Failed to set timeout: The 'this' value is not a Server.", .{}); } if (!seconds.isNumber()) { - globalThis.throw("Failed to set timeout: The provided value is not of type 'number'.", .{}); - return; + return globalThis.throw("Failed to set timeout: The provided value is not of type 'number'.", .{}); } const value = seconds.to(c_uint); if (server.as(HTTPServer)) |this| { @@ -7410,7 +7366,7 @@ pub export fn Server__setIdleTimeout( } else if (server.as(DebugHTTPSServer)) |this| { this.setIdleTimeout(value); } else { - globalThis.throw("Failed to set timeout: The 'this' value is not a Server.", .{}); + return globalThis.throw("Failed to set timeout: The 'this' value is not a Server.", .{}); } } @@ -7424,7 +7380,7 @@ fn throwSSLErrorIfNecessary(globalThis: *JSC.JSGlobalObject) bool { const err_code = BoringSSL.ERR_get_error(); if (err_code != 0) { defer BoringSSL.ERR_clear_error(); - globalThis.throwValue(JSC.API.Bun.Crypto.createCryptoError(globalThis, err_code)); + globalThis.throwValue(JSC.API.Bun.Crypto.createCryptoError(globalThis, err_code)) catch {}; return true; } diff --git a/src/bun.js/base.zig b/src/bun.js/base.zig index c8bf5f4ea21e95..3c010ea1b47a58 100644 --- a/src/bun.js/base.zig +++ b/src/bun.js/base.zig @@ -279,8 +279,7 @@ pub const ArrayBuffer = extern struct { } }, .err => |err| { - globalObject.throwValue(err.toJSC(globalObject)); - return .zero; + return globalObject.throwValue(err.toJSC(globalObject)) catch .zero; }, } } @@ -293,12 +292,11 @@ pub const ArrayBuffer = extern struct { extern fn ArrayBuffer__fromSharedMemfd(fd: i64, globalObject: *JSC.JSGlobalObject, byte_offset: usize, byte_length: usize, total_size: usize, JSC.JSValue.JSType) JSC.JSValue; pub const toArrayBufferFromSharedMemfd = ArrayBuffer__fromSharedMemfd; - pub fn toJSBufferFromMemfd(fd: bun.FileDescriptor, globalObject: *JSC.JSGlobalObject) JSC.JSValue { + pub fn toJSBufferFromMemfd(fd: bun.FileDescriptor, globalObject: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { const stat = switch (bun.sys.fstat(fd)) { .err => |err| { - globalObject.throwValue(err.toJSC(globalObject)); _ = bun.sys.close(fd); - return .zero; + return globalObject.throwValue(err.toJSC(globalObject)); }, .result => |fstat| fstat, }; @@ -335,9 +333,7 @@ pub const ArrayBuffer = extern struct { return JSBuffer__fromMmap(globalObject, buf.ptr, buf.len); }, .err => |err| { - globalObject.throwValue(err.toJSC(globalObject)); - - return .zero; + return globalObject.throwValue(err.toJSC(globalObject)); }, } } @@ -678,8 +674,7 @@ pub const MarkedArrayBuffer = struct { const obj = this.toJSObjectRef(globalObject, &exception); if (exception[0] != null) { - globalObject.throwValue(JSC.JSValue.c(exception[0])); - return .zero; + return globalObject.throwValue(JSC.JSValue.c(exception[0])) catch return .zero; } return JSC.JSValue.c(obj); diff --git a/src/bun.js/bindings/bindings.zig b/src/bun.js/bindings/bindings.zig index 9a0603b5a6015a..6c9ea21c053ec8 100644 --- a/src/bun.js/bindings/bindings.zig +++ b/src/bun.js/bindings/bindings.zig @@ -736,7 +736,7 @@ pub const ZigString = extern struct { pub fn toExternalU16(ptr: [*]const u16, len: usize, global: *JSGlobalObject) JSValue { if (len > String.max_length()) { bun.default_allocator.free(ptr[0..len]); - global.ERR_STRING_TOO_LONG("Cannot create a string longer than 2^32-1 characters", .{}).throw(); + global.ERR_STRING_TOO_LONG("Cannot create a string longer than 2^32-1 characters", .{}).throw() catch {}; // TODO: propagate? return .zero; } return shim.cppFn("toExternalU16", .{ ptr, len, global }); @@ -922,7 +922,7 @@ pub const ZigString = extern struct { this.assertGlobal(); if (this.len > String.max_length()) { bun.default_allocator.free(@constCast(this.byteSlice())); - global.ERR_STRING_TOO_LONG("Cannot create a string longer than 2^32-1 characters", .{}).throw(); + global.ERR_STRING_TOO_LONG("Cannot create a string longer than 2^32-1 characters", .{}).throw() catch {}; // TODO: propagate? return .zero; } return shim.cppFn("toExternalValue", .{ this, global }); @@ -944,7 +944,7 @@ pub const ZigString = extern struct { ) JSValue { if (this.len > String.max_length()) { callback(ctx, @constCast(@ptrCast(this.byteSlice().ptr)), this.len); - global.ERR_STRING_TOO_LONG("Cannot create a string longer than 2^32-1 characters", .{}).throw(); + global.ERR_STRING_TOO_LONG("Cannot create a string longer than 2^32-1 characters", .{}).throw() catch {}; // TODO: propagate? return .zero; } @@ -2966,7 +2966,7 @@ pub const JSGlobalObject = opaque { pub fn throwTODO(this: *JSGlobalObject, msg: []const u8) bun.JSError { const err = this.createErrorInstance("{s}", .{msg}); err.put(this, ZigString.static("name"), bun.String.static("TODOError").toJS(this)); - return this.throwValue2(err); + return this.throwValue(err); } pub const throwTerminationException = JSGlobalObject__throwTerminationException; @@ -2982,18 +2982,17 @@ pub const JSGlobalObject = opaque { 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); + return this.throwValue(err); } - pub inline fn throwMissingArgumentsValue(this: *JSGlobalObject, comptime arg_names: []const []const u8) JSValue { - switch (arg_names.len) { + pub inline fn throwMissingArgumentsValue(this: *JSGlobalObject, comptime arg_names: []const []const u8) bun.JSError { + return switch (arg_names.len) { 0 => @compileError("requires at least one argument"), 1 => this.ERR_MISSING_ARGS("The \"{s}\" argument must be specified", .{arg_names[0]}).throw(), 2 => this.ERR_MISSING_ARGS("The \"{s}\" and \"{s}\" arguments must be specified", .{ arg_names[0], arg_names[1] }).throw(), 3 => this.ERR_MISSING_ARGS("The \"{s}\", \"{s}\", and \"{s}\" arguments must be specified", .{ arg_names[0], arg_names[1], arg_names[2] }).throw(), else => @compileError("implement this message"), - } - return .zero; + }; } pub fn createInvalidArgumentType( @@ -3014,8 +3013,8 @@ pub const JSGlobalObject = opaque { comptime name_: []const u8, comptime field: []const u8, comptime typename: []const u8, - ) void { - this.throwValue(this.createInvalidArgumentType(name_, field, typename)); + ) bun.JSError { + return this.throwValue(this.createInvalidArgumentType(name_, field, typename)); } pub fn throwInvalidArgumentTypeValue( @@ -3025,8 +3024,7 @@ pub const JSGlobalObject = opaque { value: JSValue, ) bun.JSError { var formatter = JSC.ConsoleObject.Formatter{ .globalThis = this }; - this.ERR_INVALID_ARG_TYPE("The \"{s}\" argument must be of type {s}. Received {}", .{ argname, typename, value.toFmt(&formatter) }).throw(); - return error.JSError; + return this.ERR_INVALID_ARG_TYPE("The \"{s}\" argument must be of type {s}. Received {}", .{ argname, typename, value.toFmt(&formatter) }).throw(); } pub fn throwInvalidArgumentRangeValue( @@ -3035,8 +3033,7 @@ pub const JSGlobalObject = opaque { typename: []const u8, value: i64, ) bun.JSError { - this.ERR_OUT_OF_RANGE("The \"{s}\" is out of range. {s}. Received {}", .{ argname, typename, value }).throw(); - return error.JSError; + return this.ERR_OUT_OF_RANGE("The \"{s}\" is out of range. {s}. Received {}", .{ argname, typename, value }).throw(); } pub fn throwInvalidPropertyTypeValue( @@ -3047,8 +3044,7 @@ pub const JSGlobalObject = opaque { ) bun.JSError { const ty_str = value.jsTypeString(this).toSlice(this, bun.default_allocator); defer ty_str.deinit(); - this.ERR_INVALID_ARG_TYPE("The \"{s}\" property must be of type {s}. Received {s}", .{ field, typename, ty_str.slice() }).throw(); - return error.JSError; + return this.ERR_INVALID_ARG_TYPE("The \"{s}\" property must be of type {s}. Received {s}", .{ field, typename, ty_str.slice() }).throw(); } pub fn createNotEnoughArguments( @@ -3066,7 +3062,7 @@ pub const JSGlobalObject = opaque { comptime expected: usize, got: usize, ) bun.JSError { - return this.throwValue2(this.createNotEnoughArguments(name_, expected, got)); + return this.throwValue(this.createNotEnoughArguments(name_, expected, got)); } extern fn JSC__JSGlobalObject__reload(JSC__JSGlobalObject__ptr: *JSGlobalObject) void; @@ -3194,16 +3190,10 @@ pub const JSGlobalObject = opaque { return err; } - pub fn throw(this: *JSGlobalObject, comptime fmt: [:0]const u8, args: anytype) void { - const instance = this.createErrorInstance(fmt, args); - bun.assert(instance != .zero); - this.vm().throwError(this, instance); - } - - pub fn throw2(this: *JSGlobalObject, comptime fmt: [:0]const u8, args: anytype) JSError { + pub fn throw(this: *JSGlobalObject, comptime fmt: [:0]const u8, args: anytype) JSError { const instance = this.createErrorInstance(fmt, args); bun.assert(instance != .zero); - return this.vm().throwError2(this, instance); + return this.throwValue(instance); } pub fn throwPretty(this: *JSGlobalObject, comptime fmt: [:0]const u8, args: anytype) bun.JSError { @@ -3211,8 +3201,9 @@ pub const JSGlobalObject = opaque { inline else => |enabled| this.createErrorInstance(Output.prettyFmt(fmt, enabled), args), }; bun.assert(instance != .zero); - return this.vm().throwError2(this, instance); + return this.throwValue(instance); } + extern fn JSC__JSGlobalObject__queueMicrotaskCallback(*JSGlobalObject, *anyopaque, Function: *const (fn (*anyopaque) callconv(.C) void)) void; pub fn queueMicrotaskCallback( this: *JSGlobalObject, @@ -3231,11 +3222,7 @@ pub const JSGlobalObject = opaque { JSC__JSGlobalObject__queueMicrotaskCallback(this, ctx_val, &Wrapper.call); } - pub fn queueMicrotask( - this: *JSGlobalObject, - function: JSValue, - args: []const JSC.JSValue, - ) void { + pub fn queueMicrotask(this: *JSGlobalObject, function: JSValue, args: []const JSC.JSValue) void { this.queueMicrotaskJob( function, if (args.len > 0) args[0] else .zero, @@ -3244,27 +3231,13 @@ pub const JSGlobalObject = opaque { } extern fn JSC__JSGlobalObject__queueMicrotaskJob(JSC__JSGlobalObject__ptr: *JSGlobalObject, JSValue, JSValue, JSValue) void; - pub fn queueMicrotaskJob( - this: *JSGlobalObject, - function: JSValue, - first: JSValue, - second: JSValue, - ) void { + pub fn queueMicrotaskJob(this: *JSGlobalObject, function: JSValue, first: JSValue, second: JSValue) void { JSC__JSGlobalObject__queueMicrotaskJob(this, function, first, second); } - pub fn throwValue( - this: *JSGlobalObject, - value: JSC.JSValue, - ) void { + pub fn throwValue(this: *JSGlobalObject, value: JSC.JSValue) JSError { this.vm().throwError(this, value); - } - - pub fn throwValue2( - this: *JSGlobalObject, - value: JSC.JSValue, - ) JSError { - return this.vm().throwError2(this, value); + return error.JSError; } pub fn throwError(this: *JSGlobalObject, err: anyerror, comptime fmt: [:0]const u8) bun.JSError { @@ -3284,7 +3257,8 @@ pub const JSGlobalObject = opaque { defer allocator_.free(buffer); const str = ZigString.initUTF8(buffer); const err_value = str.toErrorInstance(this); - return this.vm().throwError2(this, err_value); + this.vm().throwError(this, err_value); + return error.JSError; } pub fn ref(this: *JSGlobalObject) C_API.JSContextRef { @@ -3440,10 +3414,11 @@ pub const JSGlobalObject = opaque { } } - pub fn throwRangeError(this: *JSGlobalObject, value: anytype, options: bun.fmt.OutOfRangeOptions) void { + pub fn throwRangeError(this: *JSGlobalObject, value: anytype, options: bun.fmt.OutOfRangeOptions) bun.JSError { + // TODO: // This works around a Zig compiler bug // when using this.ERR_OUT_OF_RANGE. - JSC.Error.ERR_OUT_OF_RANGE.throw(this, "{}", .{bun.fmt.outOfRange(value, options)}); + return JSC.Error.ERR_OUT_OF_RANGE.throw(this, "{}", .{bun.fmt.outOfRange(value, options)}); } pub const IntegerRange = struct { @@ -3481,8 +3456,7 @@ pub const JSGlobalObject = opaque { return 0; } if (int < min_t or int > max_t) { - this.throwRangeError(int, .{ .field_name = field_name, .min = min, .max = max }); - return error.JSError; + return this.throwRangeError(int, .{ .field_name = field_name, .min = min, .max = max }); } return @intCast(int); } @@ -3503,8 +3477,7 @@ pub const JSGlobalObject = opaque { return this.throwInvalidPropertyTypeValue(field_name, "integer", value); } if (f64_val < min_t or f64_val > max_t) { - this.throwRangeError(f64_val, .{ .field_name = comptime field_name, .min = min, .max = max }); - return error.JSError; + return this.throwRangeError(f64_val, .{ .field_name = comptime field_name, .min = min, .max = max }); } return @intFromFloat(f64_val); @@ -6416,18 +6389,11 @@ pub const VM = extern struct { }); } - pub fn throwError(vm: *VM, global_object: *JSGlobalObject, value: JSValue) void { - return cppFn("throwError", .{ - vm, - global_object, - value, - }); - } - - // TODO: rewrite all `throwError` to use `JSError` - pub fn throwError2(vm: *VM, global_object: *JSGlobalObject, value: JSValue) JSError { - vm.throwError(global_object, value); - return error.JSError; + // manual extern to workaround shimmer limitation + // shimmer doesnt let you change the return type or make it non-pub + extern fn JSC__VM__throwError(*VM, *JSGlobalObject, JSValue) void; + fn throwError(vm: *VM, global_object: *JSGlobalObject, value: JSValue) void { + JSC__VM__throwError(vm, global_object, value); } pub fn releaseWeakRefs(vm: *VM) void { diff --git a/src/bun.js/node/node_cluster_binding.zig b/src/bun.js/node/node_cluster_binding.zig index 9e8e9fbdb742d3..8f6d09381ed6af 100644 --- a/src/bun.js/node/node_cluster_binding.zig +++ b/src/bun.js/node/node_cluster_binding.zig @@ -29,8 +29,7 @@ pub fn sendHelperChild(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFram return globalThis.throwMissingArgumentsValue(&.{"message"}); } if (!handle.isNull()) { - globalThis.throw("passing 'handle' not implemented yet", .{}); - return .zero; + return globalThis.throw("passing 'handle' not implemented yet", .{}); } if (!message.isObject()) { return globalThis.throwInvalidArgumentTypeValue("message", "object", message); diff --git a/src/bun.js/node/node_crypto_binding.zig b/src/bun.js/node/node_crypto_binding.zig index 442173bfcc250a..2605f64fb86a78 100644 --- a/src/bun.js/node/node_crypto_binding.zig +++ b/src/bun.js/node/node_crypto_binding.zig @@ -67,8 +67,7 @@ fn pbkdf2Sync(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JS if (!data.run(output.slice())) { const err = Crypto.createCryptoError(globalThis, BoringSSL.ERR_get_error()); BoringSSL.ERR_clear_error(); - globalThis.throwValue(err); - return .zero; + return globalThis.throwValue(err); } return out_arraybuffer; diff --git a/src/bun.js/node/node_fs.zig b/src/bun.js/node/node_fs.zig index e58bce0e7c857d..31c5d47fcba1b5 100644 --- a/src/bun.js/node/node_fs.zig +++ b/src/bun.js/node/node_fs.zig @@ -2559,8 +2559,7 @@ pub const Arguments = struct { if (defined_length and args.length > 0 and buffer.slice().len == 0) { var formatter = bun.JSC.ConsoleObject.Formatter{ .globalThis = ctx }; - ctx.ERR_INVALID_ARG_VALUE("The argument 'buffer' is empty and cannot be written. Received {}", .{buffer_value.?.toFmt(&formatter)}).throw(); - return error.JSError; + return ctx.ERR_INVALID_ARG_VALUE("The argument 'buffer' is empty and cannot be written. Received {}", .{buffer_value.?.toFmt(&formatter)}).throw(); } return args; @@ -5552,7 +5551,7 @@ pub const NodeFS = struct { .message = bun.String.init(buf), .code = bun.String.init(@errorName(err)), .path = bun.String.init(args.path.slice()), - }).toErrorInstance(args.global_this)); + }).toErrorInstance(args.global_this)) catch {}; return Maybe(Return.Watch){ .result = JSC.JSValue.undefined }; }; return Maybe(Return.Watch){ .result = watcher }; diff --git a/src/bun.js/node/node_fs_binding.zig b/src/bun.js/node/node_fs_binding.zig index ef52334d980786..cee9ac021f8ae0 100644 --- a/src/bun.js/node/node_fs_binding.zig +++ b/src/bun.js/node/node_fs_binding.zig @@ -50,8 +50,7 @@ fn callSync(comptime FunctionEnum: NodeFSFunctionEnum) NodeFSFunction { ); switch (result) { .err => |err| { - globalObject.throwValue(JSC.JSValue.c(err.toJS(globalObject))); - return .zero; + return globalObject.throwValue(JSC.JSValue.c(err.toJS(globalObject))); }, .result => |*res| { return globalObject.toJS(res, .temporary); @@ -239,8 +238,7 @@ pub fn createMemfdForTesting(globalObject: *JSC.JSGlobalObject, callFrame: *JSC. } if (comptime !bun.Environment.isLinux) { - globalObject.throw("memfd_create is not implemented on this platform", .{}); - return .zero; + return globalObject.throw("memfd_create is not implemented on this platform", .{}); } const size = arguments.ptr[0].toInt64(); @@ -250,8 +248,7 @@ pub fn createMemfdForTesting(globalObject: *JSC.JSGlobalObject, callFrame: *JSC. return JSC.JSValue.jsNumber(fd.cast()); }, .err => |err| { - globalObject.throwValue(err.toJSC(globalObject)); - return .zero; + return globalObject.throwValue(err.toJSC(globalObject)); }, } } diff --git a/src/bun.js/node/node_net_binding.zig b/src/bun.js/node/node_net_binding.zig index 6a3a50350c34a0..ade4c17c0cb203 100644 --- a/src/bun.js/node/node_net_binding.zig +++ b/src/bun.js/node/node_net_binding.zig @@ -26,7 +26,7 @@ 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) { - return globalThis.throw2("missing argument", .{}); + return globalThis.throw("missing argument", .{}); } const arg = arguments.slice()[0]; if (!arg.isBoolean()) { @@ -59,7 +59,7 @@ 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) { - return globalThis.throw2("missing argument", .{}); + return globalThis.throw("missing argument", .{}); } const arg = arguments.slice()[0]; if (!arg.isInt32AsAnyInt()) { diff --git a/src/bun.js/node/node_os.zig b/src/bun.js/node/node_os.zig index 7d8ffc223ffcc4..a7c4da6691d15d 100644 --- a/src/bun.js/node/node_os.zig +++ b/src/bun.js/node/node_os.zig @@ -65,8 +65,7 @@ pub const OS = struct { .code = bun.String.static(@tagName(JSC.Node.ErrorCode.ERR_SYSTEM_ERROR)), }; - globalThis.vm().throwError(globalThis, err.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(err.toErrorInstance(globalThis)); }; } @@ -313,8 +312,7 @@ pub const OS = struct { const arguments: []const JSC.JSValue = args_.ptr[0..args_.len]; if (arguments.len > 0 and !arguments[0].isNumber()) { - globalThis.ERR_INVALID_ARG_TYPE("getPriority() expects a number", .{}).throw(); - return .zero; + return globalThis.ERR_INVALID_ARG_TYPE("getPriority() expects a number", .{}).throw(); } const pid = if (arguments.len > 0) arguments[0].asInt32() else 0; @@ -335,8 +333,7 @@ pub const OS = struct { .syscall = bun.String.static("uv_os_getpriority"), }; - globalThis.vm().throwError(globalThis, err.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(err.toErrorInstance(globalThis)); } return JSC.JSValue.jsNumberFromInt32(priority); @@ -406,7 +403,7 @@ pub const OS = struct { }; } - fn networkInterfacesPosix(globalThis: *JSC.JSGlobalObject) JSC.JSValue { + fn networkInterfacesPosix(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { // getifaddrs sets a pointer to a linked list var interface_start: ?*C.ifaddrs = null; const rc = C.getifaddrs(&interface_start); @@ -418,8 +415,7 @@ pub const OS = struct { .syscall = bun.String.static("getifaddrs"), }; - globalThis.vm().throwError(globalThis, err.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(err.toErrorInstance(globalThis)); } defer C.freeifaddrs(interface_start); @@ -589,7 +585,7 @@ pub const OS = struct { return ret; } - fn networkInterfacesWindows(globalThis: *JSC.JSGlobalObject) JSC.JSValue { + fn networkInterfacesWindows(globalThis: *JSC.JSGlobalObject) bun.JSError!JSC.JSValue { var ifaces: [*]libuv.uv_interface_address_t = undefined; var count: c_int = undefined; const err = libuv.uv_interface_addresses(&ifaces, &count); @@ -601,8 +597,7 @@ pub const OS = struct { .errno = err, .syscall = bun.String.static("uv_interface_addresses"), }; - globalThis.vm().throwError(globalThis, sys_err.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(sys_err.toErrorInstance(globalThis)); } defer libuv.uv_free_interface_addresses(ifaces, count); @@ -729,8 +724,7 @@ pub const OS = struct { .{}, globalThis, ); - globalThis.vm().throwError(globalThis, err); - return .zero; + return globalThis.throwValue(err); } const pid = if (arguments.len == 2) arguments[0].coerce(i32, globalThis) else 0; @@ -743,8 +737,7 @@ pub const OS = struct { .{}, globalThis, ); - globalThis.vm().throwError(globalThis, err); - return .zero; + return globalThis.throwValue(err); } const errcode = C.setProcessPriority(pid, priority); @@ -758,8 +751,7 @@ pub const OS = struct { .syscall = bun.String.static("uv_os_setpriority"), }; - globalThis.vm().throwError(globalThis, err.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(err.toErrorInstance(globalThis)); }, .ACCES => { const err = JSC.SystemError{ @@ -770,8 +762,7 @@ pub const OS = struct { .syscall = bun.String.static("uv_os_setpriority"), }; - globalThis.vm().throwError(globalThis, err.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(err.toErrorInstance(globalThis)); }, else => {}, } @@ -809,8 +800,7 @@ pub const OS = struct { .errno = err, .syscall = bun.String.static("uv_uptime"), }; - globalThis.vm().throwError(globalThis, sys_err.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(sys_err.toErrorInstance(globalThis)); } return JSC.JSValue.jsNumber(uptime_value); } diff --git a/src/bun.js/node/node_zlib_binding.zig b/src/bun.js/node/node_zlib_binding.zig index a094d75bda3856..8531c209d5e4f9 100644 --- a/src/bun.js/node/node_zlib_binding.zig +++ b/src/bun.js/node/node_zlib_binding.zig @@ -22,8 +22,7 @@ pub fn crc32(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE const buffer: JSC.Buffer = JSC.Buffer.fromJS(globalThis, data) orelse { const ty_str = data.jsTypeString(globalThis).toSlice(globalThis, bun.default_allocator); defer ty_str.deinit(); - globalThis.ERR_INVALID_ARG_TYPE("The \"data\" property must be an instance of Buffer, TypedArray, DataView, or ArrayBuffer. Received {s}", .{ty_str.slice()}).throw(); - return .zero; + return globalThis.ERR_INVALID_ARG_TYPE("The \"data\" property must be an instance of Buffer, TypedArray, DataView, or ArrayBuffer. Received {s}", .{ty_str.slice()}).throw(); }; break :blk ZigString.Slice.fromUTF8NeverFree(buffer.slice()); }; @@ -42,12 +41,10 @@ pub fn crc32(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSE const max = std.math.maxInt(u32); if (@floor(valuef) != valuef) { - globalThis.ERR_OUT_OF_RANGE("The value of \"{s}\" is out of range. It must be an integer. Received {}", .{ "value", valuef }).throw(); - return .zero; + return globalThis.ERR_OUT_OF_RANGE("The value of \"{s}\" is out of range. It must be an integer. Received {}", .{ "value", valuef }).throw(); } if (valuef < min or valuef > max) { - globalThis.ERR_OUT_OF_RANGE("The value of \"{s}\" is out of range. It must be >= {d} and <= {d}. Received {d}", .{ "value", min, max, valuef }).throw(); - return .zero; + return globalThis.ERR_OUT_OF_RANGE("The value of \"{s}\" is out of range. It must be >= {d} and <= {d}. Received {d}", .{ "value", min, max, valuef }).throw(); } break :blk @intFromFloat(valuef); }; @@ -63,8 +60,7 @@ pub fn CompressionStream(comptime T: type) type { const arguments = callframe.argumentsUndef(7).slice(); if (arguments.len != 7) { - globalThis.ERR_MISSING_ARGS("write(flush, in, in_off, in_len, out, out_off, out_len)", .{}).throw(); - return .zero; + return globalThis.ERR_MISSING_ARGS("write(flush, in, in_off, in_len, out, out_off, out_len)", .{}).throw(); } var in_off: u32 = 0; @@ -155,8 +151,7 @@ pub fn CompressionStream(comptime T: type) type { const arguments = callframe.argumentsUndef(7).slice(); if (arguments.len != 7) { - globalThis.ERR_MISSING_ARGS("writeSync(flush, in, in_off, in_len, out, out_off, out_len)", .{}).throw(); - return .zero; + return globalThis.ERR_MISSING_ARGS("writeSync(flush, in, in_off, in_len, out, out_off, out_len)", .{}).throw(); } var in_off: u32 = 0; @@ -334,8 +329,7 @@ pub const SNativeZlib = struct { } const mode_int: i64 = @intFromFloat(mode_double); if (mode_int < 1 or mode_int > 7) { - _ = globalThis.throwRangeError(mode_int, .{ .field_name = "mode", .min = 1, .max = 7 }); - return error.JSError; + return globalThis.throwRangeError(mode_int, .{ .field_name = "mode", .min = 1, .max = 7 }); } const ptr = SNativeZlib.new(.{ @@ -357,8 +351,7 @@ pub const SNativeZlib = struct { const arguments = callframe.argumentsUndef(7).slice(); if (arguments.len != 7) { - globalThis.ERR_MISSING_ARGS("init(windowBits, level, memLevel, strategy, writeResult, writeCallback, dictionary)", .{}).throw(); - return .zero; + return globalThis.ERR_MISSING_ARGS("init(windowBits, level, memLevel, strategy, writeResult, writeCallback, dictionary)", .{}).throw(); } const windowBits = try validators.validateInt32(globalThis, arguments[0], "windowBits", .{}, null, null); @@ -382,8 +375,7 @@ pub const SNativeZlib = struct { const arguments = callframe.argumentsUndef(2).slice(); if (arguments.len != 2) { - globalThis.ERR_MISSING_ARGS("params(level, strategy)", .{}).throw(); - return .zero; + return globalThis.ERR_MISSING_ARGS("params(level, strategy)", .{}).throw(); } const level = try validators.validateInt32(globalThis, arguments[0], "level", .{}, null, null); @@ -692,8 +684,7 @@ pub const SNativeBrotli = struct { } const mode_int: i64 = @intFromFloat(mode_double); if (mode_int < 8 or mode_int > 9) { - _ = globalThis.throwRangeError(mode_int, .{ .field_name = "mode", .min = 8, .max = 9 }); - return error.JSError; + return globalThis.throwRangeError(mode_int, .{ .field_name = "mode", .min = 8, .max = 9 }); } const ptr = @This().new(.{ @@ -718,8 +709,7 @@ pub const SNativeBrotli = struct { pub fn init(this: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { const arguments = callframe.argumentsUndef(3).slice(); if (arguments.len != 3) { - globalThis.ERR_MISSING_ARGS("init(params, writeResult, writeCallback)", .{}).throw(); - return .zero; + return globalThis.ERR_MISSING_ARGS("init(params, writeResult, writeCallback)", .{}).throw(); } // this does not get gc'd because it is stored in the JS object's `this._writeState`. and the JS object is tied to the native handle as `_handle[owner_symbol]`. diff --git a/src/bun.js/node/types.zig b/src/bun.js/node/types.zig index c1529a53452cf6..c664c4895436db 100644 --- a/src/bun.js/node/types.zig +++ b/src/bun.js/node/types.zig @@ -699,13 +699,7 @@ pub const Encoding = enum(u8) { } pub fn throwEncodingError(globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) bun.JSError { - globalObject.ERR_INVALID_ARG_VALUE( - "encoding '{}' is an invalid encoding", - .{ - value.fmtString(globalObject), - }, - ).throw(); - return error.JSError; + return globalObject.ERR_INVALID_ARG_VALUE("encoding '{}' is an invalid encoding", .{value.fmtString(globalObject)}).throw(); } pub fn encodeWithSize(encoding: Encoding, globalObject: *JSC.JSGlobalObject, comptime size: usize, input: *const [size]u8) JSC.JSValue { @@ -733,8 +727,7 @@ pub const Encoding = enum(u8) { inline else => |enc| { const res = JSC.WebCore.Encoder.toString(input.ptr, size, globalObject, enc); if (res.isError()) { - globalObject.throwValue(res); - return .zero; + return globalObject.throwValue(res) catch .zero; } return res; @@ -770,8 +763,7 @@ pub const Encoding = enum(u8) { inline else => |enc| { const res = JSC.WebCore.Encoder.toString(input.ptr, input.len, globalObject, enc); if (res.isError()) { - globalObject.throwValue(res); - return .zero; + return globalObject.throwValue(res) catch .zero; } return res; @@ -1047,8 +1039,7 @@ pub const Valid = struct { // TODO: should this be an EINVAL? var system_error = bun.sys.Error.fromCode(.NAMETOOLONG, .open).withPath(zig_str.slice()).toSystemError(); system_error.syscall = bun.String.dead; - ctx.throwValue(system_error.toErrorInstance(ctx)); - return error.JSError; + return ctx.throwValue(system_error.toErrorInstance(ctx)); }, } unreachable; @@ -1061,8 +1052,7 @@ pub const Valid = struct { // TODO: should this be an EINVAL? var system_error = bun.sys.Error.fromCode(.NAMETOOLONG, .open).toSystemError(); system_error.syscall = bun.String.dead; - ctx.throwValue(system_error.toErrorInstance(ctx)); - return error.JSError; + return ctx.throwValue(system_error.toErrorInstance(ctx)); }, } unreachable; @@ -1081,8 +1071,7 @@ pub const Valid = struct { else => { var system_error = bun.sys.Error.fromCode(.NAMETOOLONG, .open).toSystemError(); system_error.syscall = bun.String.dead; - ctx.throwValue(system_error.toErrorInstance(ctx)); - return error.JSError; + return ctx.throwValue(system_error.toErrorInstance(ctx)); }, 1...bun.MAX_PATH_BYTES => return, } @@ -1285,8 +1274,7 @@ pub fn modeFromJS(ctx: JSC.C.JSContextRef, value: JSC.JSValue) bun.JSError!?Mode break :brk std.fmt.parseInt(Mode, slice, 8) catch { var formatter = bun.JSC.ConsoleObject.Formatter{ .globalThis = ctx }; - ctx.throwValue(ctx.ERR_INVALID_ARG_VALUE("The argument 'mode' must be a 32-bit unsigned integer or an octal string. Received {}", .{value.toFmt(&formatter)}).toJS()); - return error.JSError; + return ctx.throwValue(ctx.ERR_INVALID_ARG_VALUE("The argument 'mode' must be a 32-bit unsigned integer or an octal string. Received {}", .{value.toFmt(&formatter)}).toJS()); }; }; @@ -1458,8 +1446,7 @@ pub const FileSystemFlags = enum(Mode) { pub fn fromJS(ctx: JSC.C.JSContextRef, val: JSC.JSValue) bun.JSError!?FileSystemFlags { if (val.isNumber()) { if (!val.isInt32()) { - ctx.throwValue(ctx.ERR_OUT_OF_RANGE("The value of \"flags\" is out of range. It must be an integer. Received {d}", .{val.asNumber()}).toJS()); - return error.JSError; + return ctx.throwValue(ctx.ERR_OUT_OF_RANGE("The value of \"flags\" is out of range. It must be an integer. Received {d}", .{val.asNumber()}).toJS()); } const number = val.coerce(i32, ctx); return @as(FileSystemFlags, @enumFromInt(@as(Mode, @intCast(@max(number, 0))))); @@ -1839,7 +1826,7 @@ pub const Dirent = struct { pub usingnamespace bun.New(@This()); pub fn constructor(globalObject: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*Dirent { - return globalObject.throw2("Dirent is not a constructor", .{}); + return globalObject.throw("Dirent is not a constructor", .{}); } pub fn toJS(this: *Dirent, globalObject: *JSC.JSGlobalObject) JSC.JSValue { @@ -2082,7 +2069,7 @@ pub const Process = struct { switch (Path.getCwd(&buf)) { .result => |r| return JSC.ZigString.init(r).withEncoding().toJS(globalObject), .err => |e| { - return globalObject.throwValue2(e.toJSC(globalObject)); + return globalObject.throwValue(e.toJSC(globalObject)); }, } } @@ -2097,8 +2084,7 @@ pub const Process = struct { var buf: bun.PathBuffer = undefined; const slice = to.sliceZBuf(&buf) catch { - globalObject.throw("Invalid path", .{}); - return .zero; + return globalObject.throw("Invalid path", .{}); }; switch (Syscall.chdir(slice)) { @@ -2111,8 +2097,7 @@ pub const Process = struct { .result => |r| r, .err => |err| { _ = Syscall.chdir(@as([:0]const u8, @ptrCast(fs.top_level_dir))); - globalObject.throwValue(err.toJSC(globalObject)); - return .zero; + return globalObject.throwValue(err.toJSC(globalObject)); }, }; @memcpy(fs.top_level_dir_buf[0..into_cwd_buf.len], into_cwd_buf); @@ -2130,8 +2115,7 @@ pub const Process = struct { return str.transferToJS(globalObject); }, .err => |e| { - globalObject.throwValue(e.toJSC(globalObject)); - return .zero; + return globalObject.throwValue(e.toJSC(globalObject)); }, } } diff --git a/src/bun.js/node/util/parse_args.zig b/src/bun.js/node/util/parse_args.zig index 4a0268856d767c..221823fcb1a36f 100644 --- a/src/bun.js/node/util/parse_args.zig +++ b/src/bun.js/node/util/parse_args.zig @@ -205,8 +205,7 @@ fn checkOptionLikeValue(globalThis: *JSGlobalObject, token: OptionToken) bun.JSE globalThis, ); } - globalThis.vm().throwError(globalThis, err); - return error.JSError; + return globalThis.throwValue(err); } } @@ -227,8 +226,7 @@ fn checkOptionUsage(globalThis: *JSGlobalObject, options: []const OptionDefiniti }, globalThis, ); - globalThis.vm().throwError(globalThis, err); - return error.JSError; + return globalThis.throwValue(err); }, .boolean => if (token.value != .jsvalue or !token.value.jsvalue.isUndefined()) { const err = JSC.toTypeError( @@ -242,8 +240,7 @@ fn checkOptionUsage(globalThis: *JSGlobalObject, options: []const OptionDefiniti }, globalThis, ); - globalThis.vm().throwError(globalThis, err); - return error.JSError; + return globalThis.throwValue(err); }, } } else { @@ -260,8 +257,7 @@ fn checkOptionUsage(globalThis: *JSGlobalObject, options: []const OptionDefiniti .{raw_name}, globalThis, )); - globalThis.vm().throwError(globalThis, err); - return error.JSError; + return globalThis.throwValue(err); } } @@ -327,8 +323,7 @@ fn parseOptionDefinitions(globalThis: *JSGlobalObject, options_obj: JSValue, opt var short_option_str = short_option.toBunString(globalThis); if (short_option_str.length() != 1) { const err = JSC.toTypeError(.ERR_INVALID_ARG_VALUE, "options.{s}.short must be a single character", .{option.long_name}, globalThis); - globalThis.vm().throwError(globalThis, err); - return error.JSError; + return globalThis.throwValue(err); } option.short_name = short_option_str; } @@ -595,8 +590,7 @@ const ParseArgsState = struct { .{token.value.asBunString(globalThis)}, globalThis, ); - globalThis.vm().throwError(globalThis, err); - return error.JSError; + return globalThis.throwValue(err); } const value = token.value.asJSValue(globalThis); this.positionals.push(globalThis, value); diff --git a/src/bun.js/node/util/validators.zig b/src/bun.js/node/util/validators.zig index 807e9e596884bb..cf8f3b1e045e81 100644 --- a/src/bun.js/node/util/validators.zig +++ b/src/bun.js/node/util/validators.zig @@ -20,8 +20,7 @@ pub fn throwErrInvalidArgValue( args: anytype, ) bun.JSError { @setCold(true); - globalThis.ERR_INVALID_ARG_VALUE(fmt, args).throw(); - return error.JSError; + return globalThis.ERR_INVALID_ARG_VALUE(fmt, args).throw(); } pub fn throwErrInvalidArgTypeWithMessage( @@ -30,8 +29,7 @@ pub fn throwErrInvalidArgTypeWithMessage( args: anytype, ) bun.JSError { @setCold(true); - globalThis.ERR_INVALID_ARG_TYPE(fmt, args).throw(); - return error.JSError; + return globalThis.ERR_INVALID_ARG_TYPE(fmt, args).throw(); } pub fn throwErrInvalidArgType( @@ -52,8 +50,7 @@ pub fn throwRangeError( args: anytype, ) bun.JSError { @setCold(true); - globalThis.ERR_OUT_OF_RANGE(fmt, args).throw(); - return error.JSError; + return globalThis.ERR_OUT_OF_RANGE(fmt, args).throw(); } pub fn validateInteger(globalThis: *JSGlobalObject, value: JSValue, comptime name_fmt: string, name_args: anytype, min_value: ?i64, max_value: ?i64) bun.JSError!i64 { diff --git a/src/bun.js/test/expect.zig b/src/bun.js/test/expect.zig index f64e143e23ada7..1650e7dd262a01 100644 --- a/src/bun.js/test/expect.zig +++ b/src/bun.js/test/expect.zig @@ -169,8 +169,7 @@ pub const Expect = struct { this.flags.promise = switch (this.flags.promise) { .resolves, .none => .resolves, .rejects => { - globalThis.throw("Cannot chain .resolves() after .rejects()", .{}); - return .zero; + return globalThis.throw("Cannot chain .resolves() after .rejects()", .{}) catch .zero; }, }; @@ -181,8 +180,7 @@ pub const Expect = struct { this.flags.promise = switch (this.flags.promise) { .none, .rejects => .rejects, .resolves => { - globalThis.throw("Cannot chain .rejects() after .resolves()", .{}); - return .zero; + return globalThis.throw("Cannot chain .rejects() after .resolves()", .{}) catch .zero; }, }; @@ -191,7 +189,7 @@ pub const Expect = struct { pub fn getValue(this: *Expect, globalThis: *JSGlobalObject, thisValue: JSValue, matcher_name: string, comptime matcher_params_fmt: string) bun.JSError!JSValue { const value = Expect.capturedValueGetCached(thisValue) orelse { - return globalThis.throw2("Internal error: the expect(value) was garbage collected but it should not have been!", .{}); + return globalThis.throw("Internal error: the expect(value) was garbage collected but it should not have been!", .{}); }; value.ensureStillAlive(); @@ -404,7 +402,7 @@ pub const Expect = struct { } pub fn constructor(globalThis: *JSGlobalObject, _: *CallFrame) bun.JSError!*Expect { - return globalThis.throw2("expect() cannot be called with new", .{}); + return globalThis.throw("expect() cannot be called with new", .{}); } // pass here has a leading underscore to avoid name collision with the pass variable in other functions @@ -425,8 +423,7 @@ pub const Expect = struct { value.ensureStillAlive(); if (!value.isString()) { - globalThis.throwInvalidArgumentType("pass", "message", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("pass", "message", "string"); } value.toZigString(&_msg, globalThis); @@ -471,8 +468,7 @@ pub const Expect = struct { value.ensureStillAlive(); if (!value.isString()) { - globalThis.throwInvalidArgumentType("fail", "message", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("fail", "message", "string"); } value.toZigString(&_msg, globalThis); @@ -579,21 +575,18 @@ pub const Expect = struct { if (!value.isObject() and !value.isString()) { var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; - globalThis.throw("Received value does not have a length property: {any}", .{value.toFmt(&fmt)}); - return .zero; + return globalThis.throw("Received value does not have a length property: {any}", .{value.toFmt(&fmt)}); } if (!expected.isNumber()) { var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; - globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); - return .zero; + return globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); } const expected_length: f64 = expected.asNumber(); if (@round(expected_length) != expected_length or std.math.isInf(expected_length) or std.math.isNan(expected_length) or expected_length < 0) { var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; - globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); - return .zero; + return globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); } const not = this.flags.not; @@ -603,11 +596,9 @@ pub const Expect = struct { if (actual_length == std.math.inf(f64)) { var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; - globalThis.throw("Received value does not have a length property: {any}", .{value.toFmt(&fmt)}); - return .zero; + return globalThis.throw("Received value does not have a length property: {any}", .{value.toFmt(&fmt)}); } else if (std.math.isNan(actual_length)) { - globalThis.throw("Received value has non-number length property: {}", .{actual_length}); - return .zero; + return globalThis.throw("Received value has non-number length property: {}", .{actual_length}); } if (actual_length == expected_length) { @@ -689,8 +680,7 @@ pub const Expect = struct { } }.sameValueIterator); } else { - globalThis.throw("Received value must be an array type, or both received and expected values must be strings.", .{}); - return .zero; + return globalThis.throw("Received value must be an array type, or both received and expected values must be strings.", .{}); } if (not) pass = !pass; @@ -784,8 +774,7 @@ pub const Expect = struct { } }.sameValueIterator); } else { - globalThis.throw("Received value must be an array type, or both received and expected values must be strings.", .{}); - return .zero; + return globalThis.throw("Received value must be an array type, or both received and expected values must be strings.", .{}); } if (not) pass = !pass; @@ -881,8 +870,7 @@ pub const Expect = struct { const value: JSValue = try this.getValue(globalThis, thisValue, "toContainKeys", "expected"); if (!expected.jsType().isArray()) { - globalThis.throwInvalidArgumentType("toContainKeys", "expected", "array"); - return .zero; + return globalThis.throwInvalidArgumentType("toContainKeys", "expected", "array"); } const not = this.flags.not; @@ -951,8 +939,7 @@ pub const Expect = struct { const value: JSValue = try this.getValue(globalObject, thisValue, "toContainAllKeys", "expected"); if (!expected.jsType().isArray()) { - globalObject.throwInvalidArgumentType("toContainAllKeys", "expected", "array"); - return .zero; + return globalObject.throwInvalidArgumentType("toContainAllKeys", "expected", "array"); } const not = this.flags.not; @@ -1016,8 +1003,7 @@ pub const Expect = struct { const value: JSValue = try this.getValue(globalThis, thisValue, "toContainAnyKeys", "expected"); if (!expected.jsType().isArray()) { - globalThis.throwInvalidArgumentType("toContainAnyKeys", "expected", "array"); - return .zero; + return globalThis.throwInvalidArgumentType("toContainAnyKeys", "expected", "array"); } const not = this.flags.not; @@ -1132,8 +1118,7 @@ pub const Expect = struct { const expected = arguments[0]; if (!expected.jsType().isArray()) { - globalObject.throwInvalidArgumentType("toContainValues", "expected", "array"); - return .zero; + return globalObject.throwInvalidArgumentType("toContainValues", "expected", "array"); } expected.ensureStillAlive(); const value: JSValue = try this.getValue(globalObject, thisValue, "toContainValues", "expected"); @@ -1196,8 +1181,7 @@ pub const Expect = struct { const expected = arguments[0]; if (!expected.jsType().isArray()) { - globalObject.throwInvalidArgumentType("toContainAllValues", "expected", "array"); - return .zero; + return globalObject.throwInvalidArgumentType("toContainAllValues", "expected", "array"); } expected.ensureStillAlive(); const value: JSValue = try this.getValue(globalObject, thisValue, "toContainAllValues", "expected"); @@ -1266,8 +1250,7 @@ pub const Expect = struct { const expected = arguments[0]; if (!expected.jsType().isArray()) { - globalObject.throwInvalidArgumentType("toContainAnyValues", "expected", "array"); - return .zero; + return globalObject.throwInvalidArgumentType("toContainAnyValues", "expected", "array"); } expected.ensureStillAlive(); const value: JSValue = try this.getValue(globalObject, thisValue, "toContainAnyValues", "expected"); @@ -1392,8 +1375,7 @@ pub const Expect = struct { } }.deepEqualsIterator); } else { - globalThis.throw("Received value must be an array type, or both received and expected values must be strings.", .{}); - return .zero; + return globalThis.throw("Received value must be an array type, or both received and expected values must be strings.", .{}); } if (not) pass = !pass; @@ -1685,8 +1667,7 @@ pub const Expect = struct { const value: JSValue = try this.getValue(globalThis, thisValue, "toHaveProperty", "path, value"); if (!expected_property_path.isString() and !expected_property_path.isIterable(globalThis)) { - globalThis.throw("Expected path must be a string or an array", .{}); - return .zero; + return globalThis.throw("Expected path must be a string or an array", .{}); } const not = this.flags.not; @@ -1824,8 +1805,7 @@ pub const Expect = struct { const value: JSValue = try this.getValue(globalThis, thisValue, "toBeGreaterThan", "expected"); if ((!value.isNumber() and !value.isBigInt()) or (!other_value.isNumber() and !other_value.isBigInt())) { - globalThis.throw("Expected and actual values must be numbers or bigints", .{}); - return .zero; + return globalThis.throw("Expected and actual values must be numbers or bigints", .{}); } const not = this.flags.not; @@ -1884,8 +1864,7 @@ pub const Expect = struct { const value: JSValue = try this.getValue(globalThis, thisValue, "toBeGreaterThanOrEqual", "expected"); if ((!value.isNumber() and !value.isBigInt()) or (!other_value.isNumber() and !other_value.isBigInt())) { - globalThis.throw("Expected and actual values must be numbers or bigints", .{}); - return .zero; + return globalThis.throw("Expected and actual values must be numbers or bigints", .{}); } const not = this.flags.not; @@ -1944,8 +1923,7 @@ pub const Expect = struct { const value: JSValue = try this.getValue(globalThis, thisValue, "toBeLessThan", "expected"); if ((!value.isNumber() and !value.isBigInt()) or (!other_value.isNumber() and !other_value.isBigInt())) { - globalThis.throw("Expected and actual values must be numbers or bigints", .{}); - return .zero; + return globalThis.throw("Expected and actual values must be numbers or bigints", .{}); } const not = this.flags.not; @@ -2004,8 +1982,7 @@ pub const Expect = struct { const value: JSValue = try this.getValue(globalThis, thisValue, "toBeLessThanOrEqual", "expected"); if ((!value.isNumber() and !value.isBigInt()) or (!other_value.isNumber() and !other_value.isBigInt())) { - globalThis.throw("Expected and actual values must be numbers or bigints", .{}); - return .zero; + return globalThis.throw("Expected and actual values must be numbers or bigints", .{}); } const not = this.flags.not; @@ -2058,16 +2035,14 @@ pub const Expect = struct { const expected_ = arguments[0]; if (!expected_.isNumber()) { - globalThis.throwInvalidArgumentType("toBeCloseTo", "expected", "number"); - return .zero; + return globalThis.throwInvalidArgumentType("toBeCloseTo", "expected", "number"); } var precision: f64 = 2.0; if (arguments.len > 1) { const precision_ = arguments[1]; if (!precision_.isNumber()) { - globalThis.throwInvalidArgumentType("toBeCloseTo", "precision", "number"); - return .zero; + return globalThis.throwInvalidArgumentType("toBeCloseTo", "precision", "number"); } precision = precision_.asNumber(); @@ -2075,8 +2050,7 @@ pub const Expect = struct { const received_: JSValue = try this.getValue(globalThis, thisValue, "toBeCloseTo", "expected, precision"); if (!received_.isNumber()) { - globalThis.throwInvalidArgumentType("expect", "received", "number"); - return .zero; + return globalThis.throwInvalidArgumentType("expect", "received", "number"); } var expected = expected_.asNumber(); @@ -2191,8 +2165,7 @@ pub const Expect = struct { const value = arguments[0]; if (value.isUndefinedOrNull() or !value.isObject() and !value.isString()) { var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; - globalThis.throw("Expected value must be string or Error: {any}", .{value.toFmt(&fmt)}); - return .zero; + return globalThis.throw("Expected value must be string or Error: {any}", .{value.toFmt(&fmt)}); } if (value.isObject()) { if (ExpectAny.fromJSDirect(value)) |_| { @@ -2216,8 +2189,7 @@ pub const Expect = struct { break :brk value; } - globalThis.throw("Expected value must be a function", .{}); - return .zero; + return globalThis.throw("Expected value must be a function", .{}); } var return_value: JSValue = .zero; @@ -2605,22 +2577,20 @@ pub const Expect = struct { const result = Jest.runner.?.snapshots.getOrPut(this, value, hint.slice(), globalThis) catch |err| { var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; const test_file_path = Jest.runner.?.files.get(this.testScope().?.describe.file_id).source.path.text; - switch (err) { + return switch (err) { error.FailedToOpenSnapshotFile => globalThis.throw("Failed to open snapshot file for test file: {s}", .{test_file_path}), error.FailedToMakeSnapshotDirectory => globalThis.throw("Failed to make snapshot directory for test file: {s}", .{test_file_path}), error.FailedToWriteSnapshotFile => globalThis.throw("Failed write to snapshot file: {s}", .{test_file_path}), error.SyntaxError, error.ParseError => globalThis.throw("Failed to parse snapshot file for: {s}", .{test_file_path}), else => globalThis.throw("Failed to snapshot value: {any}", .{value.toFmt(&formatter)}), - } - return .zero; + }; }; if (result) |saved_value| { var pretty_value: MutableString = MutableString.init(default_allocator, 0) catch unreachable; value.jestSnapshotPrettyFormat(&pretty_value, globalThis) catch { var formatter = JSC.ConsoleObject.Formatter{ .globalThis = globalThis }; - globalThis.throw("Failed to pretty format value: {s}", .{value.toFmt(&formatter)}); - return .zero; + return globalThis.throw("Failed to pretty format value: {s}", .{value.toFmt(&formatter)}); }; defer pretty_value.deinit(); @@ -2689,8 +2659,7 @@ pub const Expect = struct { return globalThis.throwPretty(fmt, .{value.toFmt(&formatter)}); } } else if (std.math.isNan(actual_length)) { - globalThis.throw("Received value has non-number length property: {}", .{actual_length}); - return .zero; + return globalThis.throw("Received value has non-number length property: {}", .{actual_length}); } else { pass = actual_length == 0; } @@ -2811,8 +2780,7 @@ pub const Expect = struct { size.ensureStillAlive(); if (!size.isAnyInt()) { - globalThis.throw("toBeArrayOfSize() requires the first argument to be a number", .{}); - return .zero; + return globalThis.throw("toBeArrayOfSize() requires the first argument to be a number", .{}); } incrementExpectCallCounter(); @@ -2910,8 +2878,7 @@ pub const Expect = struct { } else if (value.isUndefined()) { whatIsTheType = "undefined"; } else { - globalThis.throw("Internal consistency error: unknown JSValue type", .{}); - return .zero; + return globalThis.throw("Internal consistency error: unknown JSValue type", .{}); } pass = strings.eql(typeof, whatIsTheType); @@ -3167,16 +3134,14 @@ pub const Expect = struct { startValue.ensureStillAlive(); if (!startValue.isNumber()) { - globalThis.throw("toBeWithin() requires the first argument to be a number", .{}); - return .zero; + return globalThis.throw("toBeWithin() requires the first argument to be a number", .{}); } const endValue = arguments[1]; endValue.ensureStillAlive(); if (!endValue.isNumber()) { - globalThis.throw("toBeWithin() requires the second argument to be a number", .{}); - return .zero; + return globalThis.throw("toBeWithin() requires the second argument to be a number", .{}); } incrementExpectCallCounter(); @@ -3227,8 +3192,7 @@ pub const Expect = struct { const value: JSValue = try this.getValue(globalThis, thisValue, "toEqualIgnoringWhitespace", "expected"); if (!expected.isString()) { - globalThis.throw("toEqualIgnoringWhitespace() requires argument to be a string", .{}); - return .zero; + return globalThis.throw("toEqualIgnoringWhitespace() requires argument to be a string", .{}); } const not = this.flags.not; @@ -3430,8 +3394,7 @@ pub const Expect = struct { expected.ensureStillAlive(); if (!expected.isString()) { - globalThis.throw("toInclude() requires the first argument to be a string", .{}); - return .zero; + return globalThis.throw("toInclude() requires the first argument to be a string", .{}); } const value: JSValue = try this.getValue(globalThis, thisValue, "toInclude", ""); @@ -3486,28 +3449,24 @@ pub const Expect = struct { substring.ensureStillAlive(); if (!substring.isString()) { - globalThis.throw("toIncludeRepeated() requires the first argument to be a string", .{}); - return .zero; + return globalThis.throw("toIncludeRepeated() requires the first argument to be a string", .{}); } const count = arguments[1]; count.ensureStillAlive(); if (!count.isAnyInt()) { - globalThis.throw("toIncludeRepeated() requires the second argument to be a number", .{}); - return .zero; + return globalThis.throw("toIncludeRepeated() requires the second argument to be a number", .{}); } const countAsNum = count.toU32(); const expect_string = Expect.capturedValueGetCached(thisValue) orelse { - globalThis.throw("Internal consistency error: the expect(value) was garbage collected but it should not have been!", .{}); - return .zero; + return globalThis.throw("Internal consistency error: the expect(value) was garbage collected but it should not have been!", .{}); }; if (!expect_string.isString()) { - globalThis.throw("toIncludeRepeated() requires the expect(value) to be a string", .{}); - return .zero; + return globalThis.throw("toIncludeRepeated() requires the expect(value) to be a string", .{}); } const not = this.flags.not; @@ -3525,8 +3484,7 @@ pub const Expect = struct { const subStringAsStr = _subStringAsStr.slice(); if (subStringAsStr.len == 0) { - globalThis.throw("toIncludeRepeated() requires the first argument to be a non-empty string", .{}); - return .zero; + return globalThis.throw("toIncludeRepeated() requires the first argument to be a non-empty string", .{}); } if (countAsNum == 0) @@ -3592,21 +3550,18 @@ pub const Expect = struct { predicate.ensureStillAlive(); if (!predicate.isCallable(globalThis.vm())) { - globalThis.throw("toSatisfy() argument must be a function", .{}); - return .zero; + return globalThis.throw("toSatisfy() argument must be a function", .{}); } const value = Expect.capturedValueGetCached(thisValue) orelse { - globalThis.throw("Internal consistency error: the expect(value) was garbage collected but it should not have been!", .{}); - return .zero; + return globalThis.throw("Internal consistency error: the expect(value) was garbage collected but it should not have been!", .{}); }; value.ensureStillAlive(); const result = predicate.call(globalThis, .undefined, &.{value}) catch |e| { const err = globalThis.takeException(e); const fmt = ZigString.init("toSatisfy() predicate threw an exception"); - globalThis.vm().throwError(globalThis, globalThis.createAggregateError(&.{err}, &fmt)); - return .zero; + return globalThis.throwValue(globalThis.createAggregateError(&.{err}, &fmt)); }; const not = this.flags.not; @@ -3644,8 +3599,7 @@ pub const Expect = struct { expected.ensureStillAlive(); if (!expected.isString()) { - globalThis.throw("toStartWith() requires the first argument to be a string", .{}); - return .zero; + return globalThis.throw("toStartWith() requires the first argument to be a string", .{}); } const value: JSValue = try this.getValue(globalThis, thisValue, "toStartWith", "expected"); @@ -3698,8 +3652,7 @@ pub const Expect = struct { expected.ensureStillAlive(); if (!expected.isString()) { - globalThis.throw("toEndWith() requires the first argument to be a string", .{}); - return .zero; + return globalThis.throw("toEndWith() requires the first argument to be a string", .{}); } const value: JSValue = try this.getValue(globalThis, thisValue, "toEndWith", "expected"); @@ -3753,8 +3706,7 @@ pub const Expect = struct { const expected_value = arguments[0]; if (!expected_value.isConstructor()) { - globalThis.throw("Expected value must be a function: {any}", .{expected_value.toFmt(&formatter)}); - return .zero; + return globalThis.throw("Expected value must be a function: {any}", .{expected_value.toFmt(&formatter)}); } expected_value.ensureStillAlive(); @@ -3800,16 +3752,14 @@ pub const Expect = struct { const expected_value = arguments[0]; if (!expected_value.isString() and !expected_value.isRegExp()) { - globalThis.throw("Expected value must be a string or regular expression: {any}", .{expected_value.toFmt(&formatter)}); - return .zero; + return globalThis.throw("Expected value must be a string or regular expression: {any}", .{expected_value.toFmt(&formatter)}); } expected_value.ensureStillAlive(); const value: JSValue = try this.getValue(globalThis, thisValue, "toMatch", "expected"); if (!value.isString()) { - globalThis.throw("Received value must be a string: {any}", .{value.toFmt(&formatter)}); - return .zero; + return globalThis.throw("Received value must be a string: {any}", .{value.toFmt(&formatter)}); } const not = this.flags.not; @@ -3853,8 +3803,7 @@ pub const Expect = struct { incrementExpectCallCounter(); if (calls == .zero or !calls.jsType().isArray()) { - globalThis.throw("Expected value must be a mock function: {}", .{value}); - return .zero; + return globalThis.throw("Expected value must be a mock function: {}", .{value}); } var pass = calls.getLength(globalThis) > 0; @@ -3887,8 +3836,7 @@ pub const Expect = struct { const calls = JSMockFunction__getCalls(value); if (calls == .zero or !calls.jsType().isArray()) { - globalThis.throw("Expected value must be a mock function: {}", .{value}); - return .zero; + return globalThis.throw("Expected value must be a mock function: {}", .{value}); } if (arguments.len < 1 or !arguments[0].isUInt32AsAnyInt()) { @@ -3984,8 +3932,7 @@ pub const Expect = struct { const calls = JSMockFunction__getCalls(value); if (calls == .zero or !calls.jsType().isArray()) { - globalThis.throw("Expected value must be a mock function: {}", .{value}); - return .zero; + return globalThis.throw("Expected value must be a mock function: {}", .{value}); } var pass = false; @@ -3994,8 +3941,7 @@ pub const Expect = struct { var itr = calls.arrayIterator(globalThis); while (itr.next()) |callItem| { if (callItem == .zero or !callItem.jsType().isArray()) { - globalThis.throw("Expected value must be a mock function with calls: {}", .{value}); - return .zero; + return globalThis.throw("Expected value must be a mock function with calls: {}", .{value}); } if (callItem.getLength(globalThis) != arguments.len) { @@ -4045,8 +3991,7 @@ pub const Expect = struct { const calls = JSMockFunction__getCalls(value); if (calls == .zero or !calls.jsType().isArray()) { - globalThis.throw("Expected value must be a mock function: {}", .{value}); - return .zero; + return globalThis.throw("Expected value must be a mock function: {}", .{value}); } const totalCalls = @as(u32, @intCast(calls.getLength(globalThis))); @@ -4058,8 +4003,7 @@ pub const Expect = struct { lastCallValue = calls.getIndex(globalThis, totalCalls - 1); if (lastCallValue == .zero or !lastCallValue.jsType().isArray()) { - globalThis.throw("Expected value must be a mock function with calls: {}", .{value}); - return .zero; + return globalThis.throw("Expected value must be a mock function with calls: {}", .{value}); } if (lastCallValue.getLength(globalThis) != arguments.len) { @@ -4105,8 +4049,7 @@ pub const Expect = struct { const calls = JSMockFunction__getCalls(value); if (calls == .zero or !calls.jsType().isArray()) { - globalThis.throw("Expected value must be a mock function: {}", .{value}); - return .zero; + return globalThis.throw("Expected value must be a mock function: {}", .{value}); } const nthCallNum = if (arguments.len > 0 and arguments[0].isUInt32AsAnyInt()) arguments[0].coerce(i32, globalThis) else 0; @@ -4123,8 +4066,7 @@ pub const Expect = struct { nthCallValue = calls.getIndex(globalThis, @as(u32, @intCast(nthCallNum)) - 1); if (nthCallValue == .zero or !nthCallValue.jsType().isArray()) { - globalThis.throw("Expected value must be a mock function with calls: {}", .{value}); - return .zero; + return globalThis.throw("Expected value must be a mock function with calls: {}", .{value}); } if (nthCallValue.getLength(globalThis) != (arguments.len - 1)) { @@ -4181,8 +4123,7 @@ pub const Expect = struct { const returns = JSMockFunction__getReturns(value); if (returns == .zero or !returns.jsType().isArray()) { - globalThis.throw("Expected value must be a mock function: {}", .{value}); - return .zero; + return globalThis.throw("Expected value must be a mock function: {}", .{value}); } const return_count: i32 = if (known_index) |index| index else brk: { @@ -4213,7 +4154,7 @@ pub const Expect = struct { if (type_string.isString()) { break :brk ReturnStatus.Map.fromJS(globalThis, type_string) orelse { if (!globalThis.hasException()) - globalThis.throw("Expected value must be a mock function with returns: {}", .{value}); + return globalThis.throw("Expected value must be a mock function with returns: {}", .{value}); return .zero; }; } @@ -4396,7 +4337,7 @@ pub const Expect = struct { } }; - fn throwInvalidMatcherError(globalThis: *JSGlobalObject, matcher_name: bun.String, result: JSValue) void { + fn throwInvalidMatcherError(globalThis: *JSGlobalObject, matcher_name: bun.String, result: JSValue) bun.JSError { @setCold(true); var formatter = JSC.ConsoleObject.Formatter{ @@ -4413,24 +4354,21 @@ pub const Expect = struct { inline else => |colors| globalThis.createErrorInstance(Output.prettyFmt(fmt, colors), .{ matcher_name, result.toFmt(&formatter) }), }; err.put(globalThis, ZigString.static("name"), bun.String.static("InvalidMatcherError").toJS(globalThis)); - globalThis.throwValue(err); + return globalThis.throwValue(err); } /// Execute the custom matcher for the given args (the left value + the args passed to the matcher call). /// This function is called both for symmetric and asymmetric matching. /// If silent=false, throws an exception in JS if the matcher result didn't result in a pass (or if the matcher result is invalid). - pub fn executeCustomMatcher(globalThis: *JSGlobalObject, matcher_name: bun.String, matcher_fn: JSValue, args: []const JSValue, flags: Expect.Flags, silent: bool) bool { + pub fn executeCustomMatcher(globalThis: *JSGlobalObject, matcher_name: bun.String, matcher_fn: JSValue, args: []const JSValue, flags: Expect.Flags, silent: bool) bun.JSError!bool { // prepare the this object - const matcher_context = globalThis.bunVM().allocator.create(ExpectMatcherContext) catch { - globalThis.throwOutOfMemory() catch {}; // TODO: properly propagate exception upwards - return false; - }; + const matcher_context = try globalThis.bunVM().allocator.create(ExpectMatcherContext); matcher_context.flags = flags; const matcher_context_jsvalue = matcher_context.toJS(globalThis); matcher_context_jsvalue.ensureStillAlive(); // call the custom matcher implementation - var result = matcher_fn.call(globalThis, matcher_context_jsvalue, args) catch return false; + var result = try matcher_fn.call(globalThis, matcher_context_jsvalue, args); // support for async matcher results if (result.asAnyPromise()) |promise| { const vm = globalThis.vm(); @@ -4447,8 +4385,7 @@ pub const Expect = struct { .rejected => { // TODO: rewrite this code to use .then() instead of blocking the event loop JSC.VirtualMachine.get().runErrorHandler(result, null); - globalThis.throw("Matcher `{s}` returned a promise that rejected", .{matcher_name}); - return false; + return globalThis.throw("Matcher `{s}` returned a promise that rejected", .{matcher_name}); }, } } @@ -4459,7 +4396,7 @@ pub const Expect = struct { // Parse and validate the custom matcher result, which should conform to: { pass: boolean, message?: () => string } const is_valid = valid: { if (result.isObject()) { - if (result.get(globalThis, "pass") catch return false) |pass_value| { + if (try result.get(globalThis, "pass")) |pass_value| { pass = pass_value.toBoolean(); if (globalThis.hasException()) return false; @@ -4478,8 +4415,7 @@ pub const Expect = struct { break :valid false; }; if (!is_valid) { - throwInvalidMatcherError(globalThis, matcher_name, result); - return false; + return throwInvalidMatcherError(globalThis, matcher_name, result); } if (flags.not) pass = !pass; @@ -4496,21 +4432,8 @@ pub const Expect = struct { if (comptime Environment.allow_assert) assert(message.isCallable(globalThis.vm())); // checked above - const message_result = message.callWithGlobalThis(globalThis, &.{}) catch return false; - if (bun.String.tryFromJS(message_result, globalThis)) |str| { - message_text = str; - } else { - if (globalThis.hasException()) return false; - var formatter = JSC.ConsoleObject.Formatter{ - .globalThis = globalThis, - .quote_strings = true, - }; - globalThis.throw( - "Expected custom matcher message to return a string, but got: {}", - .{message_result.toFmt(&formatter)}, - ); - return false; - } + const message_result = try message.callWithGlobalThis(globalThis, &.{}); + message_text = try bun.String.fromJS2(message_result, globalThis); } const matcher_params = CustomMatcherParamsFormatter{ @@ -4518,8 +4441,7 @@ pub const Expect = struct { .globalThis = globalThis, .matcher_fn = matcher_fn, }; - throwPrettyMatcherError(globalThis, bun.String.empty, matcher_name, matcher_params, .{}, "{s}", .{message_text}) catch {}; - return false; + return throwPrettyMatcherError(globalThis, bun.String.empty, matcher_name, matcher_params, .{}, "{s}", .{message_text}); } /// Function that is run for either `expect.myMatcher()` call or `expect().myMatcher` call, @@ -4531,8 +4453,7 @@ pub const Expect = struct { const func: JSValue = callFrame.callee(); var matcher_fn = getCustomMatcherFn(func, globalThis) orelse JSValue.undefined; if (!matcher_fn.jsType().isFunction()) { - globalThis.throw("Internal consistency error: failed to retrieve the matcher function for a custom matcher!", .{}); - return .zero; + return globalThis.throw("Internal consistency error: failed to retrieve the matcher function for a custom matcher!", .{}); } matcher_fn.ensureStillAlive(); @@ -4557,8 +4478,7 @@ pub const Expect = struct { // retrieve the captured expected value var value = Expect.capturedValueGetCached(thisValue) orelse { - globalThis.throw("Internal consistency error: failed to retrieve the captured value", .{}); - return .zero; + return globalThis.throw("Internal consistency error: failed to retrieve the captured value", .{}); }; value = try Expect.processPromise(expect.custom_label, expect.flags, globalThis, value, matcher_name, matcher_params, false); value.ensureStillAlive(); @@ -4573,10 +4493,7 @@ pub const Expect = struct { matcher_args.appendAssumeCapacity(value); for (0..args_count) |i| matcher_args.appendAssumeCapacity(args_ptr[i]); - // call the matcher, which will throw a js exception when failed - if (!executeCustomMatcher(globalThis, matcher_name, matcher_fn, matcher_args.items, expect.flags, false) or globalThis.hasException()) { - return .zero; - } + _ = try executeCustomMatcher(globalThis, matcher_name, matcher_fn, matcher_args.items, expect.flags, false); return thisValue; } @@ -4606,15 +4523,13 @@ pub const Expect = struct { if (!expected.isNumber()) { var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; - globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); - return .zero; + return globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); } const expected_assertions: f64 = expected.coerceToDouble(globalThis); if (@round(expected_assertions) != expected_assertions or std.math.isInf(expected_assertions) or std.math.isNan(expected_assertions) or expected_assertions < 0 or expected_assertions > std.math.maxInt(u32)) { var fmt = JSC.ConsoleObject.Formatter{ .globalThis = globalThis, .quote_strings = true }; - globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); - return .zero; + return globalThis.throw("Expected value must be a non-negative integer: {any}", .{expected.toFmt(&fmt)}); } const unsigned_expected_assertions: u32 = @intFromFloat(expected_assertions); @@ -4626,23 +4541,19 @@ pub const Expect = struct { } pub fn notImplementedJSCFn(_: *Expect, globalThis: *JSGlobalObject, _: *CallFrame) bun.JSError!JSValue { - globalThis.throw("Not implemented", .{}); - return .zero; + return globalThis.throw("Not implemented", .{}); } pub fn notImplementedStaticFn(globalThis: *JSGlobalObject, _: *CallFrame) bun.JSError!JSValue { - globalThis.throw("Not implemented", .{}); - return .zero; + return globalThis.throw("Not implemented", .{}); } - pub fn notImplementedJSCProp(_: *Expect, _: JSValue, globalThis: *JSGlobalObject) JSValue { - globalThis.throw("Not implemented", .{}); - return .zero; + pub fn notImplementedJSCProp(_: *Expect, _: JSValue, globalThis: *JSGlobalObject) bun.JSError!JSValue { + return globalThis.throw("Not implemented", .{}); } - pub fn notImplementedStaticProp(globalThis: *JSGlobalObject, _: JSValue, _: JSValue) JSValue { - globalThis.throw("Not implemented", .{}); - return .zero; + pub fn notImplementedStaticProp(globalThis: *JSGlobalObject, _: JSValue, _: JSValue) bun.JSError!JSValue { + return globalThis.throw("Not implemented", .{}); } pub fn postMatch(_: *Expect, globalThis: *JSGlobalObject) void { @@ -4656,19 +4567,16 @@ pub const Expect = struct { if (arg.isEmptyOrUndefinedOrNull()) { const error_value = bun.String.init("reached unreachable code").toErrorInstance(globalThis); error_value.put(globalThis, ZigString.static("name"), bun.String.init("UnreachableError").toJS(globalThis)); - globalThis.throwValue(error_value); - return .zero; + return globalThis.throwValue(error_value); } if (arg.isString()) { const error_value = arg.toBunString(globalThis).toErrorInstance(globalThis); error_value.put(globalThis, ZigString.static("name"), bun.String.init("UnreachableError").toJS(globalThis)); - globalThis.throwValue(error_value); - return .zero; + return globalThis.throwValue(error_value); } - globalThis.throwValue(arg); - return .zero; + return globalThis.throwValue(arg); } }; @@ -4704,27 +4612,26 @@ pub const ExpectStatic = struct { pub fn getResolvesTo(this: *ExpectStatic, _: JSValue, globalThis: *JSGlobalObject) JSValue { var flags = this.flags; - if (flags.promise != .none) return asyncChainingError(globalThis, flags, "resolvesTo"); + if (flags.promise != .none) return asyncChainingError(globalThis, flags, "resolvesTo") catch .zero; flags.promise = .resolves; return create(globalThis, flags); } pub fn getRejectsTo(this: *ExpectStatic, _: JSValue, globalThis: *JSGlobalObject) JSValue { var flags = this.flags; - if (flags.promise != .none) return asyncChainingError(globalThis, flags, "rejectsTo"); + if (flags.promise != .none) return asyncChainingError(globalThis, flags, "rejectsTo") catch .zero; flags.promise = .rejects; return create(globalThis, flags); } - fn asyncChainingError(globalThis: *JSGlobalObject, flags: Expect.Flags, name: string) JSValue { + fn asyncChainingError(globalThis: *JSGlobalObject, flags: Expect.Flags, name: string) bun.JSError!JSValue { @setCold(true); const str = switch (flags.promise) { .resolves => "resolvesTo", .rejects => "rejectsTo", else => unreachable, }; - globalThis.throw("expect.{s}: already called expect.{s} on this chain", .{ name, str }); - return .zero; + return globalThis.throw("expect.{s}: already called expect.{s} on this chain", .{ name, str }); } fn createAsymmetricMatcherWithFlags(T: type, this: *ExpectStatic, globalThis: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue { @@ -4948,7 +4855,7 @@ pub const ExpectAny = struct { const arguments: []const JSValue = _arguments.ptr[0.._arguments.len]; if (arguments.len == 0) { - return globalThis.throw2("any() expects to be passed a constructor function. Please pass one or use anything() to match any object.", .{}); + return globalThis.throw("any() expects to be passed a constructor function. Please pass one or use anything() to match any object.", .{}); } const constructor = arguments[0]; @@ -5077,12 +4984,12 @@ pub const ExpectCustomAsymmetricMatcher = struct { pub fn execute(this: *ExpectCustomAsymmetricMatcher, thisValue: JSValue, globalThis: *JSGlobalObject, received: JSValue) callconv(.C) bool { // retrieve the user-provided matcher implementation function (the function passed to expect.extend({ ... })) const matcher_fn: JSValue = ExpectCustomAsymmetricMatcher.matcherFnGetCached(thisValue) orelse { - globalThis.throw("Internal consistency error: the ExpectCustomAsymmetricMatcher(matcherFn) was garbage collected but it should not have been!", .{}); + globalThis.throw("Internal consistency error: the ExpectCustomAsymmetricMatcher(matcherFn) was garbage collected but it should not have been!", .{}) catch {}; return false; }; matcher_fn.ensureStillAlive(); if (!matcher_fn.jsType().isFunction()) { - globalThis.throw("Internal consistency error: the ExpectCustomMatcher(matcherFn) is not a function!", .{}); + globalThis.throw("Internal consistency error: the ExpectCustomMatcher(matcherFn) is not a function!", .{}) catch {}; return false; } @@ -5092,7 +4999,7 @@ pub const ExpectCustomAsymmetricMatcher = struct { // retrieve the asymmetric matcher args // if null, it means the function has not yet been called to capture the args, which is a misuse of the matcher const captured_args: JSValue = ExpectCustomAsymmetricMatcher.capturedArgsGetCached(thisValue) orelse { - globalThis.throw("expect.{s} misused, it needs to be instantiated by calling it with 0 or more arguments", .{matcher_name}); + globalThis.throw("expect.{s} misused, it needs to be instantiated by calling it with 0 or more arguments", .{matcher_name}) catch {}; return false; }; captured_args.ensureStillAlive(); @@ -5101,7 +5008,7 @@ pub const ExpectCustomAsymmetricMatcher = struct { const args_count = captured_args.getLength(globalThis); var allocator = std.heap.stackFallback(8 * @sizeOf(JSValue), globalThis.allocator()); var matcher_args = std.ArrayList(JSValue).initCapacity(allocator.get(), args_count + 1) catch { - globalThis.throwOutOfMemory() catch {}; // TODO: properly propagate exception upwards + globalThis.throwOutOfMemory() catch {}; return false; }; matcher_args.appendAssumeCapacity(received); @@ -5109,7 +5016,7 @@ pub const ExpectCustomAsymmetricMatcher = struct { matcher_args.appendAssumeCapacity(captured_args.getIndex(globalThis, @truncate(i))); } - return Expect.executeCustomMatcher(globalThis, matcher_name, matcher_fn, matcher_args.items, this.flags, true); + return Expect.executeCustomMatcher(globalThis, matcher_name, matcher_fn, matcher_args.items, this.flags, true) catch false; } pub fn asymmetricMatch(this: *ExpectCustomAsymmetricMatcher, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { @@ -5196,8 +5103,7 @@ pub const ExpectMatcherContext = struct { pub fn equals(_: *ExpectMatcherContext, globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { var arguments = callframe.arguments_old(3); if (arguments.len < 2) { - globalThis.throw("expect.extends matcher: this.util.equals expects at least 2 arguments", .{}); - return .zero; + return globalThis.throw("expect.extends matcher: this.util.equals expects at least 2 arguments", .{}); } const args = arguments.slice(); return JSValue.jsBoolean(try args[0].jestDeepEquals(args[1], globalThis)); @@ -5282,8 +5188,7 @@ pub const ExpectMatcherUtils = struct { const arguments = callframe.arguments_old(4).slice(); if (arguments.len == 0 or !arguments[0].isString()) { - globalThis.throw("matcherHint: the first argument (matcher name) must be a string", .{}); - return .zero; + return globalThis.throw("matcherHint: the first argument (matcher name) must be a string", .{}); } const matcher_name = arguments[0].toBunString(globalThis); defer matcher_name.deref(); @@ -5303,8 +5208,7 @@ pub const ExpectMatcherUtils = struct { if (!options.isUndefinedOrNull()) { if (!options.isObject()) { - globalThis.throw("matcherHint: options must be an object (or undefined)", .{}); - return .zero; + return globalThis.throw("matcherHint: options must be an object (or undefined)", .{}); } if (try options.get(globalThis, "isNot")) |val| { is_not = val.coerce(bool, globalThis); diff --git a/src/bun.js/test/jest.zig b/src/bun.js/test/jest.zig index 26af8a98481275..4be73143aa7ef1 100644 --- a/src/bun.js/test/jest.zig +++ b/src/bun.js/test/jest.zig @@ -281,7 +281,7 @@ pub const Jest = struct { return struct { pub fn appendGlobalFunctionCallback(globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { const the_runner = runner orelse { - return globalThis.throw2("Cannot use " ++ name ++ "() outside of the test runner. Run \"bun test\" to run tests.", .{}); + return globalThis.throw("Cannot use " ++ name ++ "() outside of the test runner. Run \"bun test\" to run tests.", .{}); }; const arguments = callframe.arguments_old(2); @@ -291,12 +291,11 @@ pub const Jest = struct { const function = arguments.ptr[0]; if (function.isEmptyOrUndefinedOrNull() or !function.isCallable(globalThis.vm())) { - globalThis.throwInvalidArgumentType(name, "callback", "function"); - return error.JSError; + return globalThis.throwInvalidArgumentType(name, "callback", "function"); } if (function.getLength(globalThis) > 0) { - return globalThis.throw2("done() callback is not implemented in global hooks yet. Please make your function take no arguments", .{}); + return globalThis.throw("done() callback is not implemented in global hooks yet. Please make your function take no arguments", .{}); } function.protect(); @@ -527,16 +526,14 @@ pub const Jest = struct { const arguments = callframe.arguments_old(2).slice(); if (arguments.len < 1 or !arguments[0].isString()) { - globalObject.throw("Bun.jest() expects a string filename", .{}); - return .zero; + return globalObject.throw("Bun.jest() expects a string filename", .{}); } var str = arguments[0].toSlice(globalObject, bun.default_allocator); defer str.deinit(); const slice = str.slice(); if (!std.fs.path.isAbsolute(slice)) { - globalObject.throw("Bun.jest() expects an absolute file path, got '{s}'", .{slice}); - return .zero; + return globalObject.throw("Bun.jest() expects an absolute file path, got '{s}'", .{slice}); } const filepath = Fs.FileSystem.instance.filename_store.append([]const u8, slice) catch unreachable; @@ -549,8 +546,7 @@ pub const Jest = struct { fn jsSetDefaultTimeout(globalObject: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { const arguments = callframe.arguments_old(1).slice(); if (arguments.len < 1 or !arguments[0].isNumber()) { - globalObject.throw("setTimeout() expects a number (milliseconds)", .{}); - return .zero; + return globalObject.throw("setTimeout() expects a number (milliseconds)", .{}); } const timeout_ms: u32 = @intCast(@max(arguments[0].coerce(i32, globalObject), 0)); @@ -902,8 +898,7 @@ pub const DescribeScope = struct { const cb = arguments.ptr[0]; if (!cb.isObject() or !cb.isCallable(globalThis.vm())) { - globalThis.throwInvalidArgumentType(@tagName(hook), "callback", "function"); - return error.JSError; + return globalThis.throwInvalidArgumentType(@tagName(hook), "callback", "function"); } cb.protect(); @@ -1234,12 +1229,10 @@ pub fn wrapTestFunction(comptime name: []const u8, comptime func: JSC.JSHostZigF return struct { pub fn wrapped(globalThis: *JSGlobalObject, callframe: *CallFrame) bun.JSError!JSValue { if (Jest.runner == null) { - globalThis.throw("Cannot use " ++ name ++ "() outside of the test runner. Run \"bun test\" to run tests.", .{}); - return .zero; + return globalThis.throw("Cannot use " ++ name ++ "() outside of the test runner. Run \"bun test\" to run tests.", .{}); } if (globalThis.bunVM().is_in_preload) { - globalThis.throw("Cannot use " ++ name ++ "() outside of a test file.", .{}); - return .zero; + return globalThis.throw("Cannot use " ++ name ++ "() outside of a test file.", .{}); } return @call(bun.callmod_inline, func, .{ globalThis, callframe }); } diff --git a/src/bun.js/webcore.zig b/src/bun.js/webcore.zig index 9f62705280f169..3484590697b8c3 100644 --- a/src/bun.js/webcore.zig +++ b/src/bun.js/webcore.zig @@ -376,17 +376,14 @@ pub const Crypto = struct { if (keylen_value.isEmptyOrUndefinedOrNull() or !keylen_value.isAnyInt()) { const err = globalThis.createInvalidArgs("keylen must be an integer", .{}); - globalThis.throwValue(err); - return .zero; + return globalThis.throwValue(err); } const keylen_int = keylen_value.to(i64); if (keylen_int < 0) { - globalThis.throwValue(globalThis.createRangeError("keylen must be a positive integer", .{})); - return .zero; + return globalThis.throwValue(globalThis.createRangeError("keylen must be a positive integer", .{})); } else if (keylen_int > 0x7fffffff) { - globalThis.throwValue(globalThis.createRangeError("keylen must be less than 2^31", .{})); - return .zero; + return globalThis.throwValue(globalThis.createRangeError("keylen must be less than 2^31", .{})); } var blockSize: ?usize = null; @@ -400,8 +397,7 @@ pub const Crypto = struct { break :outer; if (!options_value.isObject()) { - globalThis.throwValue(globalThis.createInvalidArgs("options must be an object", .{})); - return .zero; + return globalThis.throwValue(globalThis.createInvalidArgs("options must be an object", .{})); } if (try options_value.getTruthy(globalThis, "cost") orelse try options_value.getTruthy(globalThis, "N")) |N_value| { @@ -507,8 +503,7 @@ pub const Crypto = struct { if (keylen > buf.len) { // i don't think its a real scenario, but just in case buf = globalThis.allocator().alloc(u8, keylen) catch { - globalThis.throw("Failed to allocate memory", .{}); - return .zero; + return globalThis.throw("Failed to allocate memory", .{}); }; needs_deinit = true; } else { @@ -533,16 +528,14 @@ pub const Crypto = struct { return JSC.ArrayBuffer.create(globalThis, buf, .ArrayBuffer); } - fn throwInvalidParameter(globalThis: *JSC.JSGlobalObject) JSC.JSValue { - globalThis.ERR_CRYPTO_SCRYPT_INVALID_PARAMETER("Invalid scrypt parameters", .{}).throw(); - return .zero; + fn throwInvalidParameter(globalThis: *JSC.JSGlobalObject) bun.JSError { + return globalThis.ERR_CRYPTO_SCRYPT_INVALID_PARAMETER("Invalid scrypt parameters", .{}).throw(); } - fn throwInvalidParams(globalThis: *JSC.JSGlobalObject, comptime error_type: @Type(.EnumLiteral), comptime message: [:0]const u8, fmt: anytype) JSC.JSValue { + fn throwInvalidParams(globalThis: *JSC.JSGlobalObject, comptime error_type: @Type(.EnumLiteral), comptime message: [:0]const u8, fmt: anytype) bun.JSError { if (error_type != .RangeError) @compileError("Error type not added!"); - globalThis.ERR_CRYPTO_INVALID_SCRYPT_PARAMS(message, fmt).throw(); BoringSSL.ERR_clear_error(); - return .zero; + return globalThis.ERR_CRYPTO_INVALID_SCRYPT_PARAMS(message, fmt).throw(); } pub fn timingSafeEqual(_: *@This(), globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { @@ -564,8 +557,7 @@ pub const Crypto = struct { const len = a.len; if (b.len != len) { - globalThis.throw("Input buffers must have the same byte length", .{}); - return .zero; + return globalThis.throw("Input buffers must have the same byte length", .{}); } return JSC.jsBoolean(len == 0 or bun.BoringSSL.CRYPTO_memcmp(a.ptr, b.ptr, len) == 0); } @@ -581,8 +573,7 @@ pub const Crypto = struct { const len = a.len; if (b.len != len) { - globalThis.throw("Input buffers must have the same byte length", .{}); - return .zero; + return globalThis.throw("Input buffers must have the same byte length", .{}); } return JSC.jsBoolean(len == 0 or bun.BoringSSL.CRYPTO_memcmp(a.ptr, b.ptr, len) == 0); @@ -666,8 +657,7 @@ pub const Crypto = struct { if (arguments[0].isString()) { encoding_value = arguments[0]; break :brk JSC.Node.Encoding.fromJS(encoding_value, globalThis) orelse { - globalThis.ERR_UNKNOWN_ENCODING("Encoding must be one of base64, base64url, hex, or buffer", .{}).throw(); - return .zero; + return globalThis.ERR_UNKNOWN_ENCODING("Encoding must be one of base64, base64url, hex, or buffer", .{}).throw(); }; } } @@ -724,7 +714,7 @@ pub const Crypto = struct { } pub fn constructor(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) bun.JSError!*Crypto { - return globalThis.throw2("Crypto is not constructable", .{}); + return globalThis.throw("Crypto is not constructable", .{}); } pub export fn CryptoObject__create(globalThis: *JSC.JSGlobalObject) JSC.JSValue { diff --git a/src/bun.js/webcore/blob.zig b/src/bun.js/webcore/blob.zig index 5ab0caa5965abc..9c1467bf5d8c0d 100644 --- a/src/bun.js/webcore/blob.zig +++ b/src/bun.js/webcore/blob.zig @@ -279,7 +279,7 @@ pub const Blob = struct { switch (res) { .err => |err| { - globalThis.throwValue(err.toJSC(globalThis)); + globalThis.throwValue(err.toJSC(globalThis)) catch {}; this.failed = true; }, .result => |result| { @@ -511,22 +511,17 @@ pub const Blob = struct { return blob.toJS(globalThis); } - pub fn onStructuredCloneDeserialize( - globalThis: *JSC.JSGlobalObject, - ptr: [*]u8, - end: [*]u8, - ) JSValue { + pub fn onStructuredCloneDeserialize(globalThis: *JSC.JSGlobalObject, ptr: [*]u8, end: [*]u8) bun.JSError!JSValue { const total_length: usize = @intFromPtr(end) - @intFromPtr(ptr); var buffer_stream = std.io.fixedBufferStream(ptr[0..total_length]); const reader = buffer_stream.reader(); return _onStructuredCloneDeserialize(globalThis, @TypeOf(reader), reader) catch |err| switch (err) { error.EndOfStream, error.TooSmall, error.InvalidValue => { - globalThis.throw("Blob.onStructuredCloneDeserialize failed", .{}); - return .zero; + return globalThis.throw("Blob.onStructuredCloneDeserialize failed", .{}); }, error.OutOfMemory => { - return globalThis.throwOutOfMemoryValue(); + return globalThis.throwOutOfMemory(); }, }; } @@ -1011,14 +1006,12 @@ pub const Blob = struct { if (options_object.isObject()) { if (try options_object.getTruthy(globalThis, "createPath")) |create_directory| { if (!create_directory.isBoolean()) { - globalThis.throwInvalidArgumentType("write", "options.createPath", "boolean"); - return .zero; + return globalThis.throwInvalidArgumentType("write", "options.createPath", "boolean"); } mkdirp_if_not_exists = create_directory.toBoolean(); } } else if (!options_object.isEmptyOrUndefinedOrNull()) { - globalThis.throwInvalidArgumentType("write", "options", "object"); - return .zero; + return globalThis.throwInvalidArgumentType("write", "options", "object"); } } @@ -3474,7 +3467,7 @@ pub const Blob = struct { break :brk result; }, .err => |err| { - return globalThis.throwValue2(err.withPath(path).toJSC(globalThis)); + return globalThis.throwValue(err.withPath(path).toJSC(globalThis)); }, } unreachable; @@ -3507,7 +3500,7 @@ pub const Blob = struct { switch (sink.writer.startSync(fd, false)) { .err => |err| { sink.deref(); - return globalThis.throwValue2(err.toJSC(globalThis)); + return globalThis.throwValue(err.toJSC(globalThis)); }, else => {}, } @@ -3515,7 +3508,7 @@ pub const Blob = struct { switch (sink.writer.start(fd, true)) { .err => |err| { sink.deref(); - return globalThis.throwValue2(err.toJSC(globalThis)); + return globalThis.throwValue(err.toJSC(globalThis)); }, else => {}, } @@ -3555,7 +3548,7 @@ pub const Blob = struct { switch (sink.start(stream_start)) { .err => |err| { sink.deref(); - return globalThis.vm().throwError2(globalThis, err.toJSC(globalThis)); + return globalThis.throwValue(err.toJSC(globalThis)); }, else => {}, } diff --git a/src/bun.js/webcore/body.zig b/src/bun.js/webcore/body.zig index a90ca2a0ad198a..89c2e4cf9d92be 100644 --- a/src/bun.js/webcore/body.zig +++ b/src/bun.js/webcore/body.zig @@ -576,7 +576,7 @@ pub const Body = struct { .InternalBlob = .{ .bytes = std.ArrayList(u8){ .items = bun.default_allocator.dupe(u8, bytes) catch { - return globalThis.vm().throwError2(globalThis, ZigString.static("Failed to clone ArrayBufferView").toErrorInstance(globalThis)); + return globalThis.throwValue(ZigString.static("Failed to clone ArrayBufferView").toErrorInstance(globalThis)); }, .capacity = bytes.len, .allocator = bun.default_allocator, @@ -611,7 +611,7 @@ pub const Body = struct { if (JSC.WebCore.ReadableStream.fromJS(value, globalThis)) |readable| { if (readable.isDisturbed(globalThis)) { - return globalThis.throw2("ReadableStream has already been used", .{}); + return globalThis.throw("ReadableStream has already been used", .{}); } switch (readable.ptr) { diff --git a/src/bun.js/webcore/encoding.zig b/src/bun.js/webcore/encoding.zig index 7071b92ea064e6..f50424ea35bc9a 100644 --- a/src/bun.js/webcore/encoding.zig +++ b/src/bun.js/webcore/encoding.zig @@ -832,8 +832,7 @@ pub const TextDecoder = struct { if (deinit) bun.default_allocator.free(input); if (comptime fail_if_invalid) { if (err == error.InvalidByteSequence) { - globalThis.ERR_ENCODING_INVALID_ENCODED_DATA("Invalid byte sequence", .{}).throw(); - return error.JSError; + return globalThis.ERR_ENCODING_INVALID_ENCODED_DATA("Invalid byte sequence", .{}).throw(); } } @@ -872,8 +871,7 @@ pub const TextDecoder = struct { 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 error.JSError; + return globalThis.ERR_ENCODING_INVALID_ENCODED_DATA("The encoded data was not valid {s} data", .{@tagName(utf16_encoding)}).throw(); } var output = bun.String.fromUTF16(decoded.items); diff --git a/src/bun.js/webcore/request.zig b/src/bun.js/webcore/request.zig index f2c45d305a1283..6d745017ecd8b5 100644 --- a/src/bun.js/webcore/request.zig +++ b/src/bun.js/webcore/request.zig @@ -93,13 +93,9 @@ pub const Request = struct { this.request_context.enableTimeoutEvents(); } - pub export fn Request__setTimeout( - this: *Request, - seconds: JSC.JSValue, - globalThis: *JSC.JSGlobalObject, - ) void { + pub export fn Request__setTimeout(this: *Request, seconds: JSC.JSValue, globalThis: *JSC.JSGlobalObject) void { if (!seconds.isNumber()) { - globalThis.throw("Failed to set timeout: The provided value is not of type 'number'.", .{}); + globalThis.throw("Failed to set timeout: The provided value is not of type 'number'.", .{}) catch {}; return; } @@ -381,12 +377,9 @@ pub const Request = struct { ) JSC.JSValue { return ZigString.init("").toJS(globalThis); } - pub fn getUrl( - this: *Request, - globalObject: *JSC.JSGlobalObject, - ) JSC.JSValue { + pub fn getUrl(this: *Request, globalObject: *JSC.JSGlobalObject) JSC.JSValue { this.ensureURL() catch { - globalObject.throw("Failed to join URL", .{}); + globalObject.throw("Failed to join URL", .{}) catch {}; // TODO: propagate return .zero; }; @@ -542,9 +535,9 @@ pub const Request = struct { } if (arguments.len == 0) { - return globalThis.throw2("Failed to construct 'Request': 1 argument required, but only 0 present.", .{}); + return globalThis.throw("Failed to construct 'Request': 1 argument required, but only 0 present.", .{}); } else if (arguments[0].isEmptyOrUndefinedOrNull() or !arguments[0].isCell()) { - return globalThis.throw2("Failed to construct 'Request': expected non-empty string or object, got undefined", .{}); + return globalThis.throw("Failed to construct 'Request': expected non-empty string or object, got undefined", .{}); } const url_or_object = arguments[0]; @@ -564,7 +557,7 @@ pub const Request = struct { if (!req.url.isEmpty()) fields.insert(.url); } else if (!url_or_object_type.isObject()) { - return globalThis.throw2("Failed to construct 'Request': expected non-empty string or object", .{}); + return globalThis.throw("Failed to construct 'Request': expected non-empty string or object", .{}); } const values_to_try_ = [_]JSValue{ @@ -686,7 +679,7 @@ pub const Request = struct { req.signal = signal.ref(); } else { if (!globalThis.hasException()) { - globalThis.throw("Failed to construct 'Request': signal is not of type AbortSignal.", .{}); + return globalThis.throw("Failed to construct 'Request': signal is not of type AbortSignal.", .{}); } return error.JSError; } @@ -729,7 +722,7 @@ pub const Request = struct { } if (req.url.isEmpty()) { - return globalThis.throw2("Failed to construct 'Request': url is required.", .{}); + return globalThis.throw("Failed to construct 'Request': url is required.", .{}); } const href = JSC.URL.hrefFromString(req.url); @@ -737,9 +730,7 @@ pub const Request = struct { if (!globalThis.hasException()) { // globalThis.throw can cause GC, which could cause the above string to be freed. // so we must increment the reference count before calling it. - globalThis.ERR_INVALID_URL("Failed to construct 'Request': Invalid URL \"{}\"", .{ - req.url, - }).throw(); + return globalThis.ERR_INVALID_URL("Failed to construct 'Request': Invalid URL \"{}\"", .{req.url}).throw(); } return error.JSError; } @@ -924,7 +915,7 @@ pub const Request = struct { const vm = globalThis.bunVM(); const body = vm.initRequestBodyValue(this.body.value.clone(globalThis)) catch { if (!globalThis.hasException()) { - globalThis.throw("Failed to clone request", .{}); + globalThis.throw("Failed to clone request", .{}) catch {}; } return; }; diff --git a/src/bun.js/webcore/response.zig b/src/bun.js/webcore/response.zig index acf8a0513f463a..30c4299d3ff3e5 100644 --- a/src/bun.js/webcore/response.zig +++ b/src/bun.js/webcore/response.zig @@ -633,7 +633,7 @@ pub const Response = struct { } else { if (!globalThis.hasException()) { const err = globalThis.createRangeErrorInstance("The status provided ({d}) must be 101 or in the range of [200, 599]", .{number}); - globalThis.throwValue(err); + return globalThis.throwValue(err); } return error.JSError; } @@ -1933,13 +1933,11 @@ pub const Fetch = struct { } if (url_str.tag == .Dead) { - globalObject.ERR_INVALID_ARG_TYPE("Invalid URL", .{}).throw(); - return .zero; + return globalObject.ERR_INVALID_ARG_TYPE("Invalid URL", .{}).throw(); } if (url_str.isEmpty()) { - globalObject.ERR_INVALID_ARG_TYPE(fetch_error_blank_url, .{}).throw(); - return .zero; + return globalObject.ERR_INVALID_ARG_TYPE(fetch_error_blank_url, .{}).throw(); } const url = ZigURL.parse(url_str.toOwnedSlice(bun.default_allocator) catch bun.outOfMemory()); @@ -1949,9 +1947,8 @@ pub const Fetch = struct { } if (url.hostname.len == 0) { - globalObject.ERR_INVALID_ARG_TYPE(fetch_error_blank_url, .{}).throw(); bun.default_allocator.free(url.href); - return .zero; + return globalObject.ERR_INVALID_ARG_TYPE(fetch_error_blank_url, .{}).throw(); } if (!url.hasValidPort()) { @@ -2575,9 +2572,7 @@ pub const Fetch = struct { if (request) |req| { if (req.body.value == .Used or (req.body.value == .Locked and (req.body.value.Locked.action != .none or req.body.value.Locked.isDisturbed(Request, globalThis, first_arg)))) { - globalThis.ERR_BODY_ALREADY_USED("Request body already used", .{}).throw(); - is_error = true; - return .zero; + return globalThis.ERR_BODY_ALREADY_USED("Request body already used", .{}).throw(); } break :extract_body req.body.value.useAsAnyBlob(); diff --git a/src/bun.js/webcore/streams.zig b/src/bun.js/webcore/streams.zig index 2ab7e4ddd6161d..de93c7502f92ca 100644 --- a/src/bun.js/webcore/streams.zig +++ b/src/bun.js/webcore/streams.zig @@ -376,7 +376,7 @@ pub const ReadableStream = struct { globalThis: *JSGlobalObject, blob: *const Blob, offset: usize, - ) JSC.JSValue { + ) bun.JSError!JSC.JSValue { JSC.markBinding(@src()); var store = blob.store orelse { return ReadableStream.empty(globalThis); @@ -398,8 +398,7 @@ pub const ReadableStream = struct { return reader.toReadableStream(globalThis); }, else => { - globalThis.throw("Expected FileBlob", .{}); - return .zero; + return globalThis.throw("Expected FileBlob", .{}); }, } } @@ -511,8 +510,7 @@ pub const StreamStart = union(Tag) { return JSC.JSValue.jsNumber(@as(Blob.SizeType, @intCast(chunk))); }, .err => |err| { - globalThis.vm().throwError(globalThis, err.toJSC(globalThis)); - return .zero; + return globalThis.throwValue(err.toJSC(globalThis)) catch .zero; }, .owned_and_done => |list| { return JSC.ArrayBuffer.fromBytes(list.slice(), .Uint8Array).toJS(globalThis, null); @@ -1684,14 +1682,12 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { .message = bun.String.static(Static.message), .code = bun.String.static(@tagName(.ERR_ILLEGAL_CONSTRUCTOR)), }; - globalThis.throwValue(err.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(err.toErrorInstance(globalThis)); } var allocator = globalThis.bunVM().allocator; var this = allocator.create(ThisSink) catch { - globalThis.vm().throwError(globalThis, Syscall.Error.oom.toJSC(globalThis)); - return .zero; + return globalThis.throwValue(Syscall.Error.oom.toJSC(globalThis)); }; this.sink.construct(allocator); return createObject(globalThis, this, 0); @@ -1721,21 +1717,11 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { } inline fn getThis(globalThis: *JSGlobalObject, callframe: *const JSC.CallFrame) ?*ThisSink { - return @as( - *ThisSink, - @ptrCast(@alignCast( - fromJS( - globalThis, - callframe.this(), - ) orelse return null, - )), - ); + return @as(*ThisSink, @ptrCast(@alignCast(fromJS(globalThis, callframe.this()) orelse return null))); } - fn invalidThis(globalThis: *JSGlobalObject) JSValue { - const err = JSC.toTypeError(.ERR_INVALID_THIS, "Expected Sink", .{}, globalThis); - globalThis.vm().throwError(globalThis, err); - return .zero; + fn invalidThis(globalThis: *JSGlobalObject) bun.JSError { + return globalThis.ERR_INVALID_THIS("Expected Sink", .{}).throw(); } pub fn unprotect(this: *@This()) void { @@ -1749,8 +1735,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { if (comptime @hasDecl(SinkType, "getPendingError")) { if (this.sink.getPendingError()) |err| { - globalThis.vm().throwError(globalThis, err); - return .zero; + return globalThis.throwValue(err); } } @@ -1758,8 +1743,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { const args = args_list.ptr[0..args_list.len]; if (args.len == 0) { - globalThis.vm().throwError(globalThis, JSC.toTypeError(.ERR_MISSING_ARGS, "write() expects a string, ArrayBufferView, or ArrayBuffer", .{}, globalThis)); - return .zero; + return globalThis.throwValue(JSC.toTypeError(.ERR_MISSING_ARGS, "write() expects a string, ArrayBufferView, or ArrayBuffer", .{}, globalThis)); } const arg = args[0]; @@ -1767,8 +1751,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { defer arg.ensureStillAlive(); if (arg.isEmptyOrUndefinedOrNull()) { - globalThis.vm().throwError(globalThis, JSC.toTypeError(.ERR_STREAM_NULL_VALUES, "write() expects a string, ArrayBufferView, or ArrayBuffer", .{}, globalThis)); - return .zero; + return globalThis.throwValue(JSC.toTypeError(.ERR_STREAM_NULL_VALUES, "write() expects a string, ArrayBufferView, or ArrayBuffer", .{}, globalThis)); } if (arg.asArrayBuffer(globalThis)) |buffer| { @@ -1781,8 +1764,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { } if (!arg.isString()) { - globalThis.vm().throwError(globalThis, JSC.toTypeError(.ERR_INVALID_ARG_TYPE, "write() expects a string, ArrayBufferView, or ArrayBuffer", .{}, globalThis)); - return .zero; + return globalThis.throwValue(JSC.toTypeError(.ERR_INVALID_ARG_TYPE, "write() expects a string, ArrayBufferView, or ArrayBuffer", .{}, globalThis)); } const str = arg.getZigString(globalThis); @@ -1804,8 +1786,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { if (comptime @hasDecl(SinkType, "getPendingError")) { if (this.sink.getPendingError()) |err| { - globalThis.vm().throwError(globalThis, err); - return .zero; + return globalThis.throwValue(err); } } @@ -1818,8 +1799,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { .{}, globalThis, ); - globalThis.vm().throwError(globalThis, err); - return .zero; + return globalThis.throwValue(err); } const arg = args[0]; @@ -1838,12 +1818,11 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { pub fn close(globalThis: *JSGlobalObject, sink_ptr: ?*anyopaque) callconv(.C) JSValue { JSC.markBinding(@src()); - var this = @as(*ThisSink, @ptrCast(@alignCast(sink_ptr orelse return invalidThis(globalThis)))); + var this = @as(*ThisSink, @ptrCast(@alignCast(sink_ptr orelse return invalidThis(globalThis) catch .zero))); if (comptime @hasDecl(SinkType, "getPendingError")) { if (this.sink.getPendingError()) |err| { - globalThis.vm().throwError(globalThis, err); - return .zero; + return globalThis.vm().throwError(globalThis, err) catch .zero; } } @@ -1857,8 +1836,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { if (comptime @hasDecl(SinkType, "getPendingError")) { if (this.sink.getPendingError()) |err| { - globalThis.vm().throwError(globalThis, err); - return .zero; + return globalThis.throwValue(err); } } @@ -1869,16 +1847,11 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { } if (comptime @hasDecl(SinkType, "flushFromJS")) { - const wait = callframe.argumentsCount() > 0 and - callframe.argument(0).isBoolean() and - callframe.argument(0).asBoolean(); + const wait = callframe.argumentsCount() > 0 and callframe.argument(0).isBoolean() and callframe.argument(0).asBoolean(); const maybe_value: JSC.Maybe(JSValue) = this.sink.flushFromJS(globalThis, wait); return switch (maybe_value) { .result => |value| value, - .err => |err| blk: { - globalThis.vm().throwError(globalThis, err.toJSC(globalThis)); - break :blk .zero; - }, + .err => |err| return globalThis.throwValue(err.toJSC(globalThis)), }; } @@ -1892,8 +1865,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { if (comptime @hasDecl(SinkType, "getPendingError")) { if (this.sink.getPendingError()) |err| { - globalThis.vm().throwError(globalThis, err); - return .zero; + return globalThis.throwValue(err); } } @@ -1921,8 +1893,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { if (comptime @hasDecl(SinkType, "getPendingError")) { if (this.sink.getPendingError()) |err| { - globalThis.vm().throwError(globalThis, err); - return .zero; + return globalThis.throwValue(err); } } @@ -1944,8 +1915,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { if (comptime @hasDecl(SinkType, "getPendingError")) { if (this.sink.getPendingError()) |err| { - globalThis.vm().throwError(globalThis, err); - return .zero; + return globalThis.throwValue(err); } } @@ -2005,7 +1975,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type { // var this = @ptrCast(*ThisSocket, @alignCast( fromJS(globalThis, callframe.this()) orelse { // const err = JSC.toTypeError(.ERR_INVALID_THIS, "Expected Socket", .{}, globalThis); -// globalThis.vm().throwError(globalThis, err); +// globalThis.throwValue( err); // return .zero; // })); // } @@ -2648,7 +2618,7 @@ pub fn ReadableStreamSource( comptime deinit_fn: fn (this: *Context) void, comptime setRefUnrefFn: ?fn (this: *Context, enable: bool) void, comptime drainInternalBuffer: ?fn (this: *Context) bun.ByteList, - comptime toBufferedValue: ?fn (this: *Context, globalThis: *JSC.JSGlobalObject, action: BufferedReadableStreamAction) JSC.JSValue, + comptime toBufferedValue: ?fn (this: *Context, globalThis: *JSC.JSGlobalObject, action: BufferedReadableStreamAction) bun.JSError!JSC.JSValue, ) type { return struct { context: Context, @@ -2813,12 +2783,6 @@ pub fn ReadableStreamSource( pub const blobFromJS = JSReadableStreamSource.blob; pub const bytesFromJS = JSReadableStreamSource.bytes; pub const JSReadableStreamSource = struct { - pub fn construct(globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) ?*ReadableStreamSourceType { - _ = callFrame; // autofix - globalThis.throw("Cannot construct ReadableStreamSource", .{}); - return null; - } - pub fn pull(this: *ReadableStreamSourceType, globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { JSC.markBinding(@src()); const this_jsvalue = callFrame.this(); @@ -2844,8 +2808,7 @@ pub fn ReadableStreamSource( .ready => return JSValue.jsNumber(16384), .chunk_size => |size| return JSValue.jsNumber(size), .err => |err| { - globalThis.vm().throwError(globalThis, err.toJSC(globalThis)); - return .zero; + return globalThis.throwValue(err.toJSC(globalThis)); }, else => |rc| { return rc.toJS(globalThis); @@ -2858,18 +2821,17 @@ pub fn ReadableStreamSource( return JSC.JSValue.jsBoolean(this.is_closed); } - fn processResult(this_jsvalue: JSC.JSValue, globalThis: *JSGlobalObject, flags: JSValue, result: StreamResult) JSC.JSValue { + fn processResult(this_jsvalue: JSC.JSValue, globalThis: *JSGlobalObject, flags: JSValue, result: StreamResult) bun.JSError!JSC.JSValue { switch (result) { .err => |err| { if (err == .Error) { - globalThis.vm().throwError(globalThis, err.Error.toJSC(globalThis)); + return globalThis.throwValue(err.Error.toJSC(globalThis)); } else { const js_err = err.JSValue; js_err.ensureStillAlive(); js_err.unprotect(); - globalThis.vm().throwError(globalThis, js_err); + return globalThis.throwValue(js_err); } - return .zero; }, .pending => { const out = result.toJS(globalThis); @@ -2903,7 +2865,7 @@ pub fn ReadableStreamSource( } if (!value.isCallable(globalObject.vm())) { - globalObject.throwInvalidArgumentType("ReadableStreamSource", "onclose", "function"); + globalObject.throwInvalidArgumentType("ReadableStreamSource", "onclose", "function") catch {}; return false; } const cb = value.withAsyncContextIfNeeded(globalObject); @@ -2921,7 +2883,7 @@ pub fn ReadableStreamSource( } if (!value.isCallable(globalObject.vm())) { - globalObject.throwInvalidArgumentType("ReadableStreamSource", "onDrain", "function"); + globalObject.throwInvalidArgumentType("ReadableStreamSource", "onDrain", "function") catch {}; return false; } const cb = value.withAsyncContextIfNeeded(globalObject); @@ -4328,7 +4290,7 @@ pub const ByteBlobLoader = struct { return bun.ByteList.fromList(cloned); } - pub fn toBufferedValue(this: *ByteBlobLoader, globalThis: *JSC.JSGlobalObject, action: BufferedReadableStreamAction) JSC.JSValue { + pub fn toBufferedValue(this: *ByteBlobLoader, globalThis: *JSC.JSGlobalObject, action: BufferedReadableStreamAction) bun.JSError!JSC.JSValue { if (this.toAnyBlob(globalThis)) |blob_| { var blob = blob_; return blob.toPromise(globalThis, action); @@ -4809,10 +4771,9 @@ pub const ByteStream = struct { return null; } - pub fn toBufferedValue(this: *@This(), globalThis: *JSC.JSGlobalObject, action: BufferedReadableStreamAction) JSC.JSValue { + pub fn toBufferedValue(this: *@This(), globalThis: *JSC.JSGlobalObject, action: BufferedReadableStreamAction) bun.JSError!JSC.JSValue { if (this.buffer_action != null) { - globalThis.throw("Cannot buffer value twice", .{}); - return .zero; + return globalThis.throw("Cannot buffer value twice", .{}); } if (this.pending.result == .err) { diff --git a/src/cli/pack_command.zig b/src/cli/pack_command.zig index 73fdd87118326d..1ad073b2654ae1 100644 --- a/src/cli/pack_command.zig +++ b/src/cli/pack_command.zig @@ -2301,8 +2301,7 @@ pub const bindings = struct { pub fn jsReadTarball(global: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue { const args = callFrame.arguments_old(1).slice(); if (args.len < 1 or !args[0].isString()) { - global.throw("expected tarball path string argument", .{}); - return .zero; + return global.throw("expected tarball path string argument", .{}); } const tarball_path_str = args[0].toBunString(global); @@ -2312,14 +2311,12 @@ pub const bindings = struct { defer tarball_path.deinit(); const tarball_file = File.from(std.fs.openFileAbsolute(tarball_path.slice(), .{}) catch |err| { - global.throw("failed to open tarball file \"{s}\": {s}", .{ tarball_path.slice(), @errorName(err) }); - return .zero; + return global.throw("failed to open tarball file \"{s}\": {s}", .{ tarball_path.slice(), @errorName(err) }); }); defer tarball_file.close(); const tarball = tarball_file.readToEnd(bun.default_allocator).unwrap() catch |err| { - global.throw("failed to read tarball contents \"{s}\": {s}", .{ tarball_path.slice(), @errorName(err) }); - return .zero; + return global.throw("failed to read tarball contents \"{s}\": {s}", .{ tarball_path.slice(), @errorName(err) }); }; defer bun.default_allocator.free(tarball); @@ -2353,38 +2350,33 @@ pub const bindings = struct { switch (archive.readSupportFormatTar()) { .failed, .fatal, .warn => { - global.throw("failed to support tar: {s}", .{archive.errorString()}); - return .zero; + return global.throw("failed to support tar: {s}", .{archive.errorString()}); }, else => {}, } switch (archive.readSupportFormatGnutar()) { .failed, .fatal, .warn => { - global.throw("failed to support gnutar: {s}", .{archive.errorString()}); - return .zero; + return global.throw("failed to support gnutar: {s}", .{archive.errorString()}); }, else => {}, } switch (archive.readSupportFilterGzip()) { .failed, .fatal, .warn => { - global.throw("failed to support gzip compression: {s}", .{archive.errorString()}); - return .zero; + return global.throw("failed to support gzip compression: {s}", .{archive.errorString()}); }, else => {}, } switch (archive.readSetOptions("read_concatenated_archives")) { .failed, .fatal, .warn => { - global.throw("failed to set read_concatenated_archives option: {s}", .{archive.errorString()}); - return .zero; + return global.throw("failed to set read_concatenated_archives option: {s}", .{archive.errorString()}); }, else => {}, } switch (archive.readOpenMemory(tarball)) { .failed, .fatal, .warn => { - global.throw("failed to open archive in memory: {s}", .{archive.errorString()}); - return .zero; + return global.throw("failed to open archive in memory: {s}", .{archive.errorString()}); }, else => {}, } @@ -2400,8 +2392,7 @@ pub const bindings = struct { .eof => unreachable, .retry => continue, .failed, .fatal => { - global.throw("failed to read archive header: {s}", .{Archive.errorString(@ptrCast(archive))}); - return .zero; + return global.throw("failed to read archive header: {s}", .{Archive.errorString(@ptrCast(archive))}); }, else => { const pathname = archive_entry.pathname(); @@ -2421,11 +2412,10 @@ pub const bindings = struct { const read = archive.readData(read_buf.items); if (read < 0) { - global.throw("failed to read archive entry \"{}\": {s}", .{ + return global.throw("failed to read archive entry \"{}\": {s}", .{ bun.fmt.fmtPath(u8, pathname, .{}), Archive.errorString(@ptrCast(archive)), }); - return .zero; } read_buf.items.len = @intCast(read); entry_info.contents = String.createUTF8(read_buf.items); @@ -2438,15 +2428,13 @@ pub const bindings = struct { switch (archive.readClose()) { .failed, .fatal, .warn => { - global.throw("failed to close read archive: {s}", .{archive.errorString()}); - return .zero; + return global.throw("failed to close read archive: {s}", .{archive.errorString()}); }, else => {}, } switch (archive.readFree()) { .failed, .fatal, .warn => { - global.throw("failed to close read archive: {s}", .{archive.errorString()}); - return .zero; + return global.throw("failed to close read archive: {s}", .{archive.errorString()}); }, else => {}, } diff --git a/src/codegen/generate-classes.ts b/src/codegen/generate-classes.ts index 2281e6564e2060..bc83c72f4591a6 100644 --- a/src/codegen/generate-classes.ts +++ b/src/codegen/generate-classes.ts @@ -1885,7 +1885,7 @@ const JavaScriptCoreBindings = struct { output += ` pub fn ${symbolName(typeName, "onStructuredCloneDeserialize")}(globalObject: *JSC.JSGlobalObject, ptr: [*]u8, end: [*]u8) callconv(JSC.conv) JSC.JSValue { if (comptime Environment.enable_logs) JSC.markBinding(@src()); - return @call(.always_inline, ${typeName}.onStructuredCloneDeserialize, .{globalObject, ptr, end}); + return @call(.always_inline, JSC.toJSHostValue, .{ globalObject, @call(.always_inline, ${typeName}.onStructuredCloneDeserialize, .{globalObject, ptr, end}) }); } `; } else { diff --git a/src/codegen/generate-node-errors.ts b/src/codegen/generate-node-errors.ts index 916bece2d4032f..6dfcedb4e1f096 100644 --- a/src/codegen/generate-node-errors.ts +++ b/src/codegen/generate-node-errors.ts @@ -45,8 +45,8 @@ fn ErrorBuilder(comptime code: Error, comptime fmt: [:0]const u8, Args: type) ty args: Args, // Throw this error as a JS exception - pub inline fn throw(this: @This()) void { - code.throw(this.globalThis, fmt, this.args); + pub inline fn throw(this: @This()) bun.JSError { + return code.throw(this.globalThis, fmt, this.args); } /// Turn this into a JSValue @@ -109,8 +109,8 @@ zig += ` return toJS(this, globalThis, &message); } - pub fn throw(this: Error, globalThis: *JSC.JSGlobalObject, comptime fmt_str: [:0]const u8, args: anytype) void { - globalThis.throwValue(fmt(this, globalThis, fmt_str, args)); + pub fn throw(this: Error, globalThis: *JSC.JSGlobalObject, comptime fmt_str: [:0]const u8, args: anytype) bun.JSError { + return globalThis.throwValue(fmt(this, globalThis, fmt_str, args)); } }; diff --git a/src/css/css_internals.zig b/src/css/css_internals.zig index 9445c8ab7c0762..46b7f133f09928 100644 --- a/src/css/css_internals.zig +++ b/src/css/css_internals.zig @@ -39,12 +39,10 @@ pub fn testingImpl(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, c const arguments_ = callframe.arguments_old(3); var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const source_arg: JSC.JSValue = arguments.nextEat() orelse { - globalThis.throw("minifyTestWithOptions: expected 2 arguments, got 0", .{}); - return .zero; + return globalThis.throw("minifyTestWithOptions: expected 2 arguments, got 0", .{}); }; if (!source_arg.isString()) { - globalThis.throw("minifyTestWithOptions: expected source to be a string", .{}); - return .zero; + return globalThis.throw("minifyTestWithOptions: expected source to be a string", .{}); } const source_bunstr = source_arg.toBunString(globalThis); defer source_bunstr.deref(); @@ -52,12 +50,10 @@ pub fn testingImpl(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, c defer source.deinit(); const expected_arg = arguments.nextEat() orelse { - globalThis.throw("minifyTestWithOptions: expected 2 arguments, got 1", .{}); - return .zero; + return globalThis.throw("minifyTestWithOptions: expected 2 arguments, got 1", .{}); }; if (!expected_arg.isString()) { - globalThis.throw("minifyTestWithOptions: expected `expected` arg to be a string", .{}); - return .zero; + return globalThis.throw("minifyTestWithOptions: expected `expected` arg to be a string", .{}); } const expected_bunstr = expected_arg.toBunString(globalThis); defer expected_bunstr.deref(); @@ -119,8 +115,7 @@ pub fn testingImpl(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, c if (log.hasAny()) { return log.toJS(globalThis, bun.default_allocator, "parsing failed:"); } - globalThis.throw("parsing failed: {}", .{err.kind}); - return .zero; + return globalThis.throw("parsing failed: {}", .{err.kind}); }, } } @@ -205,12 +200,10 @@ pub fn attrTest(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. const arguments_ = callframe.arguments_old(4); var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const source_arg: JSC.JSValue = arguments.nextEat() orelse { - globalThis.throw("attrTest: expected 3 arguments, got 0", .{}); - return .zero; + return globalThis.throw("attrTest: expected 3 arguments, got 0", .{}); }; if (!source_arg.isString()) { - globalThis.throw("attrTest: expected source to be a string", .{}); - return .zero; + return globalThis.throw("attrTest: expected source to be a string", .{}); } const source_bunstr = source_arg.toBunString(globalThis); defer source_bunstr.deref(); @@ -218,12 +211,10 @@ pub fn attrTest(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. defer source.deinit(); const expected_arg = arguments.nextEat() orelse { - globalThis.throw("attrTest: expected 3 arguments, got 1", .{}); - return .zero; + return globalThis.throw("attrTest: expected 3 arguments, got 1", .{}); }; if (!expected_arg.isString()) { - globalThis.throw("attrTest: expected `expected` arg to be a string", .{}); - return .zero; + return globalThis.throw("attrTest: expected `expected` arg to be a string", .{}); } const expected_bunstr = expected_arg.toBunString(globalThis); defer expected_bunstr.deref(); @@ -231,8 +222,7 @@ pub fn attrTest(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. defer expected.deinit(); const minify_arg: JSC.JSValue = arguments.nextEat() orelse { - globalThis.throw("attrTest: expected 3 arguments, got 2", .{}); - return .zero; + return globalThis.throw("attrTest: expected 3 arguments, got 2", .{}); }; const minify = minify_arg.isBoolean() and minify_arg.toBoolean(); @@ -270,8 +260,7 @@ pub fn attrTest(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. if (log.hasAny()) { return log.toJS(globalThis, bun.default_allocator, "parsing failed:"); } - globalThis.throw("parsing failed: {}", .{err.kind}); - return .zero; + return globalThis.throw("parsing failed: {}", .{err.kind}); }, } } diff --git a/src/css/values/color_js.zig b/src/css/values/color_js.zig index cf7662994d276e..052d92ed7046ac 100644 --- a/src/css/values/color_js.zig +++ b/src/css/values/color_js.zig @@ -58,11 +58,9 @@ const OutputColorFormat = enum { }); }; -fn colorIntFromJS(globalThis: *JSC.JSGlobalObject, input: JSC.JSValue, comptime property: []const u8) ?i32 { +fn colorIntFromJS(globalThis: *JSC.JSGlobalObject, input: JSC.JSValue, comptime property: []const u8) bun.JSError!i32 { if (input == .zero or input == .undefined or !input.isNumber()) { - globalThis.throwInvalidArgumentType("color", property, "integer"); - - return null; + return globalThis.throwInvalidArgumentType("color", property, "integer"); } // CSS spec says to clamp values to their valid range so we'll respect that here @@ -150,8 +148,7 @@ pub const Ansi256 = struct { pub fn jsFunctionColor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFrame) bun.JSError!JSC.JSValue { const args = callFrame.argumentsAsArray(2); if (args[0].isUndefined()) { - globalThis.throwInvalidArgumentType("color", "input", "string, number, or object"); - return .zero; + return globalThis.throwInvalidArgumentType("color", "input", "string, number, or object"); } var arena = std.heap.ArenaAllocator.init(bun.default_allocator); @@ -165,8 +162,7 @@ pub fn jsFunctionColor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFram const unresolved_format: OutputColorFormat = brk: { if (!args[1].isEmptyOrUndefinedOrNull()) { if (!args[1].isString()) { - globalThis.throwInvalidArgumentType("color", "format", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("color", "format", "string"); } break :brk try args[1].toEnum(globalThis, "format", OutputColorFormat); @@ -193,60 +189,26 @@ pub fn jsFunctionColor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFram } else if (args[0].jsType().isArrayLike()) { switch (args[0].getLength(globalThis)) { 3 => { - const r = colorIntFromJS(globalThis, args[0].getIndex(globalThis, 0), "[0]") orelse return .zero; - if (globalThis.hasException()) { - return .zero; - } - const g = colorIntFromJS(globalThis, args[0].getIndex(globalThis, 1), "[1]") orelse return .zero; - if (globalThis.hasException()) { - return .zero; - } - const b = colorIntFromJS(globalThis, args[0].getIndex(globalThis, 2), "[2]") orelse return .zero; - if (globalThis.hasException()) { - return .zero; - } + const r = try colorIntFromJS(globalThis, args[0].getIndex(globalThis, 0), "[0]"); + const g = try colorIntFromJS(globalThis, args[0].getIndex(globalThis, 1), "[1]"); + const b = try colorIntFromJS(globalThis, args[0].getIndex(globalThis, 2), "[2]"); break :brk .{ .result = css.CssColor{ .rgba = .{ .alpha = 255, .red = @intCast(r), .green = @intCast(g), .blue = @intCast(b) } } }; }, 4 => { - const r = colorIntFromJS(globalThis, args[0].getIndex(globalThis, 0), "[0]") orelse return .zero; - if (globalThis.hasException()) { - return .zero; - } - const g = colorIntFromJS(globalThis, args[0].getIndex(globalThis, 1), "[1]") orelse return .zero; - if (globalThis.hasException()) { - return .zero; - } - const b = colorIntFromJS(globalThis, args[0].getIndex(globalThis, 2), "[2]") orelse return .zero; - if (globalThis.hasException()) { - return .zero; - } - const a = colorIntFromJS(globalThis, args[0].getIndex(globalThis, 3), "[3]") orelse return .zero; - if (globalThis.hasException()) { - return .zero; - } + const r = try colorIntFromJS(globalThis, args[0].getIndex(globalThis, 0), "[0]"); + const g = try colorIntFromJS(globalThis, args[0].getIndex(globalThis, 1), "[1]"); + const b = try colorIntFromJS(globalThis, args[0].getIndex(globalThis, 2), "[2]"); + const a = try colorIntFromJS(globalThis, args[0].getIndex(globalThis, 3), "[3]"); break :brk .{ .result = css.CssColor{ .rgba = .{ .alpha = @intCast(a), .red = @intCast(r), .green = @intCast(g), .blue = @intCast(b) } } }; }, else => { - globalThis.throw("Expected array length 3 or 4", .{}); - return .zero; + return globalThis.throw("Expected array length 3 or 4", .{}); }, } } else if (args[0].isObject()) { - const r = colorIntFromJS(globalThis, try args[0].get(globalThis, "r") orelse .zero, "r") orelse return .zero; - - if (globalThis.hasException()) { - return .zero; - } - const g = colorIntFromJS(globalThis, try args[0].get(globalThis, "g") orelse .zero, "g") orelse return .zero; - - if (globalThis.hasException()) { - return .zero; - } - const b = colorIntFromJS(globalThis, try args[0].get(globalThis, "b") orelse .zero, "b") orelse return .zero; - - if (globalThis.hasException()) { - return .zero; - } + const r = try colorIntFromJS(globalThis, try args[0].get(globalThis, "r") orelse .zero, "r"); + const g = try colorIntFromJS(globalThis, try args[0].get(globalThis, "g") orelse .zero, "g"); + const b = try colorIntFromJS(globalThis, try args[0].get(globalThis, "b") orelse .zero, "b"); const a: ?u8 = if (try args[0].getTruthy(globalThis, "a")) |a_value| brk2: { if (a_value.isNumber()) { @@ -283,8 +245,7 @@ pub fn jsFunctionColor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFram return .null; } - globalThis.throw("color() failed to parse {s}", .{@tagName(err.basic().kind)}); - return .zero; + return globalThis.throw("color() failed to parse {s}", .{@tagName(err.basic().kind)}); }, .result => |*result| { const format: OutputColorFormat = if (unresolved_format == .ansi) switch (bun.Output.Source.colorDepth()) { @@ -470,8 +431,7 @@ pub fn jsFunctionColor(globalThis: *JSC.JSGlobalObject, callFrame: *JSC.CallFram ); result.toCss(@TypeOf(writer), &printer) catch |err| { - globalThis.throw("color() internal error: {s}", .{@errorName(err)}); - return .zero; + return globalThis.throw("color() internal error: {s}", .{@errorName(err)}); }; var out = bun.String.createUTF8(dest.items); diff --git a/src/fd.zig b/src/fd.zig index b1d466b0019e1c..4a518805418b54 100644 --- a/src/fd.zig +++ b/src/fd.zig @@ -343,11 +343,10 @@ pub const FDImpl = packed struct { pub fn toJS(value: FDImpl, global: *JSC.JSGlobalObject) JSValue { const fd = value.makeLibUVOwned() catch { _ = value.close(); - global.throwValue((JSC.SystemError{ + return global.throwValue((JSC.SystemError{ .message = bun.String.static("EMFILE, too many open files"), .code = bun.String.static("EMFILE"), - }).toErrorInstance(global)); - return .zero; + }).toErrorInstance(global)) catch .zero; }; return JSValue.jsNumberFromInt32(fd.uv()); } diff --git a/src/install/dependency.zig b/src/install/dependency.zig index 00f0d3d7a60c01..6f3667988e4f7a 100644 --- a/src/install/dependency.zig +++ b/src/install/dependency.zig @@ -1278,14 +1278,14 @@ pub fn fromJS(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JS const dep: Version = Dependency.parse(allocator, SlicedString.init(buf, alias).value(), null, buf, &sliced, &log, null) orelse { if (log.msgs.items.len > 0) { - return globalThis.throwValue2(log.toJS(globalThis, bun.default_allocator, "Failed to parse dependency")); + return globalThis.throwValue(log.toJS(globalThis, bun.default_allocator, "Failed to parse dependency")); } return .undefined; }; if (log.msgs.items.len > 0) { - return globalThis.throwValue2(log.toJS(globalThis, bun.default_allocator, "Failed to parse dependency")); + return globalThis.throwValue(log.toJS(globalThis, bun.default_allocator, "Failed to parse dependency")); } log.deinit(); diff --git a/src/install/install.zig b/src/install/install.zig index 23db1639fd259d..3a5c80c1a5d4b0 100644 --- a/src/install/install.zig +++ b/src/install/install.zig @@ -10096,16 +10096,16 @@ pub const PackageManager = struct { var array = Array{}; const update_requests = parseWithError(allocator, null, &log, all_positionals.items, &array, .add, false) catch { - return globalThis.throwValue2(log.toJS(globalThis, bun.default_allocator, "Failed to parse dependencies")); + return globalThis.throwValue(log.toJS(globalThis, bun.default_allocator, "Failed to parse dependencies")); }; if (update_requests.len == 0) return .undefined; if (log.msgs.items.len > 0) { - return globalThis.throwValue2(log.toJS(globalThis, bun.default_allocator, "Failed to parse dependencies")); + return globalThis.throwValue(log.toJS(globalThis, bun.default_allocator, "Failed to parse dependencies")); } if (update_requests[0].failed) { - return globalThis.throw2("Failed to parse dependencies", .{}); + return globalThis.throw("Failed to parse dependencies", .{}); } var object = JSC.JSValue.createEmptyObject(globalThis, 2); @@ -15016,12 +15016,10 @@ pub const bun_install_js_bindings = struct { switch (load_result) { .err => |err| { - globalObject.throw("failed to load lockfile: {s}, \"{s}\"", .{ @errorName(err.value), lockfile_path }); - return .zero; + return globalObject.throw("failed to load lockfile: {s}, \"{s}\"", .{ @errorName(err.value), lockfile_path }); }, .not_found => { - globalObject.throw("lockfile not found: \"{s}\"", .{lockfile_path}); - return .zero; + return globalObject.throw("lockfile not found: \"{s}\"", .{lockfile_path}); }, .ok => {}, } @@ -15040,13 +15038,11 @@ pub const bun_install_js_bindings = struct { }, buffered_writer.writer(), ) catch |err| { - globalObject.throw("failed to print lockfile as JSON: {s}", .{@errorName(err)}); - return .zero; + return globalObject.throw("failed to print lockfile as JSON: {s}", .{@errorName(err)}); }; buffered_writer.flush() catch |err| { - globalObject.throw("failed to print lockfile as JSON: {s}", .{@errorName(err)}); - return .zero; + return globalObject.throw("failed to print lockfile as JSON: {s}", .{@errorName(err)}); }; var str = bun.String.createUTF8(buffer.list.items); diff --git a/src/install/npm.zig b/src/install/npm.zig index abff7db58b0aad..4c5210f86d9440 100644 --- a/src/install/npm.zig +++ b/src/install/npm.zig @@ -1286,8 +1286,7 @@ pub const PackageManifest = struct { pub fn jsParseManifest(global: *JSGlobalObject, callFrame: *CallFrame) bun.JSError!JSValue { const args = callFrame.arguments_old(2).slice(); if (args.len < 2 or !args[0].isString() or !args[1].isString()) { - global.throw("expected manifest filename and registry string arguments", .{}); - return .zero; + return global.throw("expected manifest filename and registry string arguments", .{}); } const manifest_filename_str = args[0].toBunString(global); @@ -1303,8 +1302,7 @@ pub const PackageManifest = struct { defer registry.deinit(); const manifest_file = std.fs.openFileAbsolute(manifest_filename.slice(), .{}) catch |err| { - global.throw("failed to open manifest file \"{s}\": {s}", .{ manifest_filename.slice(), @errorName(err) }); - return .zero; + return global.throw("failed to open manifest file \"{s}\": {s}", .{ manifest_filename.slice(), @errorName(err) }); }; defer manifest_file.close(); @@ -1320,13 +1318,11 @@ pub const PackageManifest = struct { }; const maybe_package_manifest = Serializer.loadByFile(bun.default_allocator, &scope, File.from(manifest_file)) catch |err| { - global.throw("failed to load manifest file: {s}", .{@errorName(err)}); - return .zero; + return global.throw("failed to load manifest file: {s}", .{@errorName(err)}); }; const package_manifest: PackageManifest = maybe_package_manifest orelse { - global.throw("manifest is invalid ", .{}); - return .zero; + return global.throw("manifest is invalid ", .{}); }; var buf: std.ArrayListUnmanaged(u8) = .{}; diff --git a/src/install/semver.zig b/src/install/semver.zig index 1a01dd95d909fe..fc90129b67d560 100644 --- a/src/install/semver.zig +++ b/src/install/semver.zig @@ -2657,8 +2657,7 @@ pub const SemverObject = struct { const arguments = callFrame.arguments_old(2).slice(); if (arguments.len < 2) { - globalThis.throw("Expected two arguments", .{}); - return .zero; + return globalThis.throw("Expected two arguments", .{}); } const left_arg = arguments[0]; @@ -2679,13 +2678,11 @@ pub const SemverObject = struct { const right_result = Version.parse(SlicedString.init(right.slice(), right.slice())); if (!left_result.valid) { - globalThis.throw("Invalid SemVer: {s}\n", .{left.slice()}); - return .zero; + return globalThis.throw("Invalid SemVer: {s}\n", .{left.slice()}); } if (!right_result.valid) { - globalThis.throw("Invalid SemVer: {s}\n", .{right.slice()}); - return .zero; + return globalThis.throw("Invalid SemVer: {s}\n", .{right.slice()}); } const left_version = left_result.version.max(); @@ -2706,8 +2703,7 @@ pub const SemverObject = struct { const arguments = callFrame.arguments_old(2).slice(); if (arguments.len < 2) { - globalThis.throw("Expected two arguments", .{}); - return .zero; + return globalThis.throw("Expected two arguments", .{}); } const left_arg = arguments[0]; diff --git a/src/patch.zig b/src/patch.zig index f4d267ec174636..55b5780a3bbc02 100644 --- a/src/patch.zig +++ b/src/patch.zig @@ -1099,15 +1099,13 @@ pub const TestingAPIs = struct { var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const old_folder_jsval = arguments.nextEat() orelse { - globalThis.throw("expected 2 strings", .{}); - return .zero; + return globalThis.throw("expected 2 strings", .{}); }; const old_folder_bunstr = old_folder_jsval.toBunString(globalThis); defer old_folder_bunstr.deref(); const new_folder_jsval = arguments.nextEat() orelse { - globalThis.throw("expected 2 strings", .{}); - return .zero; + return globalThis.throw("expected 2 strings", .{}); }; const new_folder_bunstr = new_folder_jsval.toBunString(globalThis); defer new_folder_bunstr.deref(); @@ -1127,8 +1125,7 @@ pub const TestingAPIs = struct { }, .err => |e| { defer e.deinit(); - globalThis.throw("failed to make diff: {s}", .{e.items}); - return .zero; + return globalThis.throw("failed to make diff: {s}", .{e.items}); }, }; } @@ -1153,8 +1150,7 @@ pub const TestingAPIs = struct { defer args.deinit(); if (args.patchfile.apply(bun.default_allocator, args.dirfd)) |err| { - globalThis.throwValue(err.toErrorInstance(globalThis)); - return .zero; + return globalThis.throwValue(err.toErrorInstance(globalThis)); } return .true; @@ -1165,8 +1161,7 @@ pub const TestingAPIs = struct { var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const patchfile_src_js = arguments.nextEat() orelse { - globalThis.throw("TestingAPIs.parse: expected at least 1 argument, got 0", .{}); - return .zero; + return globalThis.throw("TestingAPIs.parse: expected at least 1 argument, got 0", .{}); }; const patchfile_src_bunstr = patchfile_src_js.toBunString(globalThis); const patchfile_src = patchfile_src_bunstr.toUTF8(bun.default_allocator); @@ -1190,7 +1185,7 @@ pub const TestingAPIs = struct { var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const patchfile_js = arguments.nextEat() orelse { - globalThis.throw("apply: expected at least 1 argument, got 0", .{}); + globalThis.throw("apply: expected at least 1 argument, got 0", .{}) catch {}; return .{ .err = .undefined }; }; @@ -1202,7 +1197,7 @@ pub const TestingAPIs = struct { break :brk switch (bun.sys.open(path, bun.O.DIRECTORY | bun.O.RDONLY, 0)) { .err => |e| { - globalThis.throwValue(e.withPath(path).toJSC(globalThis)); + globalThis.throwValue(e.withPath(path).toJSC(globalThis)) catch {}; return .{ .err = .undefined }; }, .result => |fd| fd, diff --git a/src/resolver/resolver.zig b/src/resolver/resolver.zig index 4196d18a16f95a..c765c9f79bfee5 100644 --- a/src/resolver/resolver.zig +++ b/src/resolver/resolver.zig @@ -3302,8 +3302,7 @@ pub const Resolver = struct { const argument: bun.JSC.JSValue = callframe.argument(0); if (argument == .zero or !argument.isString()) { - globalThis.throwInvalidArgumentType("nodeModulePaths", "path", "string"); - return .zero; + return globalThis.throwInvalidArgumentType("nodeModulePaths", "path", "string"); } const in_str = argument.toBunString(globalThis); diff --git a/src/shell/interpreter.zig b/src/shell/interpreter.zig index c05d297e9f37d7..ec729b3da6577f 100644 --- a/src/shell/interpreter.zig +++ b/src/shell/interpreter.zig @@ -707,8 +707,7 @@ pub const ParsedShellScript = struct { const arguments_ = callframe.arguments_old(2); var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const str_js = arguments.nextEat() orelse { - globalThis.throw("$`...`.cwd(): expected a string argument", .{}); - return .zero; + return globalThis.throw("$`...`.cwd(): expected a string argument", .{}); }; const str = bun.String.fromJS(str_js, globalThis); this.cwd = str; @@ -786,9 +785,7 @@ pub const ParsedShellScript = struct { } var jsobjs = std.ArrayList(JSValue).init(shargs.arena_allocator()); var script = std.ArrayList(u8).init(shargs.arena_allocator()); - if (!(try bun.shell.shellCmdFromJS(globalThis, string_args, &template_args, &jsobjs, &jsstrings, &script))) { - return .undefined; - } + try bun.shell.shellCmdFromJS(globalThis, string_args, &template_args, &jsobjs, &jsstrings, &script); var parser: ?bun.shell.Parser = null; var lex_result: ?shell.LexResult = null; @@ -1176,13 +1173,13 @@ pub const Interpreter = struct { const arguments_ = callframe.arguments_old(3); var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); - const resolve = arguments.nextEat() orelse return globalThis.throw2("shell: expected 3 arguments, got 0", .{}); + const resolve = arguments.nextEat() orelse return globalThis.throw("shell: expected 3 arguments, got 0", .{}); - const reject = arguments.nextEat() orelse return globalThis.throw2("shell: expected 3 arguments, got 0", .{}); + const reject = arguments.nextEat() orelse return globalThis.throw("shell: expected 3 arguments, got 0", .{}); - const parsed_shell_script_js = arguments.nextEat() orelse return globalThis.throw2("shell: expected 3 arguments, got 0", .{}); + const parsed_shell_script_js = arguments.nextEat() orelse return globalThis.throw("shell: expected 3 arguments, got 0", .{}); - const parsed_shell_script = parsed_shell_script_js.as(ParsedShellScript) orelse return globalThis.throw2("shell: expected a ParsedShellScript", .{}); + const parsed_shell_script = parsed_shell_script_js.as(ParsedShellScript) orelse return globalThis.throw("shell: expected a ParsedShellScript", .{}); var shargs: *ShellArgs = undefined; var jsobjs: std.ArrayList(JSValue) = std.ArrayList(JSValue).init(allocator); @@ -1190,7 +1187,7 @@ pub const Interpreter = struct { var cwd: ?bun.String = null; var export_env: ?EnvMap = null; - if (parsed_shell_script.args == null) return globalThis.throw2("shell: shell args is null, this is a bug in Bun. Please file a GitHub issue.", .{}); + if (parsed_shell_script.args == null) return globalThis.throw("shell: shell args is null, this is a bug in Bun. Please file a GitHub issue.", .{}); parsed_shell_script.take( globalThis, @@ -1765,8 +1762,7 @@ pub const Interpreter = struct { defer slice.deinit(); switch (this.root_shell.changeCwd(this, slice.slice())) { .err => |e| { - globalThis.throwValue(e.toJSC(globalThis)); - return .zero; + return globalThis.throwValue(e.toJSC(globalThis)); }, .result => {}, } @@ -4973,7 +4969,7 @@ pub const Interpreter = struct { } } 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)}) catch {}; // TODO: propagate return; } }, @@ -5622,7 +5618,7 @@ pub const Interpreter = struct { } else if (interpreter.jsobjs[file.jsbuf.idx].as(JSC.WebCore.Body.Value)) |body| { if ((node.redirect.stdout or node.redirect.stderr) and !(body.* == .Blob and !body.Blob.needsToReadFile())) { // TODO: Locked->stream -> file -> blob conversion via .toBlobIfPossible() except we want to avoid modifying the Response/Request if unnecessary. - cmd.base.interpreter.event_loop.js.global.throw("Cannot redirect stdout/stderr to an immutable blob. Expected a file", .{}); + cmd.base.interpreter.event_loop.js.global.throw("Cannot redirect stdout/stderr to an immutable blob. Expected a file", .{}) catch {}; return .yield; } @@ -5650,7 +5646,7 @@ pub const Interpreter = struct { } else if (interpreter.jsobjs[file.jsbuf.idx].as(JSC.WebCore.Blob)) |blob| { if ((node.redirect.stdout or node.redirect.stderr) and !blob.needsToReadFile()) { // TODO: Locked->stream -> file -> blob conversion via .toBlobIfPossible() except we want to avoid modifying the Response/Request if unnecessary. - cmd.base.interpreter.event_loop.js.global.throw("Cannot redirect stdout/stderr to an immutable blob. Expected a file", .{}); + cmd.base.interpreter.event_loop.js.global.throw("Cannot redirect stdout/stderr to an immutable blob. Expected a file", .{}) catch {}; return .yield; } @@ -5668,7 +5664,7 @@ pub const Interpreter = struct { } } else { const jsval = cmd.base.interpreter.jsobjs[val.idx]; - cmd.base.interpreter.event_loop.js.global.throw("Unknown JS value used in shell: {}", .{jsval.fmtString(globalObject)}); + cmd.base.interpreter.event_loop.js.global.throw("Unknown JS value used in shell: {}", .{jsval.fmtString(globalObject)}) catch {}; return .yield; } }, diff --git a/src/shell/shell.zig b/src/shell/shell.zig index 089c3be357731c..a475cdd763397c 100644 --- a/src/shell/shell.zig +++ b/src/shell/shell.zig @@ -88,13 +88,13 @@ pub const ShellErr = union(enum) { switch (this.*) { .sys => { const err = this.sys.toErrorInstance(globalThis); - return globalThis.throwValue2(err); + return globalThis.throwValue(err); }, .custom => { var str = JSC.ZigString.init(this.custom); str.markUTF8(); const err_value = str.toErrorInstance(globalThis); - return globalThis.throwValue2(err_value); + return globalThis.throwValue(err_value); // this.bunVM().allocator.free(JSC.ZigString.untagged(str._unsafe_ptr_do_not_use)[0..str.len]); }, .invalid_arguments => { @@ -3747,7 +3747,7 @@ pub fn shellCmdFromJS( out_jsobjs: *std.ArrayList(JSValue), jsstrings: *std.ArrayList(bun.String), out_script: *std.ArrayList(u8), -) bun.JSError!bool { +) bun.JSError!void { var builder = ShellSrcBuilder.init(globalThis, out_script, jsstrings); var jsobjref_buf: [128]u8 = [_]u8{0} ** 128; @@ -3757,20 +3757,18 @@ pub fn shellCmdFromJS( while (string_iter.next()) |js_value| { defer i += 1; if (!try builder.appendJSValueStr(js_value, false)) { - globalThis.throw("Shell script string contains invalid UTF-16", .{}); - return false; + return globalThis.throw("Shell script string contains invalid UTF-16", .{}); } // const str = js_value.getZigString(globalThis); // try script.appendSlice(str.full()); if (i < last) { const template_value = template_args.next() orelse { - globalThis.throw("Shell script is missing JSValue arg", .{}); - return false; + return globalThis.throw("Shell script is missing JSValue arg", .{}); }; - if (!(try handleTemplateValue(globalThis, template_value, out_jsobjs, out_script, jsstrings, jsobjref_buf[0..]))) return false; + try handleTemplateValue(globalThis, template_value, out_jsobjs, out_script, jsstrings, jsobjref_buf[0..]); } } - return true; + return; } pub fn handleTemplateValue( @@ -3780,7 +3778,7 @@ pub fn handleTemplateValue( out_script: *std.ArrayList(u8), jsstrings: *std.ArrayList(bun.String), jsobjref_buf: []u8, -) bun.JSError!bool { +) bun.JSError!void { var builder = ShellSrcBuilder.init(globalThis, out_script, jsstrings); if (template_value != .zero) { if (template_value.asArrayBuffer(globalThis)) |array_buffer| { @@ -3790,7 +3788,7 @@ pub fn handleTemplateValue( try out_jsobjs.append(template_value); const slice = std.fmt.bufPrint(jsobjref_buf[0..], "{s}{d}", .{ LEX_JS_OBJREF_PREFIX, idx }) catch return globalThis.throwOutOfMemory(); try out_script.appendSlice(slice); - return true; + return; } if (template_value.as(JSC.WebCore.Blob)) |blob| { @@ -3799,10 +3797,9 @@ pub fn handleTemplateValue( if (store.data.file.pathlike == .path) { const path = store.data.file.pathlike.path.slice(); if (!try builder.appendUTF8(path, true)) { - globalThis.throw("Shell script string contains invalid UTF-16", .{}); - return false; + return globalThis.throw("Shell script string contains invalid UTF-16", .{}); } - return true; + return; } } } @@ -3812,7 +3809,7 @@ pub fn handleTemplateValue( try out_jsobjs.append(template_value); const slice = std.fmt.bufPrint(jsobjref_buf[0..], "{s}{d}", .{ LEX_JS_OBJREF_PREFIX, idx }) catch return globalThis.throwOutOfMemory(); try out_script.appendSlice(slice); - return true; + return; } if (JSC.WebCore.ReadableStream.fromJS(template_value, globalThis)) |rstream| { @@ -3823,7 +3820,7 @@ pub fn handleTemplateValue( try out_jsobjs.append(template_value); const slice = std.fmt.bufPrint(jsobjref_buf[0..], "{s}{d}", .{ LEX_JS_OBJREF_PREFIX, idx }) catch return globalThis.throwOutOfMemory(); try out_script.appendSlice(slice); - return true; + return; } if (template_value.as(JSC.WebCore.Response)) |req| { @@ -3834,15 +3831,14 @@ pub fn handleTemplateValue( try out_jsobjs.append(template_value); const slice = std.fmt.bufPrint(jsobjref_buf[0..], "{s}{d}", .{ LEX_JS_OBJREF_PREFIX, idx }) catch return globalThis.throwOutOfMemory(); try out_script.appendSlice(slice); - return true; + return; } if (template_value.isString()) { if (!try builder.appendJSValueStr(template_value, true)) { - globalThis.throw("Shell script string contains invalid UTF-16", .{}); - return false; + return globalThis.throw("Shell script string contains invalid UTF-16", .{}); } - return true; + return; } if (template_value.jsType().isArray()) { @@ -3850,13 +3846,15 @@ pub fn handleTemplateValue( const last = array.len -| 1; var i: u32 = 0; while (array.next()) |arr| : (i += 1) { - if (!(try handleTemplateValue(globalThis, arr, out_jsobjs, out_script, jsstrings, jsobjref_buf))) return false; + try handleTemplateValue(globalThis, arr, out_jsobjs, out_script, jsstrings, jsobjref_buf); if (i < last) { const str = bun.String.static(" "); - if (!try builder.appendBunStr(str, false)) return false; + if (!try builder.appendBunStr(str, false)) { + return globalThis.throw("Shell script string contains invalid UTF-16", .{}); + } } } - return true; + return; } if (template_value.isObject()) { @@ -3864,34 +3862,30 @@ pub fn handleTemplateValue( const bunstr = maybe_str.toBunString(globalThis); defer bunstr.deref(); if (!try builder.appendBunStr(bunstr, false)) { - globalThis.throw("Shell script string contains invalid UTF-16", .{}); - return false; + return globalThis.throw("Shell script string contains invalid UTF-16", .{}); } - return true; + return; } } if (template_value.isPrimitive()) { if (!try builder.appendJSValueStr(template_value, true)) { - globalThis.throw("Shell script string contains invalid UTF-16", .{}); - return false; + return globalThis.throw("Shell script string contains invalid UTF-16", .{}); } - return true; + return; } if (template_value.implementsToString(globalThis)) { if (!try builder.appendJSValueStr(template_value, true)) { - globalThis.throw("Shell script string contains invalid UTF-16", .{}); - return false; + return globalThis.throw("Shell script string contains invalid UTF-16", .{}); } - return true; + return; } - globalThis.throw("Invalid JS object used in shell: {}, you might need to call `.toString()` on it", .{template_value.fmtString(globalThis)}); - return false; + return globalThis.throw("Invalid JS object used in shell: {}, you might need to call `.toString()` on it", .{template_value.fmtString(globalThis)}); } - return true; + return; } pub const ShellSrcBuilder = struct { @@ -3912,7 +3906,7 @@ pub const ShellSrcBuilder = struct { }; } - pub fn appendJSValueStr(this: *ShellSrcBuilder, jsval: JSValue, comptime allow_escape: bool) !bool { + pub fn appendJSValueStr(this: *ShellSrcBuilder, jsval: JSValue, comptime allow_escape: bool) bun.OOM!bool { const bunstr = jsval.toBunString(this.globalThis); defer bunstr.deref(); @@ -3923,7 +3917,7 @@ pub const ShellSrcBuilder = struct { this: *ShellSrcBuilder, bunstr: bun.String, comptime allow_escape: bool, - ) !bool { + ) bun.OOM!bool { const invalid = (bunstr.isUTF16() and !bun.simdutf.validate.utf16le(bunstr.utf16())) or (bunstr.isUTF8() and !bun.simdutf.validate.utf8(bunstr.byteSlice())); if (invalid) return false; if (allow_escape) { @@ -3980,7 +3974,7 @@ pub const ShellSrcBuilder = struct { this.outbuf.* = try bun.strings.allocateLatin1IntoUTF8WithList(this.outbuf.*, this.outbuf.items.len, []const u8, latin1); } - pub fn appendJSStrRef(this: *ShellSrcBuilder, bunstr: bun.String) !void { + pub fn appendJSStrRef(this: *ShellSrcBuilder, bunstr: bun.String) bun.OOM!void { const idx = this.jsstrs_to_escape.items.len; const str = std.fmt.bufPrint(this.jsstr_ref_buf[0..], "{s}{d}", .{ LEX_JS_STRING_PREFIX, idx }) catch { @panic("Impossible"); @@ -4319,8 +4313,7 @@ pub const TestingAPIs = struct { const arguments_ = callframe.arguments_old(1); var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const string = arguments.nextEat() orelse { - globalThis.throw("shellInternals.disabledOnPosix: expected 1 arguments, got 0", .{}); - return .zero; + return globalThis.throw("shellInternals.disabledOnPosix: expected 1 arguments, got 0", .{}); }; const bunstr = string.toBunString(globalThis); @@ -4343,16 +4336,14 @@ pub const TestingAPIs = struct { const arguments_ = callframe.arguments_old(2); var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const string_args = arguments.nextEat() orelse { - globalThis.throw("shell_parse: expected 2 arguments, got 0", .{}); - return .zero; + return globalThis.throw("shell_parse: expected 2 arguments, got 0", .{}); }; var arena = std.heap.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); const template_args_js = arguments.nextEat() orelse { - globalThis.throw("shell: expected 2 arguments, got 0", .{}); - return .zero; + return globalThis.throw("shell: expected 2 arguments, got 0", .{}); }; var template_args = template_args_js.arrayIterator(globalThis); var stack_alloc = std.heap.stackFallback(@sizeOf(bun.String) * 4, arena.allocator()); @@ -4371,9 +4362,7 @@ pub const TestingAPIs = struct { } var script = std.ArrayList(u8).init(arena.allocator()); - if (!(try shellCmdFromJS(globalThis, string_args, &template_args, &jsobjs, &jsstrings, &script))) { - return .undefined; - } + try shellCmdFromJS(globalThis, string_args, &template_args, &jsobjs, &jsstrings, &script); const lex_result = brk: { if (bun.strings.isAllASCII(script.items[0..])) { @@ -4415,16 +4404,14 @@ pub const TestingAPIs = struct { const arguments_ = callframe.arguments_old(2); var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); const string_args = arguments.nextEat() orelse { - globalThis.throw("shell_parse: expected 2 arguments, got 0", .{}); - return .zero; + return globalThis.throw("shell_parse: expected 2 arguments, got 0", .{}); }; var arena = bun.ArenaAllocator.init(bun.default_allocator); defer arena.deinit(); const template_args_js = arguments.nextEat() orelse { - globalThis.throw("shell: expected 2 arguments, got 0", .{}); - return .zero; + return globalThis.throw("shell: expected 2 arguments, got 0", .{}); }; var template_args = template_args_js.arrayIterator(globalThis); var stack_alloc = std.heap.stackFallback(@sizeOf(bun.String) * 4, arena.allocator()); @@ -4442,9 +4429,7 @@ pub const TestingAPIs = struct { } } var script = std.ArrayList(u8).init(arena.allocator()); - if (!(try shellCmdFromJS(globalThis, string_args, &template_args, &jsobjs, &jsstrings, &script))) { - return .undefined; - } + try shellCmdFromJS(globalThis, string_args, &template_args, &jsobjs, &jsstrings, &script); var out_parser: ?Parser = null; var out_lex_result: ?LexResult = null; diff --git a/src/sql/postgres.zig b/src/sql/postgres.zig index 09b2cdf61f7b57..026706100e75c9 100644 --- a/src/sql/postgres.zig +++ b/src/sql/postgres.zig @@ -415,7 +415,7 @@ pub const PostgresSQLQuery = struct { pub fn constructor(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*PostgresSQLQuery { _ = callframe; - return globalThis.throw2("PostgresSQLQuery cannot be constructed directly", .{}); + return globalThis.throw("PostgresSQLQuery cannot be constructed directly", .{}); } pub fn estimatedSize(this: *PostgresSQLQuery) usize { @@ -430,19 +430,16 @@ pub const PostgresSQLQuery = struct { const columns = arguments[3]; if (!query.isString()) { - globalThis.throw("query must be a string", .{}); - return .zero; + return globalThis.throw("query must be a string", .{}); } if (values.jsType() != .Array) { - globalThis.throw("values must be an array", .{}); - return .zero; + return globalThis.throw("values must be an array", .{}); } const pending_value = arguments[2]; if (!pending_value.jsType().isArrayLike()) { - globalThis.throwInvalidArgumentType("query", "pendingValue", "Array"); - return .zero; + return globalThis.throwInvalidArgumentType("query", "pendingValue", "Array"); } var ptr = try bun.default_allocator.create(PostgresSQLQuery); @@ -481,14 +478,12 @@ pub const PostgresSQLQuery = struct { var arguments_ = callframe.arguments_old(2); const arguments = arguments_.slice(); var connection = arguments[0].as(PostgresSQLConnection) orelse { - globalObject.throw("connection must be a PostgresSQLConnection", .{}); - return error.JSError; + return globalObject.throw("connection must be a PostgresSQLConnection", .{}); }; var query = arguments[1]; if (!query.isObject()) { - globalObject.throwInvalidArgumentType("run", "query", "Query"); - return error.JSError; + return globalObject.throwInvalidArgumentType("run", "query", "Query"); } this.target.set(globalObject, query); @@ -1356,7 +1351,7 @@ pub const PostgresSQLConnection = struct { pub fn constructor(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!*PostgresSQLConnection { _ = callframe; - return globalObject.throw2("PostgresSQLConnection cannot be constructed directly", .{}); + return globalObject.throw("PostgresSQLConnection cannot be constructed directly", .{}); } comptime { @@ -1414,20 +1409,18 @@ pub const PostgresSQLConnection = struct { var err: uws.create_bun_socket_error_t = .none; tls_ctx = uws.us_create_bun_socket_context(1, vm.uwsLoop(), @sizeOf(*PostgresSQLConnection), context_options, &err) orelse { if (err != .none) { - globalObject.throw("failed to create TLS context", .{}); + return globalObject.throw("failed to create TLS context", .{}); } else { - globalObject.throwValue(err.toJS(globalObject)); + return globalObject.throwValue(err.toJS(globalObject)); } - return .zero; }; if (err != .none) { tls_config.deinit(); - globalObject.throwValue(err.toJS(globalObject)); if (tls_ctx) |ctx| { ctx.deinit(true); } - return .zero; + return globalObject.throwValue(err.toJS(globalObject)); } uws.NewSocketHandler(true).configure(tls_ctx.?, true, *PostgresSQLConnection, SocketHandler(true)); @@ -2609,7 +2602,7 @@ const QueryBindingIterator = union(enum) { this.current_row = JSC.JSObject.getIndex(this.array, globalObject, @intCast(row_i)); if (this.current_row.isEmptyOrUndefinedOrNull()) { if (!globalObject.hasException()) - globalObject.throw("Expected a row to be returned at index {d}", .{row_i}); + return globalObject.throw("Expected a row to be returned at index {d}", .{row_i}) catch null; this.any_failed = true; return null; } @@ -2626,7 +2619,7 @@ const QueryBindingIterator = union(enum) { const property = JSC.JSObject.getIndex(this.columns, globalObject, @intCast(cell_i)); if (property == .zero or property == .undefined) { if (!globalObject.hasException()) - globalObject.throw("Expected a column at index {d} in row {d}", .{ cell_i, row_i }); + return globalObject.throw("Expected a column at index {d} in row {d}", .{ cell_i, row_i }) catch null; this.any_failed = true; return null; } @@ -2634,7 +2627,7 @@ const QueryBindingIterator = union(enum) { const value = this.current_row.getOwnByValue(globalObject, property); if (value == .zero or value == .undefined) { if (!globalObject.hasException()) - globalObject.throw("Expected a value at index {d} in row {d}", .{ cell_i, row_i }); + return globalObject.throw("Expected a value at index {d} in row {d}", .{ cell_i, row_i }) catch null; this.any_failed = true; return null; } diff --git a/src/sql/postgres/postgres_types.zig b/src/sql/postgres/postgres_types.zig index 6a595cafb781e8..498b7f1d0a7044 100644 --- a/src/sql/postgres/postgres_types.zig +++ b/src/sql/postgres/postgres_types.zig @@ -474,8 +474,7 @@ pub const json = struct { defer str.deref(); const parse_result = JSValue.parse(str.toJS(globalObject), globalObject); if (parse_result.isAnyError()) { - globalObject.throwValue(parse_result); - return error.JSError; + return globalObject.throwValue(parse_result); } return parse_result;