diff --git a/src/bake/FrameworkRouter.zig b/src/bake/FrameworkRouter.zig index b689202c2f06dc..81b5219155ac8f 100644 --- a/src/bake/FrameworkRouter.zig +++ b/src/bake/FrameworkRouter.zig @@ -1026,7 +1026,7 @@ pub const JSFrameworkRouter = struct { pub fn match(jsfr: *JSFrameworkRouter, global: *JSGlobalObject, callframe: *JSC.CallFrame) !JSValue { const path_js = callframe.argumentsAsArray(1)[0]; - const path_str = try path_js.toBunString2(global); + const path_str = try path_js.toBunString(global); defer path_str.deref(); const path_slice = path_str.toSlice(bun.default_allocator); defer path_slice.deinit(); diff --git a/src/bake/bake.zig b/src/bake/bake.zig index d21fe1f6340ddd..49a3d0310d0259 100644 --- a/src/bake/bake.zig +++ b/src/bake/bake.zig @@ -263,7 +263,7 @@ pub const Framework = struct { ) !Framework { _ = bundler_options; // autofix if (opts.isString()) { - const str = try opts.toBunString2(global); + const str = try opts.toBunString(global); defer str.deref(); // Deprecated @@ -303,7 +303,7 @@ pub const Framework = struct { return global.throwInvalidArguments("'framework.reactFastRefresh' is missing 'importSource'", .{}); }; - const str = try prop.toBunString2(global); + const str = try prop.toBunString(global); defer str.deref(); break :brk .{ @@ -556,7 +556,7 @@ fn getOptionalString( return null; if (value == .undefined or value == .null) return null; - const str = try value.toBunString2(global); + const str = try value.toBunString(global); return allocations.track(str.toUTF8(arena)); } diff --git a/src/bun.js/ConsoleObject.zig b/src/bun.js/ConsoleObject.zig index cc63da873bc50b..7027861137bce3 100644 --- a/src/bun.js/ConsoleObject.zig +++ b/src/bun.js/ConsoleObject.zig @@ -536,7 +536,7 @@ pub const TablePrinter = struct { var properties_iter = JSC.JSArrayIterator.init(this.properties, globalObject); while (properties_iter.next()) |value| { try columns.append(.{ - .name = value.toBunString(globalObject), + .name = try value.toBunString(globalObject), }); } } diff --git a/src/bun.js/api/BunObject.zig b/src/bun.js/api/BunObject.zig index f89c6f08b271e0..d55f0b21ce8898 100644 --- a/src/bun.js/api/BunObject.zig +++ b/src/bun.js/api/BunObject.zig @@ -267,7 +267,7 @@ pub fn shellEscape(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) b } const jsval = arguments.ptr[0]; - const bunstr = jsval.toBunString(globalThis); + const bunstr = try jsval.toBunString(globalThis); if (globalThis.hasException()) return .zero; defer bunstr.deref(); @@ -299,7 +299,7 @@ pub fn braces(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JS globalThis.throw("braces: expected at least 1 argument, got 0", .{}); return .zero; }; - const brace_str = brace_str_js.toBunString(globalThis); + const brace_str = try brace_str_js.toBunString(globalThis); defer brace_str.deref(); if (globalThis.hasException()) return .zero; @@ -914,9 +914,9 @@ fn doResolve(globalThis: *JSC.JSGlobalObject, arguments: []const JSValue) bun.JS } } - const specifier_str = specifier.toBunString(globalThis); + const specifier_str = try specifier.toBunString(globalThis); defer specifier_str.deref(); - const from_str = from.toBunString(globalThis); + const from_str = try from.toBunString(globalThis); defer from_str.deref(); return doResolveWithArgs( globalThis, @@ -996,10 +996,10 @@ pub fn resolve(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun } export fn Bun__resolve(global: *JSGlobalObject, specifier: JSValue, source: JSValue, is_esm: bool) JSC.JSValue { - const specifier_str = specifier.toBunString(global); + const specifier_str = specifier.toBunString(global) catch return .zero; defer specifier_str.deref(); - const source_str = source.toBunString(global); + const source_str = source.toBunString(global) catch return .zero; defer source_str.deref(); const value = doResolveWithArgs(global, specifier_str, source_str, is_esm, true) catch { @@ -1011,10 +1011,10 @@ export fn Bun__resolve(global: *JSGlobalObject, specifier: JSValue, source: JSVa } export fn Bun__resolveSync(global: *JSGlobalObject, specifier: JSValue, source: JSValue, is_esm: bool) JSC.JSValue { - const specifier_str = specifier.toBunString(global); + const specifier_str = specifier.toBunString(global) catch return .zero; defer specifier_str.deref(); - const source_str = source.toBunString(global); + const source_str = source.toBunString(global) catch return .zero; defer source_str.deref(); return JSC.toJSHostValue(global, doResolveWithArgs(global, specifier_str, source_str, is_esm, true)); @@ -1026,7 +1026,7 @@ export fn Bun__resolveSyncWithStrings(global: *JSGlobalObject, specifier: *bun.S } export fn Bun__resolveSyncWithSource(global: *JSGlobalObject, specifier: JSValue, source: *bun.String, is_esm: bool) JSC.JSValue { - const specifier_str = specifier.toBunString(global); + const specifier_str = specifier.toBunString(global) catch return .zero; defer specifier_str.deref(); return JSC.toJSHostValue(global, doResolveWithArgs(global, specifier_str, source.*, is_esm, true)); } @@ -4306,7 +4306,7 @@ fn stringWidth(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun return JSC.jsNumber(0); } - const str = value.toBunString(globalObject); + const str = try value.toBunString(globalObject); defer str.deref(); var count_ansi_escapes = false; diff --git a/src/bun.js/api/JSTranspiler.zig b/src/bun.js/api/JSTranspiler.zig index 2716bc3968f5a5..c1bd468a42b820 100644 --- a/src/bun.js/api/JSTranspiler.zig +++ b/src/bun.js/api/JSTranspiler.zig @@ -443,7 +443,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std if (!kind.isStringLike()) { tsconfig.jsonStringify(globalThis, 0, &out); } else { - out = tsconfig.toBunString(globalThis); + out = try tsconfig.toBunString(globalThis); } if (out.isEmpty()) break :tsconfig; @@ -486,7 +486,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std if (is_object) { macros.jsonStringify(globalThis, 0, &out); } else { - out = macros.toBunString(globalThis); + out = try macros.toBunString(globalThis); } if (out.isEmpty()) break :macros; diff --git a/src/bun.js/api/bun/udp_socket.zig b/src/bun.js/api/bun/udp_socket.zig index 6e330048a48e0d..bceeb1499ec117 100644 --- a/src/bun.js/api/bun/udp_socket.zig +++ b/src/bun.js/api/bun/udp_socket.zig @@ -132,7 +132,7 @@ pub const UDPSocketConfig = struct { if (!value.isString()) { return globalThis.throwInvalidArguments("Expected \"hostname\" to be a string", .{}); } - const str = value.toBunString(globalThis); + const str = try value.toBunString(globalThis); defer str.deref(); break :brk str.toOwnedSliceZ(default_allocator) catch bun.outOfMemory(); } else { @@ -209,7 +209,7 @@ pub const UDPSocketConfig = struct { }; const connect_port = connect_port_js.coerceToInt32(globalThis); - const str = connect_host_js.toBunString(globalThis); + const str = try connect_host_js.toBunString(globalThis); defer str.deref(); const connect_host = str.toOwnedSliceZ(default_allocator) catch bun.outOfMemory(); @@ -418,7 +418,7 @@ pub const UDPSocket = struct { continue; } if (i % 3 == 2) { - if (!this.parseAddr(globalThis, port, val, &addrs[slice_idx])) { + if (!try this.parseAddr(globalThis, port, val, &addrs[slice_idx])) { return globalThis.throwInvalidArguments("Invalid address", .{}); } addr_ptrs[slice_idx] = &addrs[slice_idx]; @@ -482,7 +482,7 @@ pub const UDPSocket = struct { var addr: std.posix.sockaddr.storage = std.mem.zeroes(std.posix.sockaddr.storage); const addr_ptr = brk: { if (dst) |dest| { - if (!this.parseAddr(globalThis, dest.port, dest.address, &addr)) { + if (!try this.parseAddr(globalThis, dest.port, dest.address, &addr)) { return globalThis.throwInvalidArguments("Invalid address", .{}); } break :brk &addr; @@ -505,12 +505,12 @@ pub const UDPSocket = struct { port_val: JSValue, address_val: JSValue, storage: *std.posix.sockaddr.storage, - ) bool { + ) bun.JSError!bool { _ = this; const number = port_val.coerceToInt32(globalThis); const port: u16 = if (number < 1 or number > 0xffff) 0 else @intCast(number); - const str = address_val.toBunString(globalThis); + const str = try address_val.toBunString(globalThis); defer str.deref(); const address_slice = str.toOwnedSliceZ(default_allocator) catch bun.outOfMemory(); defer default_allocator.free(address_slice); @@ -685,7 +685,7 @@ pub const UDPSocket = struct { return globalThis.throwInvalidArguments("Expected 2 arguments", .{}); } - const str = args.ptr[0].toBunString(globalThis); + const str = try args.ptr[0].toBunString(globalThis); defer str.deref(); const connect_host = str.toOwnedSliceZ(default_allocator) catch bun.outOfMemory(); defer default_allocator.free(connect_host); diff --git a/src/bun.js/base.zig b/src/bun.js/base.zig index c8bf5f4ea21e95..31b90899d994a8 100644 --- a/src/bun.js/base.zig +++ b/src/bun.js/base.zig @@ -1387,7 +1387,7 @@ pub const BinaryType = enum(u4) { pub fn fromJSValue(globalThis: *JSC.JSGlobalObject, input: JSValue) bun.JSError!?BinaryType { if (input.isString()) { - return Map.getWithEql(try input.toBunString2(globalThis), bun.String.eqlComptime); + return Map.getWithEql(try input.toBunString(globalThis), bun.String.eqlComptime); } return null; diff --git a/src/bun.js/bindings/bindings.zig b/src/bun.js/bindings/bindings.zig index cfeaee4b8983c0..a2f662ec47a093 100644 --- a/src/bun.js/bindings/bindings.zig +++ b/src/bun.js/bindings/bindings.zig @@ -5065,16 +5065,10 @@ pub const JSValue = enum(i64) { } /// Increments the reference count, you must call `.deref()` or it will leak memory. - /// Returns String.Dead on error. Deprecated in favor of `toBunString2` - pub fn toBunString(this: JSValue, globalObject: *JSC.JSGlobalObject) bun.String { + pub fn toBunString(this: JSValue, globalObject: *JSC.JSGlobalObject) JSError!bun.String { return bun.String.fromJS(this, globalObject); } - /// Increments the reference count, you must call `.deref()` or it will leak memory. - pub fn toBunString2(this: JSValue, globalObject: *JSC.JSGlobalObject) JSError!bun.String { - return bun.String.fromJS2(this, globalObject); - } - /// this: RegExp value /// other: string value pub fn toMatch(this: JSValue, global: *JSGlobalObject, other: JSValue) bool { @@ -5127,7 +5121,7 @@ pub const JSValue = enum(i64) { }); } - /// Deprecated: replace with 'toBunString2' + /// Deprecated: replace with 'toBunString' pub inline fn getZigString(this: JSValue, global: *JSGlobalObject) ZigString { var str = ZigString.init(""); this.toZigString(&str, global); @@ -5142,7 +5136,7 @@ pub const JSValue = enum(i64) { /// /// To handle exceptions, use `JSValue.toSliceOrNull`. pub inline fn toSlice(this: JSValue, global: *JSGlobalObject, allocator: std.mem.Allocator) ZigString.Slice { - const str = bun.String.fromJS(this, global); + const str = bun.String.fromJS_unsafe(this, global); defer str.deref(); // This keeps the WTF::StringImpl alive if it was originally a latin1 @@ -5155,7 +5149,7 @@ pub const JSValue = enum(i64) { /// Convert a JSValue to a string, potentially calling `toString` on the /// JSValue in JavaScript. Can throw an error. pub fn toSlice2(this: JSValue, global: *JSGlobalObject, allocator: std.mem.Allocator) JSError!ZigString.Slice { - const str = try bun.String.fromJS2(this, global); + const str = try bun.String.fromJS(this, global); defer str.deref(); // This keeps the WTF::StringImpl alive if it was originally a latin1 @@ -5185,14 +5179,14 @@ pub const JSValue = enum(i64) { /// Call `toString()` on the JSValue and clone the result. pub fn toSliceOrNull(this: JSValue, globalThis: *JSGlobalObject) bun.JSError!ZigString.Slice { - const str = try bun.String.fromJS2(this, globalThis); + const str = try bun.String.fromJS(this, globalThis); defer str.deref(); return str.toUTF8(bun.default_allocator); } /// Call `toString()` on the JSValue and clone the result. pub fn toSliceOrNullWithAllocator(this: JSValue, globalThis: *JSGlobalObject, allocator: std.mem.Allocator) bun.JSError!ZigString.Slice { - const str = try bun.String.fromJS2(this, globalThis); + const str = try bun.String.fromJS(this, globalThis); defer str.deref(); return str.toUTF8(allocator); } @@ -5512,7 +5506,7 @@ pub const JSValue = enum(i64) { return error.JSError; } - const str = prop.toBunString(global); + const str = try prop.toBunString(global); if (global.hasException()) { str.deref(); return error.JSError; @@ -5829,7 +5823,7 @@ pub const JSValue = enum(i64) { globalObject: *JSC.JSGlobalObject, pub fn format(this: StringFormatter, comptime text: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void { - const str = this.value.toBunString(this.globalObject); + const str = try this.value.toBunString(this.globalObject); defer str.deref(); try str.format(text, opts, writer); } @@ -6754,6 +6748,7 @@ pub const CallFrame = opaque { pub fn arguments_old(self: *const CallFrame, comptime max: usize) Arguments(max) { const len = self.argumentsCount(); const ptr = self.argumentsPtr(); + if (max > 10) @compileError(std.fmt.comptimePrint("arguments({d})", .{max})); return switch (@as(u4, @min(len, max))) { 0 => .{ .ptr = undefined, .len = 0 }, inline 1...10 => |count| Arguments(max).init(comptime @min(count, max), ptr), @@ -6764,6 +6759,7 @@ pub const CallFrame = opaque { pub fn argumentsUndef(self: *const CallFrame, comptime max: usize) Arguments(max) { const len = self.argumentsCount(); const ptr = self.argumentsPtr(); + if (max > 9) @compileError(std.fmt.comptimePrint("arguments({d})", .{max})); return switch (@as(u4, @min(len, max))) { 0 => .{ .ptr = .{.undefined} ** max, .len = 0 }, inline 1...9 => |count| Arguments(max).initUndef(@min(count, max), ptr), diff --git a/src/bun.js/javascript.zig b/src/bun.js/javascript.zig index bd2197511ca156..2316927b2b70f6 100644 --- a/src/bun.js/javascript.zig +++ b/src/bun.js/javascript.zig @@ -1365,11 +1365,10 @@ pub const VirtualMachine = struct { pub fn specifierIsEvalEntryPoint(this: *VirtualMachine, specifier: JSValue) callconv(.C) bool { if (this.module_loader.eval_source) |eval_source| { - var specifier_str = specifier.toBunString(this.global); + var specifier_str = specifier.toBunString(this.global) catch return false; defer specifier_str.deref(); return specifier_str.eqlUTF8(eval_source.path.text); } - return false; } diff --git a/src/bun.js/node/node_fs.zig b/src/bun.js/node/node_fs.zig index ec043e44ce1d6e..88545c3c7108e4 100644 --- a/src/bun.js/node/node_fs.zig +++ b/src/bun.js/node/node_fs.zig @@ -1852,7 +1852,7 @@ pub const Arguments = struct { // will automatically be normalized to absolute path. if (next_val.isString()) { arguments.eat(); - var str = next_val.toBunString(ctx); + var str = try next_val.toBunString(ctx); defer str.deref(); if (str.eqlComptime("dir")) break :link_type .dir; if (str.eqlComptime("file")) break :link_type .file; diff --git a/src/bun.js/node/types.zig b/src/bun.js/node/types.zig index 52ff09cd61a9b6..b64d9c62f0b9f6 100644 --- a/src/bun.js/node/types.zig +++ b/src/bun.js/node/types.zig @@ -458,7 +458,7 @@ pub const StringOrBuffer = union(enum) { return try allocator.dupe(u8, array_buffer.byteSlice()); } - const str = try bun.String.fromJS2(value, globalObject); + const str = try bun.String.fromJS(value, globalObject); defer str.deref(); const result = try str.toOwnedSlice(allocator); @@ -534,7 +534,7 @@ pub const StringOrBuffer = union(enum) { .StringObject, .DerivedStringObject, => { - const str = bun.String.fromJS(value, global); + const str = bun.String.fromJS_unsafe(value, global); if (is_async) { defer str.deref(); @@ -592,7 +592,7 @@ pub const StringOrBuffer = union(enum) { return fromJSMaybeAsync(global, allocator, value, is_async); } - var str = try bun.String.fromJS2(value, global); + var str = try bun.String.fromJS(value, global); defer str.deref(); if (str.isEmpty()) { return fromJSMaybeAsync(global, allocator, value, is_async); @@ -690,7 +690,7 @@ pub const Encoding = enum(u8) { } pub fn fromJSWithDefaultOnEmpty(value: JSC.JSValue, globalObject: *JSC.JSGlobalObject, default: Encoding) bun.JSError!?Encoding { - const str = try bun.String.fromJS2(value, globalObject); + const str = try bun.String.fromJS(value, globalObject); defer str.deref(); if (str.isEmpty()) { return default; @@ -954,7 +954,7 @@ pub const PathLike = union(enum) { JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject, => { - var str = arg.toBunString(ctx); + var str = try arg.toBunString(ctx); defer str.deref(); arguments.eat(); diff --git a/src/bun.js/node/util/parse_args.zig b/src/bun.js/node/util/parse_args.zig index a7d2c1895da3d5..c673f151cf5903 100644 --- a/src/bun.js/node/util/parse_args.zig +++ b/src/bun.js/node/util/parse_args.zig @@ -45,7 +45,7 @@ const ValueRef = union(Tag) { const Tag = enum { jsvalue, bunstr }; - pub fn asBunString(this: ValueRef, globalObject: *JSGlobalObject) bun.String { + pub fn asBunString(this: ValueRef, globalObject: *JSGlobalObject) bun.JSError!bun.String { return switch (this) { .jsvalue => |str| str.toBunString(globalObject), .bunstr => |str| return str, @@ -98,7 +98,7 @@ const OptionToken = struct { /// Formats the raw name of the arg (includes any dashes and excludes inline values) pub fn format(this: RawNameFormatter, comptime fmt: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void { const token = this.token; - const raw = token.raw.asBunString(this.globalThis); + const raw = try token.raw.asBunString(this.globalThis); if (token.optgroup_idx) |optgroup_idx| { try raw.substringWithLen(optgroup_idx, optgroup_idx + 1).format(fmt, opts, writer); } else { @@ -121,9 +121,9 @@ const OptionToken = struct { }; /// Returns the raw name of the arg (includes any dashes and excludes inline values), as a JSValue - fn makeRawNameJSValue(this: OptionToken, globalThis: *JSGlobalObject) JSValue { + fn makeRawNameJSValue(this: OptionToken, globalThis: *JSGlobalObject) bun.JSError!JSValue { if (this.optgroup_idx) |optgroup_idx| { - const raw = this.raw.asBunString(globalThis); + const raw = try this.raw.asBunString(globalThis); var buf: [8]u8 = undefined; const str = std.fmt.bufPrint(&buf, "-{}", .{raw.substringWithLen(optgroup_idx, optgroup_idx + 1)}) catch unreachable; return String.fromUTF8(str).toJS(globalThis); @@ -133,12 +133,12 @@ const OptionToken = struct { return this.raw.asJSValue(globalThis); }, .short_option_and_value => { - var raw = this.raw.asBunString(globalThis); + var raw = try this.raw.asBunString(globalThis); var substr = raw.substringWithLen(0, 2); return substr.toJS(globalThis); }, .long_option_and_value => { - var raw = this.raw.asBunString(globalThis); + var raw = try this.raw.asBunString(globalThis); const equal_index = raw.indexOfAsciiChar('=').?; var substr = raw.substringWithLen(0, equal_index); return substr.toJS(globalThis); @@ -184,12 +184,12 @@ fn getDefaultArgs(globalThis: *JSGlobalObject) !ArgsSlice { /// In strict mode, throw for possible usage errors like "--foo --bar" where foo was defined as a string-valued arg fn checkOptionLikeValue(globalThis: *JSGlobalObject, token: OptionToken) bun.JSError!void { - if (!token.inline_value and isOptionLikeValue(token.value.asBunString(globalThis))) { + if (!token.inline_value and isOptionLikeValue(try token.value.asBunString(globalThis))) { const raw_name = OptionToken.RawNameFormatter{ .token = token, .globalThis = globalThis }; // Only show short example if user used short option. var err: JSValue = undefined; - if (token.raw.asBunString(globalThis).hasPrefixComptime("--")) { + if ((try token.raw.asBunString(globalThis)).hasPrefixComptime("--")) { err = JSC.toTypeError( .ERR_PARSE_ARGS_INVALID_OPTION_VALUE, "Option '{}' argument is ambiguous.\nDid you forget to specify the option argument for '{}'?\nTo specify an option argument starting with a dash use '{}=-XYZ'.", @@ -197,7 +197,7 @@ fn checkOptionLikeValue(globalThis: *JSGlobalObject, token: OptionToken) bun.JSE globalThis, ); } else { - const token_name = token.name.asBunString(globalThis); + const token_name = try token.name.asBunString(globalThis); err = JSC.toTypeError( .ERR_PARSE_ARGS_INVALID_OPTION_VALUE, "Option '{}' argument is ambiguous.\nDid you forget to specify the option argument for '{}'?\nTo specify an option argument starting with a dash use '--{}=-XYZ' or '{}-XYZ'.", @@ -223,7 +223,7 @@ fn checkOptionUsage(globalThis: *JSGlobalObject, options: []const OptionDefiniti if (!option.short_name.isEmpty()) "-" else "", option.short_name, if (!option.short_name.isEmpty()) ", " else "", - token.name.asBunString(globalThis), + try token.name.asBunString(globalThis), }, globalThis, ); @@ -238,7 +238,7 @@ fn checkOptionUsage(globalThis: *JSGlobalObject, options: []const OptionDefiniti if (!option.short_name.isEmpty()) "-" else "", option.short_name, if (!option.short_name.isEmpty()) ", " else "", - token.name.asBunString(globalThis), + try token.name.asBunString(globalThis), }, globalThis, ); @@ -271,8 +271,8 @@ fn checkOptionUsage(globalThis: *JSGlobalObject, options: []const OptionDefiniti /// - `option_value`: value from user args /// - `options`: option configs, from `parseArgs({ options })` /// - `values`: option values returned in `values` by parseArgs -fn storeOption(globalThis: *JSGlobalObject, option_name: ValueRef, option_value: ValueRef, option_idx: ?usize, options: []const OptionDefinition, values: JSValue) void { - var key = option_name.asBunString(globalThis); +fn storeOption(globalThis: *JSGlobalObject, option_name: ValueRef, option_value: ValueRef, option_idx: ?usize, options: []const OptionDefinition, values: JSValue) bun.JSError!void { + var key = try option_name.asBunString(globalThis); if (key.eqlComptime("__proto__")) { return; } @@ -324,7 +324,7 @@ fn parseOptionDefinitions(globalThis: *JSGlobalObject, options_obj: JSValue, opt if (obj.getOwn(globalThis, "short")) |short_option| { try validateString(globalThis, short_option, "options.{s}.short", .{option.long_name}); - var short_option_str = short_option.toBunString(globalThis); + var short_option_str = try 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); @@ -392,7 +392,7 @@ fn tokenizeArgs( var index: u32 = 0; while (index < num_args) : (index += 1) { const arg_ref: ValueRef = ValueRef{ .jsvalue = args.get(globalThis, index) }; - const arg = arg_ref.asBunString(globalThis); + const arg = try arg_ref.asBunString(globalThis); const token_rawtype = classifyToken(arg, options); log(" [Arg #{d}] {s} ({s})", .{ index, @tagName(token_rawtype), arg }); @@ -588,14 +588,14 @@ const ParseArgsState = struct { try checkOptionUsage(globalThis, this.option_defs, this.allow_positionals, token); try checkOptionLikeValue(globalThis, token); } - storeOption(globalThis, token.name, token.value, token.option_idx, this.option_defs, this.values); + try storeOption(globalThis, token.name, token.value, token.option_idx, this.option_defs, this.values); }, .positional => |token| { if (!this.allow_positionals) { const err = JSC.toTypeError( .ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL, "Unexpected argument '{s}'. This command does not take positional arguments", - .{token.value.asBunString(globalThis)}, + .{try token.value.asBunString(globalThis)}, globalThis, ); globalThis.vm().throwError(globalThis, err); @@ -630,7 +630,7 @@ const ParseArgsState = struct { .option => |token| { obj.put(globalThis, ZigString.static("index"), JSValue.jsNumber(token.index)); obj.put(globalThis, ZigString.static("name"), token.name.asJSValue(globalThis)); - obj.put(globalThis, ZigString.static("rawName"), token.makeRawNameJSValue(globalThis)); + obj.put(globalThis, ZigString.static("rawName"), try token.makeRawNameJSValue(globalThis)); // value exists only for string options, otherwise the property exists with "undefined" as value var value = token.value.asJSValue(globalThis); diff --git a/src/bun.js/node/util/validators.zig b/src/bun.js/node/util/validators.zig index 807e9e596884bb..ab28a418df787d 100644 --- a/src/bun.js/node/util/validators.zig +++ b/src/bun.js/node/util/validators.zig @@ -228,7 +228,7 @@ pub fn validateUndefined(globalThis: *JSGlobalObject, value: JSValue, comptime n } pub fn validateStringEnum(comptime T: type, globalThis: *JSGlobalObject, value: JSValue, comptime name_fmt: string, name_args: anytype) bun.JSError!T { - const str = try value.toBunString2(globalThis); + const str = try value.toBunString(globalThis); defer str.deref(); inline for (@typeInfo(T).Enum.fields) |enum_field| { if (str.eqlComptime(enum_field.name)) diff --git a/src/bun.js/test/expect.zig b/src/bun.js/test/expect.zig index 34fc02a4b5037e..fe67fe8d3d1390 100644 --- a/src/bun.js/test/expect.zig +++ b/src/bun.js/test/expect.zig @@ -368,7 +368,7 @@ pub const Expect = struct { var custom_label = bun.String.empty; if (arguments.len > 1) { if (arguments[1].isString() or arguments[1].implementsToString(globalThis)) { - const label = arguments[1].toBunString(globalThis); + const label = try arguments[1].toBunString(globalThis); if (globalThis.hasException()) return .zero; custom_label = label; } @@ -2993,7 +2993,7 @@ pub const Expect = struct { return globalThis.throwInvalidArguments("toBeTypeOf() requires a string argument", .{}); } - const expected_type = expected.toBunString(globalThis); + const expected_type = try expected.toBunString(globalThis); defer expected_type.deref(); incrementExpectCallCounter(); @@ -4672,7 +4672,7 @@ pub const Expect = struct { if (message.isUndefined()) { message_text = bun.String.static("No message was specified for this matcher."); } else if (message.isString()) { - message_text = message.toBunString(globalThis); + message_text = message.toBunString(globalThis) catch return false; } else { if (comptime Environment.allow_assert) assert(message.isCallable(globalThis.vm())); // checked above @@ -4840,19 +4840,18 @@ 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.throwValue2(error_value); } if (arg.isString()) { - const error_value = arg.toBunString(globalThis).toErrorInstance(globalThis); + const error_string = try arg.toBunString(globalThis); + defer error_string.deref(); + const error_value = error_string.toErrorInstance(globalThis); error_value.put(globalThis, ZigString.static("name"), bun.String.init("UnreachableError").toJS(globalThis)); - globalThis.throwValue(error_value); - return .zero; + return globalThis.throwValue2(error_value); } - globalThis.throwValue(arg); - return .zero; + return globalThis.throwValue2(arg); } }; @@ -5357,7 +5356,7 @@ pub const ExpectCustomAsymmetricMatcher = struct { } return err; }; - try writer.print("{}", .{result.toBunString(globalThis)}); + try writer.print("{}", .{try result.toBunString(globalThis)}); } } return false; @@ -5510,7 +5509,7 @@ pub const ExpectMatcherUtils = struct { globalThis.throw("matcherHint: the first argument (matcher name) must be a string", .{}); return .zero; } - const matcher_name = arguments[0].toBunString(globalThis); + const matcher_name = try arguments[0].toBunString(globalThis); defer matcher_name.deref(); const received = if (arguments.len > 1) arguments[1] else bun.String.static("received").toJS(globalThis); diff --git a/src/bun.js/test/pretty_format.zig b/src/bun.js/test/pretty_format.zig index dd119384c7a8bf..c9bc3a03296758 100644 --- a/src/bun.js/test/pretty_format.zig +++ b/src/bun.js/test/pretty_format.zig @@ -1106,7 +1106,7 @@ pub const JestPrettyFormat = struct { defer message_string.deref(); if (value.fastGet(this.globalThis, .message)) |message_prop| { - message_string = message_prop.toBunString(this.globalThis); + message_string = message_prop.toBunString(this.globalThis) catch bun.String.static("(threw exception creating message)"); } if (message_string.isEmpty()) { diff --git a/src/bun.js/web_worker.zig b/src/bun.js/web_worker.zig index b91b9174968865..7b32973bde5d75 100644 --- a/src/bun.js/web_worker.zig +++ b/src/bun.js/web_worker.zig @@ -82,7 +82,7 @@ pub const WebWorker = struct { str: []const u8, error_message: *bun.String, logger: *bun.logger.Log, - ) ?[]const u8 { + ) bun.JSError!?[]const u8 { if (parent.standalone_module_graph) |graph| { if (graph.find(str) != null) { return str; @@ -153,7 +153,7 @@ pub const WebWorker = struct { } var resolved_entry_point: bun.resolver.Result = parent.bundler.resolveEntryPoint(str) catch { - const out = logger.toJS(parent.global, bun.default_allocator, "Error resolving Worker entry point").toBunString(parent.global); + const out = try logger.toJS(parent.global, bun.default_allocator, "Error resolving Worker entry point").toBunString(parent.global); error_message.* = out; return null; }; @@ -197,15 +197,13 @@ pub const WebWorker = struct { else &.{}; - const path = resolveEntryPointSpecifier(parent, spec_slice.slice(), error_message, &temp_log) orelse { - return null; - }; + const path = (resolveEntryPointSpecifier(parent, spec_slice.slice(), error_message, &temp_log) catch return null) orelse return null; var preloads = std.ArrayList([]const u8).initCapacity(bun.default_allocator, preload_modules_len) catch bun.outOfMemory(); for (preload_modules) |module| { const utf8_slice = module.toUTF8(bun.default_allocator); defer utf8_slice.deinit(); - if (resolveEntryPointSpecifier(parent, utf8_slice.slice(), error_message, &temp_log)) |preload| { + if (resolveEntryPointSpecifier(parent, utf8_slice.slice(), error_message, &temp_log) catch return null) |preload| { preloads.append(bun.default_allocator.dupe(u8, preload) catch bun.outOfMemory()) catch bun.outOfMemory(); } @@ -328,7 +326,7 @@ pub const WebWorker = struct { var vm = this.vm orelse return; if (vm.log.msgs.items.len == 0) return; const err = vm.log.toJS(vm.global, bun.default_allocator, "Error in worker"); - const str = err.toBunString(vm.global); + const str = err.toBunString(vm.global) catch bun.String.static("(threw exception creating message)"); defer str.deref(); WebWorker__dispatchError(vm.global, this.cpp_worker, str, err); } diff --git a/src/bun.js/webcore/ObjectURLRegistry.zig b/src/bun.js/webcore/ObjectURLRegistry.zig index 846c1c04343bd9..788ddca7ec3748 100644 --- a/src/bun.js/webcore/ObjectURLRegistry.zig +++ b/src/bun.js/webcore/ObjectURLRegistry.zig @@ -119,14 +119,14 @@ fn Bun__revokeObjectURL_(globalObject: *JSC.JSGlobalObject, callframe: *JSC.Call if (!arguments.ptr[0].isString()) { return globalObject.throwInvalidArguments("revokeObjectURL expects a string", .{}); } - const str = arguments.ptr[0].toBunString(globalObject); + const str = try arguments.ptr[0].toBunString(globalObject); + defer str.deref(); if (!str.hasPrefixComptime("blob:")) { return JSC.JSValue.undefined; } const slice = str.toUTF8WithoutRef(bun.default_allocator); defer slice.deinit(); - defer str.deref(); const sliced = slice.slice(); if (sliced.len < "blob:".len + UUID.stringLength) { @@ -149,7 +149,7 @@ fn jsFunctionResolveObjectURL_(globalObject: *JSC.JSGlobalObject, callframe: *JS if (arguments.len < 1) { return JSC.JSValue.undefined; } - const str = arguments.ptr[0].toBunString(globalObject); + const str = try arguments.ptr[0].toBunString(globalObject); defer str.deref(); if (globalObject.hasException()) { diff --git a/src/bun.js/webcore/blob.zig b/src/bun.js/webcore/blob.zig index 2b6e85b5086fbf..21b3c756869c26 100644 --- a/src/bun.js/webcore/blob.zig +++ b/src/bun.js/webcore/blob.zig @@ -1055,7 +1055,7 @@ pub const Blob = struct { const len = data.getLength(globalThis); if (len < 256 * 1024) { - const str = data.toBunString(globalThis); + const str = try data.toBunString(globalThis); defer str.deref(); const pathlike: JSC.Node.PathOrFileDescriptor = if (path_or_blob == .path) @@ -4575,7 +4575,7 @@ pub const Blob = struct { JSC.JSValue.JSType.DerivedStringObject, => { if (!fail_if_top_value_is_not_typed_array_like) { - var str = top_value.toBunString(global); + var str = try top_value.toBunString(global); defer str.deref(); const bytes, const ascii = try str.toOwnedSliceReturningAllASCII(bun.default_allocator); return Blob.initWithAllASCII(bytes, bun.default_allocator, global, ascii); diff --git a/src/bun.js/webcore/body.zig b/src/bun.js/webcore/body.zig index 2af66da2321bef..6073487238c003 100644 --- a/src/bun.js/webcore/body.zig +++ b/src/bun.js/webcore/body.zig @@ -542,7 +542,7 @@ pub const Body = struct { const js_type = value.jsType(); if (js_type.isStringLike()) { - var str = value.toBunString(globalThis); + var str = try value.toBunString(globalThis); if (str.length() == 0) { return Body.Value{ .Empty = {}, diff --git a/src/bun.js/webcore/request.zig b/src/bun.js/webcore/request.zig index f2c45d305a1283..6daecc41cff1dd 100644 --- a/src/bun.js/webcore/request.zig +++ b/src/bun.js/webcore/request.zig @@ -558,7 +558,7 @@ pub const Request = struct { url_or_object.as(JSC.DOMURL) != null; if (is_first_argument_a_url) { - const str = try bun.String.fromJS2(arguments[0], globalThis); + const str = try bun.String.fromJS(arguments[0], globalThis); req.url = str; if (!req.url.isEmpty()) @@ -660,7 +660,7 @@ pub const Request = struct { if (!fields.contains(.url)) { if (value.fastGet(globalThis, .url)) |url| { - req.url = bun.String.fromJS(url, globalThis); + req.url = try bun.String.fromJS(url, globalThis); if (!req.url.isEmpty()) fields.insert(.url); @@ -668,7 +668,7 @@ pub const Request = struct { } else if (@intFromEnum(value) == @intFromEnum(values_to_try[values_to_try.len - 1]) and !is_first_argument_a_url and value.implementsToString(globalThis)) { - const str = bun.String.tryFromJS(value, globalThis) orelse return error.JSError; + const str = try bun.String.fromJS(value, globalThis); req.url = str; if (!req.url.isEmpty()) fields.insert(.url); diff --git a/src/bun.js/webcore/response.zig b/src/bun.js/webcore/response.zig index 9be1fd22a2db76..121572f0af9b84 100644 --- a/src/bun.js/webcore/response.zig +++ b/src/bun.js/webcore/response.zig @@ -644,7 +644,7 @@ pub const Response = struct { } if (response_init.fastGet(globalThis, .statusText)) |status_text| { - result.status_text = bun.String.fromJS(status_text, globalThis); + result.status_text = try bun.String.fromJS(status_text, globalThis); } if (globalThis.hasException()) { @@ -1951,7 +1951,7 @@ pub const Fetch = struct { const StringOrURL = struct { pub fn fromJS(value: JSC.JSValue, globalThis: *JSC.JSGlobalObject) bun.JSError!?bun.String { if (value.isString()) { - return try bun.String.fromJS2(value, globalThis); + return try bun.String.fromJS(value, globalThis); } const out = try JSC.URL.hrefFromJS(value, globalThis); @@ -2111,7 +2111,7 @@ pub const Fetch = struct { if (request_init_object) |request_init| { if (request_init.fastGet(globalThis, .url)) |url_| { if (!url_.isUndefined()) { - break :extract_url try bun.String.fromJS2(url_, globalThis); + break :extract_url try bun.String.fromJS(url_, globalThis); } } } diff --git a/src/bundler.zig b/src/bundler.zig index 5a11d98b28de5a..d63e67cf7f07fe 100644 --- a/src/bundler.zig +++ b/src/bundler.zig @@ -174,7 +174,7 @@ pub const PluginRunner = struct { return null; } - const file_path = path_value.toBunString(global); + const file_path = try path_value.toBunString(global); defer file_path.deref(); if (file_path.length() == 0) { @@ -206,7 +206,7 @@ pub const PluginRunner = struct { return null; } - const namespace_str = namespace_value.toBunString(global); + const namespace_str = try namespace_value.toBunString(global); if (namespace_str.length() == 0) { namespace_str.deref(); break :brk bun.String.init("file"); @@ -269,7 +269,7 @@ pub const PluginRunner = struct { ); } - const file_path = path_value.toBunString(global); + const file_path = try path_value.toBunString(global); if (file_path.length() == 0) { return JSC.ErrorableString.err( @@ -298,7 +298,7 @@ pub const PluginRunner = struct { ); } - const namespace_str = namespace_value.toBunString(global); + const namespace_str = try namespace_value.toBunString(global); if (namespace_str.length() == 0) { break :brk bun.String.static("file"); } @@ -334,7 +334,7 @@ pub const PluginRunner = struct { .{ user_namespace, file_path }, ) catch unreachable; var out_ = bun.String.init(combined_string); - const out = out_.toJS(this.global_object).toBunString(this.global_object); + const out = try out_.toJS(this.global_object).toBunString(this.global_object); this.allocator.free(combined_string); return JSC.ErrorableString.ok(out); } diff --git a/src/cli/pack_command.zig b/src/cli/pack_command.zig index 73fdd87118326d..295bd265daa703 100644 --- a/src/cli/pack_command.zig +++ b/src/cli/pack_command.zig @@ -2305,7 +2305,7 @@ pub const bindings = struct { return .zero; } - const tarball_path_str = args[0].toBunString(global); + const tarball_path_str = try args[0].toBunString(global); defer tarball_path_str.deref(); const tarball_path = tarball_path_str.toUTF8(bun.default_allocator); diff --git a/src/comptime_string_map.zig b/src/comptime_string_map.zig index f5cecafc37eed0..5b4bee6b1ba9da 100644 --- a/src/comptime_string_map.zig +++ b/src/comptime_string_map.zig @@ -173,7 +173,7 @@ pub fn ComptimeStringMapWithKeyType(comptime KeyType: type, comptime V: type, co } } - const str = bun.String.fromJS(input, globalThis); + const str = bun.String.fromJS_unsafe(input, globalThis); bun.assert(str.tag != .Dead); defer str.deref(); return getWithEql(str, bun.String.eqlComptime); @@ -187,7 +187,7 @@ pub fn ComptimeStringMapWithKeyType(comptime KeyType: type, comptime V: type, co } } - const str = bun.String.fromJS(input, globalThis); + const str = bun.String.fromJS_unsafe(input, globalThis); bun.assert(str.tag != .Dead); defer str.deref(); return str.inMapCaseInsensitive(@This()); diff --git a/src/css/css_internals.zig b/src/css/css_internals.zig index 9445c8ab7c0762..402d60842321d2 100644 --- a/src/css/css_internals.zig +++ b/src/css/css_internals.zig @@ -46,7 +46,7 @@ pub fn testingImpl(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, c globalThis.throw("minifyTestWithOptions: expected source to be a string", .{}); return .zero; } - const source_bunstr = source_arg.toBunString(globalThis); + const source_bunstr = try source_arg.toBunString(globalThis); defer source_bunstr.deref(); const source = source_bunstr.toUTF8(bun.default_allocator); defer source.deinit(); @@ -59,7 +59,7 @@ pub fn testingImpl(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, c globalThis.throw("minifyTestWithOptions: expected `expected` arg to be a string", .{}); return .zero; } - const expected_bunstr = expected_arg.toBunString(globalThis); + const expected_bunstr = try expected_arg.toBunString(globalThis); defer expected_bunstr.deref(); const expected = expected_bunstr.toUTF8(bun.default_allocator); defer expected.deinit(); @@ -212,7 +212,7 @@ pub fn attrTest(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. globalThis.throw("attrTest: expected source to be a string", .{}); return .zero; } - const source_bunstr = source_arg.toBunString(globalThis); + const source_bunstr = try source_arg.toBunString(globalThis); defer source_bunstr.deref(); const source = source_bunstr.toUTF8(bun.default_allocator); defer source.deinit(); @@ -225,7 +225,7 @@ pub fn attrTest(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun. globalThis.throw("attrTest: expected `expected` arg to be a string", .{}); return .zero; } - const expected_bunstr = expected_arg.toBunString(globalThis); + const expected_bunstr = try expected_arg.toBunString(globalThis); defer expected_bunstr.deref(); const expected = expected_bunstr.toUTF8(bun.default_allocator); defer expected.deinit(); diff --git a/src/ini.zig b/src/ini.zig index 92cefeae545c7f..48fc4906dd0ff6 100644 --- a/src/ini.zig +++ b/src/ini.zig @@ -514,7 +514,7 @@ pub const IniTestingAPIs = struct { callframe: *JSC.CallFrame, ) bun.JSError!JSC.JSValue { const arg = callframe.argument(0); - const npmrc_contents = arg.toBunString(globalThis); + const npmrc_contents = try arg.toBunString(globalThis); defer npmrc_contents.deref(); const npmrc_utf8 = npmrc_contents.toUTF8(bun.default_allocator); defer npmrc_utf8.deinit(); @@ -604,7 +604,7 @@ pub const IniTestingAPIs = struct { const arguments = arguments_.slice(); const jsstr = arguments[0]; - const bunstr = jsstr.toBunString(globalThis); + const bunstr = try jsstr.toBunString(globalThis); defer bunstr.deref(); const utf8str = bunstr.toUTF8(bun.default_allocator); defer utf8str.deinit(); diff --git a/src/install/npm.zig b/src/install/npm.zig index 74af90267879b7..f72eac6303cd62 100644 --- a/src/install/npm.zig +++ b/src/install/npm.zig @@ -1290,13 +1290,13 @@ pub const PackageManifest = struct { return .zero; } - const manifest_filename_str = args[0].toBunString(global); + const manifest_filename_str = try args[0].toBunString(global); defer manifest_filename_str.deref(); const manifest_filename = manifest_filename_str.toUTF8(bun.default_allocator); defer manifest_filename.deinit(); - const registry_str = args[1].toBunString(global); + const registry_str = try args[1].toBunString(global); defer registry_str.deref(); const registry = registry_str.toUTF8(bun.default_allocator); diff --git a/src/js_ast.zig b/src/js_ast.zig index c7713a3ddeeeed..5fe99535fb8709 100644 --- a/src/js_ast.zig +++ b/src/js_ast.zig @@ -8391,7 +8391,7 @@ pub const Macro = struct { return Expr.init(E.Number, E.Number{ .value = value.asNumber() }, this.caller.loc); }, .String => { - var bun_str = value.toBunString(this.global); + var bun_str = try value.toBunString(this.global); defer bun_str.deref(); // encode into utf16 so the printer escapes the string correctly @@ -8974,7 +8974,7 @@ fn stringToEquivalentNumberValue(str: []const u8) f64 { // STry | 384 // -- ESBuild bit sizes -const ToJSError = error{ +const ToJSError = bun.JSError || error{ @"Cannot convert argument type to JS", @"Cannot convert identifier to JS. Try a statically-known value", MacroError, diff --git a/src/logger.zig b/src/logger.zig index 3755bf16000614..a7e06c27366f6e 100644 --- a/src/logger.zig +++ b/src/logger.zig @@ -388,12 +388,12 @@ pub const Msg = struct { notes: []Data = &.{}, redact_sensitive_information: bool = false, - pub fn fromJS(allocator: std.mem.Allocator, globalObject: *bun.JSC.JSGlobalObject, file: string, err: bun.JSC.JSValue) OOM!Msg { + pub fn fromJS(allocator: std.mem.Allocator, globalObject: *bun.JSC.JSGlobalObject, file: string, err: bun.JSC.JSValue) JSError!Msg { var zig_exception_holder: bun.JSC.ZigException.Holder = bun.JSC.ZigException.Holder.init(); if (err.toError()) |value| { value.toZigException(globalObject, zig_exception_holder.zigException()); } else { - zig_exception_holder.zig_exception.message = err.toBunString(globalObject); + zig_exception_holder.zig_exception.message = try err.toBunString(globalObject); } return Msg{ diff --git a/src/napi/napi.zig b/src/napi/napi.zig index d329b68c89557f..2b093c5c3ff944 100644 --- a/src/napi/napi.zig +++ b/src/napi/napi.zig @@ -442,7 +442,7 @@ pub export fn napi_get_value_string_latin1(env: napi_env, value_: napi_value, bu defer value.ensureStillAlive(); const buf_ptr = @as(?[*:0]u8, @ptrCast(buf_ptr_)); - const str = value.toBunString(env); + const str = value.toBunString(env) catch return .pending_exception; defer str.deref(); var buf = buf_ptr orelse { @@ -498,7 +498,7 @@ pub export fn napi_get_value_string_utf16(env: napi_env, value_: napi_value, buf log("napi_get_value_string_utf16", .{}); const value = value_.get(); defer value.ensureStillAlive(); - const str = value.toBunString(env); + const str = value.toBunString(env) catch return .pending_exception; defer str.deref(); var buf = buf_ptr orelse { @@ -1606,12 +1606,10 @@ pub const ThreadSafeFunction = struct { return; } - _ = js.call(globalObject, .undefined, &.{}) catch |err| - globalObject.reportActiveExceptionAsUnhandled(err); + _ = js.call(globalObject, .undefined, &.{}) catch |err| globalObject.reportActiveExceptionAsUnhandled(err); }, .c => |cb| { const js = cb.js.get() orelse .undefined; - const handle_scope = NapiHandleScope.open(globalObject, false); defer if (handle_scope) |scope| scope.close(globalObject); cb.napi_threadsafe_function_call_js(globalObject, napi_value.create(globalObject, js), this.ctx, task); diff --git a/src/patch.zig b/src/patch.zig index 2ba0819628068b..b3935df948a05c 100644 --- a/src/patch.zig +++ b/src/patch.zig @@ -1098,18 +1098,12 @@ pub const TestingAPIs = struct { const arguments_ = callframe.arguments_old(2); var arguments = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments_.slice()); - const old_folder_jsval = arguments.nextEat() orelse { - globalThis.throw("expected 2 strings", .{}); - return .zero; - }; - const old_folder_bunstr = old_folder_jsval.toBunString(globalThis); + const old_folder_jsval = arguments.nextEat() orelse return globalThis.throw2("expected 2 strings", .{}); + const old_folder_bunstr = try old_folder_jsval.toBunString(globalThis); defer old_folder_bunstr.deref(); - const new_folder_jsval = arguments.nextEat() orelse { - globalThis.throw("expected 2 strings", .{}); - return .zero; - }; - const new_folder_bunstr = new_folder_jsval.toBunString(globalThis); + const new_folder_jsval = arguments.nextEat() orelse return globalThis.throw2("expected 2 strings", .{}); + const new_folder_bunstr = try new_folder_jsval.toBunString(globalThis); defer new_folder_bunstr.deref(); const old_folder = old_folder_bunstr.toUTF8(bun.default_allocator); @@ -1168,7 +1162,7 @@ pub const TestingAPIs = struct { globalThis.throw("TestingAPIs.parse: expected at least 1 argument, got 0", .{}); return .zero; }; - const patchfile_src_bunstr = patchfile_src_js.toBunString(globalThis); + const patchfile_src_bunstr = try patchfile_src_js.toBunString(globalThis); const patchfile_src = patchfile_src_bunstr.toUTF8(bun.default_allocator); var patchfile = parsePatchFile(patchfile_src.slice()) catch |e| { @@ -1198,7 +1192,7 @@ pub const TestingAPIs = struct { }; const dir_fd = if (arguments.nextEat()) |dir_js| brk: { - var bunstr = dir_js.toBunString(globalThis); + var bunstr = dir_js.toBunString(globalThis) catch return .{ .err = .undefined }; defer bunstr.deref(); const path = bunstr.toOwnedSliceZ(bun.default_allocator) catch unreachable; defer bun.default_allocator.free(path); @@ -1212,7 +1206,7 @@ pub const TestingAPIs = struct { }; } else bun.FileDescriptor.cwd(); - const patchfile_bunstr = patchfile_js.toBunString(globalThis); + const patchfile_bunstr = patchfile_js.toBunString(globalThis) catch return .{ .err = .undefined }; defer patchfile_bunstr.deref(); const patchfile_src = patchfile_bunstr.toUTF8(bun.default_allocator); diff --git a/src/resolver/resolver.zig b/src/resolver/resolver.zig index 4196d18a16f95a..524a094dd3016c 100644 --- a/src/resolver/resolver.zig +++ b/src/resolver/resolver.zig @@ -3306,7 +3306,7 @@ pub const Resolver = struct { return .zero; } - const in_str = argument.toBunString(globalThis); + const in_str = try argument.toBunString(globalThis); defer in_str.deref(); const r = &globalThis.bunVM().bundler.resolver; return nodeModulePathsJSValue(r, in_str, globalThis); diff --git a/src/shell/interpreter.zig b/src/shell/interpreter.zig index a54941f0288c4b..09b39b38963128 100644 --- a/src/shell/interpreter.zig +++ b/src/shell/interpreter.zig @@ -710,7 +710,7 @@ pub const ParsedShellScript = struct { globalThis.throw("$`...`.cwd(): expected a string argument", .{}); return .zero; }; - const str = bun.String.fromJS(str_js, globalThis); + const str = try bun.String.fromJS(str_js, globalThis); this.cwd = str; return .undefined; } diff --git a/src/shell/shell.zig b/src/shell/shell.zig index 748fdbe32c146f..4d720660f52d55 100644 --- a/src/shell/shell.zig +++ b/src/shell/shell.zig @@ -3861,7 +3861,7 @@ pub fn handleTemplateValue( if (template_value.isObject()) { if (template_value.getOwnTruthy(globalThis, "raw")) |maybe_str| { - const bunstr = maybe_str.toBunString(globalThis); + const bunstr = try maybe_str.toBunString(globalThis); defer bunstr.deref(); if (!try builder.appendBunStr(bunstr, false)) { globalThis.throw("Shell script string contains invalid UTF-16", .{}); @@ -3913,17 +3913,13 @@ pub const ShellSrcBuilder = struct { } pub fn appendJSValueStr(this: *ShellSrcBuilder, jsval: JSValue, comptime allow_escape: bool) !bool { - const bunstr = jsval.toBunString(this.globalThis); + const bunstr = try jsval.toBunString(this.globalThis); defer bunstr.deref(); return try this.appendBunStr(bunstr, allow_escape); } - pub fn appendBunStr( - this: *ShellSrcBuilder, - bunstr: bun.String, - comptime allow_escape: bool, - ) !bool { + pub fn appendBunStr(this: *ShellSrcBuilder, bunstr: bun.String, comptime allow_escape: bool) !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) { @@ -4323,7 +4319,7 @@ pub const TestingAPIs = struct { return .zero; }; - const bunstr = string.toBunString(globalThis); + const bunstr = try string.toBunString(globalThis); defer bunstr.deref(); const utf8str = bunstr.toUTF8(bun.default_allocator); defer utf8str.deinit(); diff --git a/src/sql/postgres.zig b/src/sql/postgres.zig index 09b2cdf61f7b57..f518f443bfa99d 100644 --- a/src/sql/postgres.zig +++ b/src/sql/postgres.zig @@ -430,19 +430,17 @@ pub const PostgresSQLQuery = struct { const columns = arguments[3]; if (!query.isString()) { - globalThis.throw("query must be a string", .{}); - return .zero; + return globalThis.throw2("query must be a string", .{}); } if (values.jsType() != .Array) { - globalThis.throw("values must be an array", .{}); - return .zero; + return globalThis.throw2("values must be an array", .{}); } const pending_value = arguments[2]; if (!pending_value.jsType().isArrayLike()) { globalThis.throwInvalidArgumentType("query", "pendingValue", "Array"); - return .zero; + return error.JSError; } var ptr = try bun.default_allocator.create(PostgresSQLQuery); @@ -451,7 +449,7 @@ pub const PostgresSQLQuery = struct { this_value.ensureStillAlive(); ptr.* = .{ - .query = query.toBunString(globalThis), + .query = try query.toBunString(globalThis), .thisValue = this_value, }; ptr.query.ref(); @@ -696,7 +694,7 @@ pub const PostgresRequest = struct { }, .timestamp, .timestamptz => { const l = try writer.length(); - try writer.int8(types.date.fromJS(globalObject, value)); + try writer.int8(try types.date.fromJS(globalObject, value)); try l.writeExcludingSelf(); }, .bytea => { @@ -1369,15 +1367,15 @@ pub const PostgresSQLConnection = struct { pub fn call(globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { var vm = globalObject.bunVM(); const arguments = callframe.arguments_old(10).slice(); - const hostname_str = arguments[0].toBunString(globalObject); + const hostname_str = try arguments[0].toBunString(globalObject); defer hostname_str.deref(); const port = arguments[1].coerce(i32, globalObject); - const username_str = arguments[2].toBunString(globalObject); + const username_str = try arguments[2].toBunString(globalObject); defer username_str.deref(); - const password_str = arguments[3].toBunString(globalObject); + const password_str = try arguments[3].toBunString(globalObject); defer password_str.deref(); - const database_str = arguments[4].toBunString(globalObject); + const database_str = try arguments[4].toBunString(globalObject); defer database_str.deref(); const ssl_mode: SSLMode = switch (arguments[5].toInt32()) { 0 => .disable, @@ -1438,7 +1436,7 @@ pub const PostgresSQLConnection = struct { var database: []const u8 = ""; var options: []const u8 = ""; - const options_str = arguments[7].toBunString(globalObject); + const options_str = try arguments[7].toBunString(globalObject); defer options_str.deref(); const options_buf: []u8 = brk: { diff --git a/src/sql/postgres/postgres_types.zig b/src/sql/postgres/postgres_types.zig index 6a595cafb781e8..9ac0b708ef6525 100644 --- a/src/sql/postgres/postgres_types.zig +++ b/src/sql/postgres/postgres_types.zig @@ -508,13 +508,13 @@ pub const date = struct { return (double_microseconds / std.time.us_per_ms) + POSTGRES_EPOCH_DATE; } - pub fn fromJS(globalObject: *JSC.JSGlobalObject, value: JSValue) i64 { + pub fn fromJS(globalObject: *JSC.JSGlobalObject, value: JSValue) bun.JSError!i64 { const double_value = if (value.isDate()) value.getUnixTimestamp() else if (value.isNumber()) value.asNumber() else if (value.isString()) brk: { - var str = value.toBunString(globalObject); + var str = try value.toBunString(globalObject); defer str.deref(); break :brk str.parseDate(globalObject); } else return 0; diff --git a/src/string.zig b/src/string.zig index 3b2dab9fcb3c15..0fc5d74f12c100 100644 --- a/src/string.zig +++ b/src/string.zig @@ -691,8 +691,8 @@ pub const String = extern struct { try self.toZigString().format(fmt, opts, writer); } - /// Deprecated: use `fromJS2` to handle errors explicitly - pub fn fromJS(value: bun.JSC.JSValue, globalObject: *JSC.JSGlobalObject) String { + /// Deprecated: use `fromJS` to handle errors explicitly + pub fn fromJS_unsafe(value: bun.JSC.JSValue, globalObject: *JSC.JSGlobalObject) String { JSC.markBinding(@src()); var out: String = String.dead; @@ -703,7 +703,7 @@ pub const String = extern struct { } } - pub fn fromJS2(value: bun.JSC.JSValue, globalObject: *JSC.JSGlobalObject) bun.JSError!String { + pub fn fromJS(value: bun.JSC.JSValue, globalObject: *JSC.JSGlobalObject) bun.JSError!String { var out: String = String.dead; if (BunString__fromJS(globalObject, value, &out)) { if (comptime bun.Environment.isDebug) { @@ -1340,7 +1340,7 @@ pub const String = extern struct { return JSC.jsNumber(@as(i32, 0)); } - const str = args[0].toBunString(globalObject); + const str = try args[0].toBunString(globalObject); defer str.deref(); if (str.isEmpty()) {