diff --git a/src/jsc/ConsoleObject.rs b/src/jsc/ConsoleObject.rs index e9f3b7261673..fdd94db0aa5e 100644 --- a/src/jsc/ConsoleObject.rs +++ b/src/jsc/ConsoleObject.rs @@ -4314,29 +4314,18 @@ pub mod formatter { failed: false, estimated_line_length: &mut self.estimated_line_length, }; - let mut str = OwnedString::new(BunString::empty()); - value.json_stringify(self.global_this, self.indent, &mut str)?; - writer.add_for_new_line(str.length()); if js_type == jsc::JSType::JSDate { - // in the code for printing dates, it never exceeds this amount - let mut iso_string_buf = [0u8; 36]; - let mut out_buf: &[u8] = { - use std::io::Write as _; - let mut cursor = &mut iso_string_buf[..]; - let start_len = cursor.len(); - let _ = write!(cursor, "{str}"); - let written = start_len - cursor.len(); - &iso_string_buf[..written] - }; - - if out_buf == b"null" { - out_buf = b"Invalid Date"; - } else if out_buf.len() > 2 { - // trim the quotes - out_buf = &out_buf[1..out_buf.len() - 1]; - } - + // Format from the Date's internal [[DateValue]] so that own/overridden + // `toJSON`/`toISOString` properties are never invoked (they could throw + // out of console.log or spoof the output). `to_iso_string` reads + // `DateInstance::internalNumber()` directly; `None` means NaN. + let mut iso_string_buf = [0u8; 64]; + let out_buf: &[u8] = value + .to_iso_string(self.global_this, &mut iso_string_buf) + .unwrap_or(b"Invalid Date"); + + writer.add_for_new_line(out_buf.len()); writer.print(format_args!( "{}{}{}", pfmt!("", C), @@ -4349,6 +4338,11 @@ pub mod formatter { return Ok(()); } + let mut str = OwnedString::new(BunString::empty()); + + value.json_stringify(self.global_this, self.indent, &mut str)?; + writer.add_for_new_line(str.length()); + writer.print(format_args!("{str}")); if writer.failed { self.failed = true; diff --git a/src/runtime/test_runner/pretty_format.rs b/src/runtime/test_runner/pretty_format.rs index b4a68cca5c07..c2c38017d5c8 100644 --- a/src/runtime/test_runner/pretty_format.rs +++ b/src/runtime/test_runner/pretty_format.rs @@ -1862,29 +1862,16 @@ impl<'a> Formatter<'a> { writer.write_all(b"\n"); } Tag::JSON => { - let mut str = bun_core::String::empty(); - - value.json_stringify(self.global_this, self.indent, &mut str)?; - self.add_for_new_line(str.length()); if js_type == JSType::JSDate { - // in the code for printing dates, it never exceeds this amount - let mut iso_string_buf = [0u8; 36]; - let mut out_buf: &[u8] = { - use std::io::Write; - let mut cursor = &mut iso_string_buf[..]; - match write!(cursor, "{}", str) { - Ok(()) => { - let written = 36 - cursor.len(); - &iso_string_buf[..written] - } - Err(_) => b"", - } - }; - if out_buf.len() > 2 { - // trim the quotes - out_buf = &out_buf[1..out_buf.len() - 1]; - } - + // Format from the Date's internal [[DateValue]] so that own/overridden + // `toJSON`/`toISOString` properties are never invoked. `to_iso_string` + // reads `DateInstance::internalNumber()` directly; `None` means NaN. + let mut iso_string_buf = [0u8; 64]; + let out_buf: &[u8] = value + .to_iso_string(self.global_this, &mut iso_string_buf) + .unwrap_or(b"Invalid Date"); + + self.add_for_new_line(out_buf.len()); writer.print(format_args!( "{}{}{}", pretty_fmt_const::(""), @@ -1894,6 +1881,11 @@ impl<'a> Formatter<'a> { return Ok(()); } + let mut str = bun_core::String::empty(); + + value.json_stringify(self.global_this, self.indent, &mut str)?; + self.add_for_new_line(str.length()); + writer.print(format_args!("{}", str)); } Tag::Event => { diff --git a/test/js/bun/util/inspect.test.js b/test/js/bun/util/inspect.test.js index e76766e7f42f..a4114f1acf3e 100644 --- a/test/js/bun/util/inspect.test.js +++ b/test/js/bun/util/inspect.test.js @@ -490,6 +490,77 @@ it("new Date(..)", () => { expect(Bun.inspect(new Date("Invalid Date"))).toBe("Invalid Date"); }); +it("Date ignores own toJSON/toISOString when formatting", () => { + // The formatter must read the Date's internal [[DateValue]] and never call + // user-provided toJSON/toISOString (which could throw or spoof the output). + const iso = "1970-01-01T00:00:00.000Z"; + + const a = new Date(0); + a.toISOString = () => { + throw new Error("iso-boom"); + }; + expect(() => Bun.inspect(a)).not.toThrow(); + expect(Bun.inspect(a)).toBe(iso); + + const b = new Date(0); + b.toISOString = 5; + expect(() => Bun.inspect(b)).not.toThrow(); + expect(Bun.inspect(b)).toBe(iso); + + const c = new Date(0); + c.toJSON = () => "SPOOFED"; + expect(Bun.inspect(c)).toBe(iso); + + const d = new Date(0); + d.toJSON = () => ({ nested: { fake: 1 } }); + expect(Bun.inspect(d)).toBe(iso); + + const e = new Date(0); + e.toJSON = () => { + throw new Error("mid"); + }; + expect(() => Bun.inspect(["before", e, "after"])).not.toThrow(); + expect(Bun.inspect(["before", e, "after"])).toBe(`[ "before", ${iso}, "after" ]`); + + const f = new Date(NaN); + f.toJSON = () => "SPOOFED-INVALID"; + expect(Bun.inspect(f)).toBe("Invalid Date"); + + class SubDate extends Date { + toJSON() { + throw new Error("sub-boom"); + } + } + expect(Bun.inspect(new SubDate(0))).toBe(iso); +}); + +it("console.log of Date with throwing toJSON does not throw", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + ` + const a = new Date(0); + a.toISOString = () => { throw new Error("iso-boom"); }; + console.log(a); + const e = new Date(0); + e.toJSON = () => { throw new Error("mid"); }; + console.log(["before", e, "after"]); + console.log("DONE"); + `, + ], + env: bunEnv, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ stdout: stdout.replaceAll("\r\n", "\n"), stderr, exitCode }).toEqual({ + stdout: `1970-01-01T00:00:00.000Z\n[ "before", 1970-01-01T00:00:00.000Z, "after" ]\nDONE\n`, + stderr: "", + exitCode: 0, + }); +}); + it("Bun.inspect.custom exists", () => { expect(Bun.inspect.custom).toBe(util.inspect.custom); });