Lightpanda: the headless browser designed for AI and automation
add js.ErrorLocation wrapper
Karl Seguinda1321eeebaf
diff --git a/src/Notification.zig b/src/Notification.zigindex 1cb187061..2734b9a0e 100644--- a/src/Notification.zig+++ b/src/Notification.zig@@ -378,6 +378,7 @@ pub const ConsoleMessage = struct {pub const ExceptionThrown = struct {timestamp: u64,value: js.Value,+ location: js.Value.ErrorLocation,};pub fn init(allocator: Allocator) !*Notification {diff --git a/src/browser/js/Value.zig b/src/browser/js/Value.zigindex edfca281c..fa231f631 100644--- a/src/browser/js/Value.zig+++ b/src/browser/js/Value.zig@@ -60,6 +60,35 @@ pub fn isNativeError(self: Value) bool {return v8.v8__Value__IsNativeError(self.handle);}+pub const ErrorLocation = struct {+ url: []const u8 = "",+ line: u32 = 0,+ column: u32 = 0,+};++pub fn errorLocation(self: Value, allocator: Allocator) !ErrorLocation {+ const l = self.local;+ const message = v8.v8__Exception__CreateMessage(l.isolate.handle, self.handle) orelse return .{};++ var location: ErrorLocation = .{};+ const line = v8.v8__Message__GetLineNumber(message, l.handle);+ if (line > 0) {+ location.line = @intCast(line);+ }+ // V8's column is 0-based.+ const column = v8.v8__Message__GetStartColumn(message);+ if (column >= 0) {+ location.column = @intCast(column + 1);+ }+ if (v8.v8__Message__GetScriptResourceName(message)) |handle| {+ const name: Value = .{ .local = l, .handle = handle };+ if (name.isString()) |str| {+ location.url = try str.toSliceWithAlloc(allocator);+ }+ }+ return location;+}+pub fn isNull(self: Value) bool {return v8.v8__Value__IsNull(self.handle);}diff --git a/src/browser/tests/window/report_error.html b/src/browser/tests/window/report_error.htmlindex eb4b1124d..ef8b4b5e4 100644--- a/src/browser/tests/window/report_error.html+++ b/src/browser/tests/window/report_error.html@@ -89,9 +89,10 @@window.reportError('Plain string error');testing.expectEqual('Plain string error', evt.message);- testing.expectEqual('', evt.filename);- testing.expectEqual(0, evt.lineno);- testing.expectEqual(0, evt.colno);+ // A non-Error value is located at the reportError call, as in Chrome.+ testing.expectEqual(true, evt.filename.endsWith('report_error.html'));+ testing.expectEqual(true, evt.lineno > 0);+ testing.expectEqual(true, evt.colno > 0);}</script>@@ -112,6 +113,28 @@}</script>+<script id=reportErrorErrorLocation>+{+ const events = [];+ const listener = (e) => {+ e.preventDefault();+ events.push(e);+ };+ window.addEventListener('error', listener);++ // An Error is located where it was created, not where it was reported.+ const first = new Error('first');+ const second = new Error('second');+ window.reportError(second);+ window.reportError(first);+ window.removeEventListener('error', listener);++ testing.expectEqual(true, events[0].filename.endsWith('report_error.html'));+ testing.expectEqual(events[1].lineno + 1, events[0].lineno);+ testing.expectEqual(18, events[0].colno);+}+</script>+<script id=reportErrorEventTarget>{let evt = null;@@ -145,9 +168,10 @@testing.expectEqual(true, eventFired);testing.expectEqual('error', evt.type);- testing.expectEqual('', evt.filename);- testing.expectEqual(0, evt.lineno);- testing.expectEqual(0, evt.colno);+ // A non-Error value is located at the reportError call, as in Chrome.+ testing.expectEqual(true, evt.filename.endsWith('report_error.html'));+ testing.expectEqual(true, evt.lineno > 0);+ testing.expectEqual(true, evt.colno > 0);}</script>@@ -166,9 +190,10 @@testing.expectEqual(true, eventFired);testing.expectEqual('error', evt.type);- testing.expectEqual('', evt.filename);- testing.expectEqual(0, evt.lineno);- testing.expectEqual(0, evt.colno);+ // A non-Error value is located at the reportError call, as in Chrome.+ testing.expectEqual(true, evt.filename.endsWith('report_error.html'));+ testing.expectEqual(true, evt.lineno > 0);+ testing.expectEqual(true, evt.colno > 0);}</script>diff --git a/src/browser/webapi/Window.zig b/src/browser/webapi/Window.zigindex 622bc8bb0..d34a13109 100644--- a/src/browser/webapi/Window.zig+++ b/src/browser/webapi/Window.zig@@ -601,6 +601,8 @@ pub fn reportError(self: *Window, err: js.Value, frame: *Frame) !void {frame.page.recordJsError(error.JsException);+ const location = err.errorLocation(frame.call_arena) catch js.Value.ErrorLocation{};+const target = self.asEventTarget();if (!frame._event_manager.hasDirectListeners(target, "error", self._on_error)) {if (comptime lp.IS_TEST == false) {@@ -608,7 +610,7 @@ pub fn reportError(self: *Window, err: js.Value, frame: *Frame) !void {.message = err.toStringSlice() catch "Unknown error",});}- notifyExceptionThrown(err, frame);+ notifyExceptionThrown(err, location, frame);return;}@@ -618,6 +620,9 @@ pub fn reportError(self: *Window, err: js.Value, frame: *Frame) !void {const error_event = try ErrorEvent.initTrusted(comptime .wrap("error"), .{.@"error" = try err.persist(),.message = err.toStringSlice() catch "Unknown error",+ .filename = location.url,+ .lineno = location.line,+ .colno = location.column,.bubbles = false,.cancelable = true,}, frame.page);@@ -669,16 +674,17 @@ pub fn reportError(self: *Window, err: js.Value, frame: *Frame) !void {}}if (!event._prevent_default) {- notifyExceptionThrown(err, frame);+ notifyExceptionThrown(err, location, frame);}}// An error event left uncancelled leaves the exception "uncaught": CDP// clients learn about it through Runtime.exceptionThrown.-fn notifyExceptionThrown(err: js.Value, frame: *Frame) void {+fn notifyExceptionThrown(err: js.Value, location: js.Value.ErrorLocation, frame: *Frame) void {frame._session.notification.dispatch(.exception_thrown, &.{.timestamp = lp.datetime.timestamp(.boot),.value = err,+ .location = location,});}diff --git a/src/server/cdp/CDP.zig b/src/server/cdp/CDP.zigindex 9e16a362e..d4c622d3e 100644--- a/src/server/cdp/CDP.zig+++ b/src/server/cdp/CDP.zig@@ -518,6 +518,9 @@ pub const BrowserContext = struct {// can use the existing Frame/js.Context as-is.main_world_touched: bool = false,+ // Runtime.exceptionThrown's exceptionDetails.exceptionId.+ next_exception_id: u32 = 1,+// Scripts registered via Page.addScriptToEvaluateOnNewDocument.// Evaluated in each new document after navigation completes.scripts_on_new_document: std.ArrayList(ScriptOnNewDocument) = .empty,diff --git a/src/server/cdp/domains/runtime.zig b/src/server/cdp/domains/runtime.zigindex 101f23790..eb2421ebf 100644--- a/src/server/cdp/domains/runtime.zig+++ b/src/server/cdp/domains/runtime.zig@@ -20,7 +20,6 @@ const std = @import("std");const CDP = @import("../CDP.zig");const js = @import("../../../browser/js/js.zig");-const v8 = js.v8;const Notification = @import("../../../Notification.zig");const repeat = @import("../../../string.zig").repeat;@@ -179,8 +178,6 @@ const ExceptionDetails = struct {executionContextId: i32,};-var next_exception_id: std.atomic.Value(u32) = .init(1);-pub fn exceptionThrown(arena: Allocator, bc: *CDP.BrowserContext, event: *const Notification.ExceptionThrown) !void {// Like consoleAPICalled: the primary session's inspector mints the handle.const session_id = bc.session_id orelse return;@@ -204,35 +201,19 @@ pub fn exceptionThrown(arena: Allocator, bc: *CDP.BrowserContext, event: *const};try exception.setPrimitive(arena, value);- // Where the exception was thrown. V8's line is 1-based, CDP's 0-based.- var line: u32 = 0;- var column: u32 = 0;- var url: ?[]const u8 = null;- if (v8.v8__Exception__CreateMessage(ls.local.isolate.handle, value.handle)) |message| {- const l = v8.v8__Message__GetLineNumber(message, ls.local.handle);- if (l > 0) {- line = @intCast(l - 1);- }- const c = v8.v8__Message__GetStartColumn(message);- if (c > 0) {- column = @intCast(c);- }- if (v8.v8__Message__GetScriptResourceName(message)) |name| {- const name_value = js.Value{ .local = &ls.local, .handle = name };- if (name_value.isString()) |str| {- url = try str.toSliceWithAlloc(arena);- }- }- }+ // The location is 1-based, CDP's is 0-based.+ const location = event.location;+ const exception_id = bc.next_exception_id;+ bc.next_exception_id += 1;return bc.cdp.sendEvent("Runtime.exceptionThrown", .{.timestamp = event.timestamp,.exceptionDetails = ExceptionDetails{- .exceptionId = next_exception_id.fetchAdd(1, .monotonic),+ .exceptionId = exception_id,.text = "Uncaught",- .lineNumber = line,- .columnNumber = column,- .url = url,+ .lineNumber = location.line -| 1,+ .columnNumber = location.column -| 1,+ .url = if (location.url.len == 0) null else location.url,.exception = exception,.executionContextId = bc.inspector().getContextId(&ls.local),},@@ -354,6 +335,30 @@ test "cdp.runtime: an uncaught exception emits Runtime.exceptionThrown" {}, .{});}+test "cdp.runtime: Runtime.exceptionThrown locates an Error where it was created" {+ testing.silenceLog(&.{.js});++ var ctx = try testing.context();+ defer ctx.deinit();++ var bc = try ctx.loadBrowserContext(.{ .id = "BID-EXC3", .url = "hi.html", .target_id = "FID-000000EXC3".* });+ try ctx.processMessage(.{ .id = 62, .method = "Runtime.enable" });++ const frame = bc.mainFrame() orelse unreachable;+ var ls: js.Local.Scope = undefined;+ frame.js.localScope(&ls);+ defer ls.deinit();+ _ = try ls.local.exec(+ \\const unused = 1;+ \\const err = new Error('here');+ \\reportError(err);+ , "exc.js");++ try ctx.expectSentEvent("Runtime.exceptionThrown", .{+ .exceptionDetails = .{ .lineNumber = 1, .columnNumber = 12, .url = "exc.js" },+ }, .{});+}+test "cdp.runtime: an exception whose error event is cancelled is not reported" {testing.silenceLog(&.{.js});