Lightpanda: the headless browser designed for AI and automation
feat(performance): add PerformanceNavigationTiming entry for the document
Gourav Kumar Dhiman0014511d12c9
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex 4810a9add..c4d4b579e 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -976,6 +976,11 @@ pub fn navigate(self: *Frame, request_url: [:0]const u8, opts: NavigateOpts) !voself.recordNavigateTelemetry(std.ascii.startsWithIgnoreCase(self.url, "https://"));session.navigationFor(self)._current_navigation_kind = opts.kind;+ self.window._performance._navigation_type = switch (opts.kind) {+ .reload => .reload,+ .traverse => .back_forward,+ .push, .replace => .navigate,+ };transfer.submit() catch |err| {log.debug(.frame, "navigate request", .{ .url = self.url, .err = err, .type = self._type });@@ -1422,6 +1427,7 @@ pub fn abortedDocumentIsComplete(self: *Frame) void {return;}self.document._ready_state = .complete;+ self.window._performance.markNavigation(.dom_complete);self.dispatchReadyStateChange() catch |err| switch (err) {error.JsException => {}, // already loggedelse => log.err(.frame, "aborted document is complete", .{ .err = err, .type = self._type, .url = self.url }),@@ -1476,6 +1482,7 @@ pub fn documentIsLoaded(self: *Frame) void {self._load_state = .load;self.document._ready_state = .interactive;+ self.window._performance.markNavigation(.dom_interactive);self._documentIsLoaded() catch |err| switch (err) {error.JsException => {}, // already logged// logged by whatever requested the terminate (watchdog, runaway loop)@@ -1488,11 +1495,14 @@ fn _documentIsLoaded(self: *Frame) !void {try self.dispatchReadyStateChange();if (self.loadEventsAborted()) return;+ const perf = self.window._performance;+ perf.markNavigation(.dom_content_loaded_event_start);const event = try Event.initTrusted(.wrap("DOMContentLoaded"), .{ .bubbles = true }, self.page);try self._event_manager.dispatch(self.document.asEventTarget(),event,);+ perf.markNavigation(.dom_content_loaded_event_end);self._session.notification.dispatch(.frame_dom_content_loaded, &.{.req_id = self._req_id,@@ -1607,9 +1617,11 @@ pub fn documentIsComplete(self: *Frame) void {}fn _documentIsComplete(self: *Frame) !void {+ const perf = self.window._performance;// abortedDocumentIsComplete may already have done this half.if (self.document._ready_state != .complete) {self.document._ready_state = .complete;+ perf.markNavigation(.dom_complete);try self.dispatchReadyStateChange();}if (self.loadEventsAborted()) return;@@ -1624,6 +1636,7 @@ fn _documentIsComplete(self: *Frame) !void {// Dispatch window.load event.const window_target = self.window.asEventTarget();+ perf.markNavigation(.load_event_start);if (self._event_manager.hasDirectListeners(window_target, "load")) {const event = try Event.initTrusted(comptime .wrap("load"), .{}, self.page);// This event is weird, it's dispatched directly on the window, but@@ -1633,6 +1646,7 @@ fn _documentIsComplete(self: *Frame) !void {defer self._load_event_in_progress = false;try self._event_manager.dispatchDirect(window_target, event, .{ .inject_target = false, .context = "page load" });}+ perf.markNavigation(.load_event_end);if (self.window._closed) {// discarded by its own load handler: no longer active, and discard()diff --git a/src/browser/tests/performance_navigation_timing.html b/src/browser/tests/performance_navigation_timing.htmlnew file mode 100644index 000000000..741f25fc1--- /dev/null+++ b/src/browser/tests/performance_navigation_timing.html@@ -0,0 +1,136 @@+<!DOCTYPE html>+<script src="testing.js"></script>++<script id=while_parsing>+ {+ const list = performance.getEntriesByType('navigation');+ testing.expectEqual(1, list.length);+ const e = list[0];+ testing.expectEqual(true, e instanceof PerformanceNavigationTiming);+ testing.expectEqual(true, e instanceof PerformanceResourceTiming);+ testing.expectEqual(true, e instanceof PerformanceEntry);+ testing.expectEqual(location.href, e.name);+ testing.expectEqual('navigation', e.entryType);+ testing.expectEqual('navigation', e.initiatorType);+ testing.expectEqual('navigate', e.type);+ testing.expectEqual(0, e.redirectCount);+ testing.expectEqual(0, e.startTime);+ testing.expectEqual(200, e.responseStatus);+ testing.expectEqual('text/html', e.contentType);+ testing.expectEqual('http/1.1', e.nextHopProtocol);+ testing.expectEqual(0, e.redirectStart);+ testing.expectEqual(0, e.redirectEnd);+ testing.expectEqual(0, e.unloadEventStart);+ testing.expectEqual(0, e.unloadEventEnd);+ testing.expectEqual(true, e.fetchStart >= 0);+ testing.expectEqual(true, e.fetchStart <= e.domainLookupStart);+ testing.expectEqual(true, e.domainLookupEnd <= e.connectStart);+ testing.expectEqual(true, e.connectEnd <= e.requestStart);+ testing.expectEqual(true, e.requestStart <= e.responseStart);+ testing.expectEqual(true, e.responseStart <= e.responseEnd);+ testing.expectEqual(true, e.responseEnd <= performance.now());+ testing.expectEqual(true, e.decodedBodySize > 0);++ // The document is still parsing and hasn't loaded.+ testing.expectEqual(0, e.domInteractive);+ testing.expectEqual(0, e.domContentLoadedEventStart);+ testing.expectEqual(0, e.domComplete);+ testing.expectEqual(0, e.loadEventEnd);+ testing.expectEqual(0, e.duration);++ testing.expectEqual(e, performance.getEntries()[0]);+ testing.expectEqual(e, performance.getEntriesByName(location.href)[0]);+ testing.expectEqual(1, performance.getEntriesByName(location.href, 'navigation').length);+ testing.expectEqual(0, performance.getEntriesByName(location.href, 'resource').length);+ // Not a resource of its own document.+ testing.expectEqual(true, performance.getEntriesByType('resource').every((r) => r.name !== location.href));+ }+</script>++<script id=dom_content_loaded>+ {+ let during = null;+ document.addEventListener('DOMContentLoaded', () => {+ const e = performance.getEntriesByType('navigation')[0];+ during = {+ domInteractive: e.domInteractive,+ start: e.domContentLoadedEventStart,+ end: e.domContentLoadedEventEnd,+ };+ });+ testing.onload(() => {+ testing.expectEqual(true, during.domInteractive > 0);+ testing.expectEqual(true, during.start >= during.domInteractive);+ // Still inside the handler.+ testing.expectEqual(0, during.end);+ });+ }+</script>++<script id=after_load>+ testing.async().then((state) => {+ let during = null;+ window.addEventListener('load', () => {+ during = performance.getEntriesByType('navigation')[0].loadEventEnd;+ setTimeout(() => state.resolve(), 0);+ });+ state.done(() => {+ const e = performance.getEntriesByType('navigation')[0];+ testing.expectEqual(0, during);+ testing.expectEqual(true, e.domContentLoadedEventStart <= e.domContentLoadedEventEnd);+ testing.expectEqual(true, e.domContentLoadedEventEnd <= e.domComplete);+ testing.expectEqual(true, e.domComplete <= e.loadEventStart);+ testing.expectEqual(true, e.loadEventStart <= e.loadEventEnd);+ testing.expectEqual(true, e.responseEnd <= e.domInteractive);+ testing.expectEqual(e.loadEventEnd, e.duration);++ const json = e.toJSON();+ testing.expectEqual(location.href, json.name);+ testing.expectEqual('navigation', json.entryType);+ testing.expectEqual('navigate', json.type);+ testing.expectEqual(0, json.redirectCount);+ testing.expectEqual(e.domComplete, json.domComplete);+ testing.expectEqual(e.loadEventEnd, json.loadEventEnd);+ testing.expectEqual(e.responseEnd, json.responseEnd);+ testing.expectEqual(true, JSON.stringify(e).includes('"entryType":"navigation"'));+ });+ });+</script>++<script id=observer_buffered>+ testing.async().then((state) => {+ new PerformanceObserver((list, observer) => {+ observer.disconnect();+ state.resolve(list.getEntries());+ }).observe({ type: 'navigation', buffered: true });+ state.done((entries) => {+ testing.expectEqual(1, entries.length);+ testing.expectEqual(performance.getEntriesByType('navigation')[0], entries[0]);+ });+ });+</script>++<iframe id=redirected src="/redirect-no-fragment"></iframe>+<script id=iframe_redirect>+ testing.async().then((state) => {+ const iframe = document.getElementById('redirected');+ iframe.addEventListener('load', () => state.resolve());+ state.done(() => {+ const list = iframe.contentWindow.performance.getEntriesByType('navigation');+ testing.expectEqual(1, list.length);+ const e = list[0];+ testing.expectEqual(testing.ORIGIN + '/redirect-target', e.name);+ testing.expectEqual(iframe.contentWindow.location.href, e.name);+ testing.expectEqual(1, e.redirectCount);+ testing.expectEqual(true, e.redirectEnd > 0);+ testing.expectEqual(true, e.redirectStart <= e.redirectEnd);+ testing.expectEqual(true, e.redirectEnd <= e.fetchStart);+ testing.expectEqual(true, e.loadEventEnd > 0);++ // The parent sees the same fetch as an iframe resource.+ const r = performance.getEntriesByName(testing.ORIGIN + '/redirect-no-fragment', 'resource');+ testing.expectEqual(1, r.length);+ testing.expectEqual('iframe', r[0].initiatorType);+ });+ });+</script>diff --git a/src/browser/tests/performance_observer/performance_observer.html b/src/browser/tests/performance_observer/performance_observer.htmlindex a1a63f543..2a9e6e0b5 100644--- a/src/browser/tests/performance_observer/performance_observer.html+++ b/src/browser/tests/performance_observer/performance_observer.html@@ -83,7 +83,7 @@<script id="supported_entry_types">// The types we implement (Chrome lists many more).- testing.expectEqual(['mark', 'measure', 'resource'], PerformanceObserver.supportedEntryTypes);+ testing.expectEqual(['mark', 'measure', 'navigation', 'resource'], PerformanceObserver.supportedEntryTypes);</script><script id="list_get_entries_by_type" type=module>diff --git a/src/browser/tests/performance_resource_timing.html b/src/browser/tests/performance_resource_timing.htmlindex 2a9647e23..d8815090f 100644--- a/src/browser/tests/performance_resource_timing.html+++ b/src/browser/tests/performance_resource_timing.html@@ -17,7 +17,8 @@testing.expectEqual(e.decodedBodySize, e.encodedBodySize);testing.expectEqual(true, e.transferSize > e.encodedBodySize);testing.expectEqual(1, performance.getEntriesByType('resource').length);- testing.expectEqual(e, performance.getEntries()[0]);+ // [0] is the navigation entry+ testing.expectEqual(e, performance.getEntries()[1]);</script><script id=fetch_entry type=module>diff --git a/src/browser/webapi/Performance.zig b/src/browser/webapi/Performance.zigindex be078dff3..2d4ec0071 100644--- a/src/browser/webapi/Performance.zig+++ b/src/browser/webapi/Performance.zig@@ -37,7 +37,7 @@ const DEFAULT_RESOURCE_BUFFER_SIZE = 250;const BUFFER_FULL = "resourcetimingbufferfull";pub fn registerTypes() []const type {- return &.{ Performance, Entry, Mark, Measure, ResourceTiming, PerformanceTiming, PerformanceNavigation };+ return &.{ Performance, Entry, Mark, Measure, ResourceTiming, NavigationTiming, PerformanceTiming, PerformanceNavigation };}const Performance = @This();@@ -61,6 +61,11 @@ _resources: std.ArrayList(*Entry) = .empty,_secondary_resources: std.ArrayList(*Entry) = .empty,_timing: PerformanceTiming = .{},_navigation: PerformanceNavigation = .{},+// This document's PerformanceNavigationTiming, also in _entries. Null until+// the document's response arrives, and for about:blank, srcdoc and blob:.+_navigation_timing: ?*NavigationTiming = null,+// Set by the Frame before it fetches the document.+_navigation_type: NavigationTiming.Type = .navigate,_event_counts: EventCounts = .{},_resource_buffer_size: u32 = DEFAULT_RESOURCE_BUFFER_SIZE,_buffer_full_pending: bool = false,@@ -262,7 +267,7 @@ fn clearResourceTimings(self: *Performance) void {}// All times are microseconds-const ResourceInfo = struct {+pub const ResourceInfo = struct {name: []const u8,initiator: []const u8, // static stringprotocol: []const u8, // static string@@ -285,6 +290,7 @@ const ResourceInfo = struct {content_type: []const u8, // unsafe to reference past the function callcontent_encoding: []const u8, // unsafe to reference past the function callfrom_cache: bool,+ redirect_count: u16 = 0,// Every response in the chain was same-origin or carried a matching// Timing-Allow-Origin.timing_allow: bool,@@ -302,18 +308,80 @@ pub fn addResource(self: *Performance, info: ResourceInfo) !void {}}- const arena = self._arena;+ const entry, const resource = try self.resourceTimingValues(info);+ const rt = try self._factory.chained(.{ entry, resource });+ rt._proto._type = .{ .resource = rt };+ // Observers see every entry; only the buffer has a cap.+ try self.notifyObservers(rt._proto);+ if (buffer) |b| {+ try self.insertOrdered(b, rt._proto);+ }+}++// The document's own fetch. Its startTime is the time origin, and it only+// gets a duration once the load event ends (see markNavigation).+pub fn addNavigation(self: *Performance, info: ResourceInfo) !void {+ if (self._navigation_timing != null) {+ return;+ }+ var entry, var resource = try self.resourceTimingValues(info);+ entry._start_time = 0;+ entry._duration = 0;+ resource._initiator_type = "navigation";+ // The final hop's start, even when the redirects are hidden.+ resource._fetch_start = self.relative(info.fetch_start);+ const nt = try self._factory.chained(.{+ entry,+ resource,+ NavigationTiming{+ ._proto = undefined,+ ._type = self._navigation_type,+ ._redirect_count = info.redirect_count,+ },+ });+ const rt = nt._proto;+ rt._type = .{ .navigation = nt };+ rt._proto._type = .{ .navigation = rt };+ self._navigation_timing = nt;+ try self.insertOrdered(&self._entries, rt._proto);+ try self.notifyObservers(rt._proto);+}++pub const NavigationPhase = enum {+ dom_interactive,+ dom_content_loaded_event_start,+ dom_content_loaded_event_end,+ dom_complete,+ load_event_start,+ load_event_end,+};++// Stamps a document lifecycle step on the navigation entry. Only the first+// time counts: document.open() can run these steps again.+pub fn markNavigation(self: *Performance, comptime phase: NavigationPhase) void {+ const nt = self._navigation_timing orelse return;+ const field = &@field(nt, "_" ++ @tagName(phase));+ if (field.* != 0) {+ return;+ }+ field.* = self.now();+ if (phase == .load_event_end) {+ nt._proto._proto._duration = field.*;+ }+}++fn resourceTimingValues(self: *const Performance, info: ResourceInfo) !struct { Entry, ResourceTiming } {const allow = info.timing_allow;const redirected = allow and info.redirect_start != 0; // redirects only show with a TAOconst start_time = self.relative(info.start);const response_end = self.relative(info.response_end);- const rt = try self._factory.chained(.{+ return .{Entry{._start_time = start_time,._duration = @max(response_end - start_time, 0),- ._name = try arena.dupe(u8, info.name),+ ._name = try self._arena.dupe(u8, info.name),._type = undefined,},ResourceTiming{@@ -339,13 +407,7 @@ pub fn addResource(self: *Performance, info: ResourceInfo) !void {._content_type = if (allow) minimizeMimeType(info.content_type) else "",._content_encoding = if (allow) contentEncoding(info.content_encoding) else "",},- });- rt._proto._type = .{ .resource = rt };- // Observers see every entry; only the buffer has a cap.- try self.notifyObservers(rt._proto);- if (buffer) |b| {- try self.insertOrdered(b, rt._proto);- }+ };}fn canAddResource(self: *const Performance) bool {@@ -798,7 +860,7 @@ pub const Entry = struct {@"long-animation-frame",longtask,measure: *Measure,- navigation,+ navigation: *ResourceTiming,paint,resource: *ResourceTiming,taskattribution,@@ -994,6 +1056,7 @@ const ResourceTiming = struct {pub const Proto = Entry;_proto: *Entry,+ _type: Type = .generic,_initiator_type: []const u8,_next_hop_protocol: []const u8,_delivery_type: []const u8,@@ -1015,6 +1078,11 @@ const ResourceTiming = struct {_content_type: []const u8,_content_encoding: []const u8,+ const Type = union(enum) {+ generic,+ navigation: *NavigationTiming,+ };+fn getInitiatorType(self: *const ResourceTiming) []const u8 {return self._initiator_type;}@@ -1205,6 +1273,172 @@ const ResourceTiming = struct {};};+/// PerformanceNavigationTiming — the document's own fetch and load steps.+/// https://w3c.github.io/navigation-timing/#sec-PerformanceNavigationTiming+const NavigationTiming = struct {+ pub const Proto = ResourceTiming;++ _proto: *ResourceTiming,+ _type: Type,+ _redirect_count: u16,+ // Milliseconds since the time origin; 0 until the step happens.+ _dom_interactive: f64 = 0,+ _dom_content_loaded_event_start: f64 = 0,+ _dom_content_loaded_event_end: f64 = 0,+ _dom_complete: f64 = 0,+ _load_event_start: f64 = 0,+ _load_event_end: f64 = 0,++ pub const Type = enum {+ navigate,+ reload,+ back_forward,+ };++ fn getUnloadEventStart(_: *const NavigationTiming) f64 {+ // The previous document's unload isn't timed.+ return 0;+ }++ fn getUnloadEventEnd(_: *const NavigationTiming) f64 {+ return 0;+ }++ fn getDomInteractive(self: *const NavigationTiming) f64 {+ return self._dom_interactive;+ }++ fn getDomContentLoadedEventStart(self: *const NavigationTiming) f64 {+ return self._dom_content_loaded_event_start;+ }++ fn getDomContentLoadedEventEnd(self: *const NavigationTiming) f64 {+ return self._dom_content_loaded_event_end;+ }++ fn getDomComplete(self: *const NavigationTiming) f64 {+ return self._dom_complete;+ }++ fn getLoadEventStart(self: *const NavigationTiming) f64 {+ return self._load_event_start;+ }++ fn getLoadEventEnd(self: *const NavigationTiming) f64 {+ return self._load_event_end;+ }++ fn getType(self: *const NavigationTiming) []const u8 {+ return @tagName(self._type);+ }++ fn getRedirectCount(self: *const NavigationTiming) u16 {+ return self._redirect_count;+ }++ pub fn toJSON(self: *const NavigationTiming) struct {+ name: []const u8,+ entryType: []const u8,+ startTime: f64,+ duration: f64,+ initiatorType: []const u8,+ nextHopProtocol: []const u8,+ deliveryType: []const u8,+ workerStart: f64,+ redirectStart: f64,+ redirectEnd: f64,+ fetchStart: f64,+ domainLookupStart: f64,+ domainLookupEnd: f64,+ connectStart: f64,+ connectEnd: f64,+ secureConnectionStart: f64,+ requestStart: f64,+ responseStart: f64,+ firstInterimResponseStart: f64,+ finalResponseHeadersStart: f64,+ responseEnd: f64,+ transferSize: u64,+ encodedBodySize: u64,+ decodedBodySize: u64,+ responseStatus: u16,+ contentType: []const u8,+ contentEncoding: []const u8,+ unloadEventStart: f64,+ unloadEventEnd: f64,+ domInteractive: f64,+ domContentLoadedEventStart: f64,+ domContentLoadedEventEnd: f64,+ domComplete: f64,+ loadEventStart: f64,+ loadEventEnd: f64,+ type: []const u8,+ redirectCount: u16,+ } {+ const r = self._proto.toJSON();+ return .{+ .name = r.name,+ .entryType = r.entryType,+ .startTime = r.startTime,+ .duration = r.duration,+ .initiatorType = r.initiatorType,+ .nextHopProtocol = r.nextHopProtocol,+ .deliveryType = r.deliveryType,+ .workerStart = r.workerStart,+ .redirectStart = r.redirectStart,+ .redirectEnd = r.redirectEnd,+ .fetchStart = r.fetchStart,+ .domainLookupStart = r.domainLookupStart,+ .domainLookupEnd = r.domainLookupEnd,+ .connectStart = r.connectStart,+ .connectEnd = r.connectEnd,+ .secureConnectionStart = r.secureConnectionStart,+ .requestStart = r.requestStart,+ .responseStart = r.responseStart,+ .firstInterimResponseStart = r.firstInterimResponseStart,+ .finalResponseHeadersStart = r.finalResponseHeadersStart,+ .responseEnd = r.responseEnd,+ .transferSize = r.transferSize,+ .encodedBodySize = r.encodedBodySize,+ .decodedBodySize = r.decodedBodySize,+ .responseStatus = r.responseStatus,+ .contentType = r.contentType,+ .contentEncoding = r.contentEncoding,+ .unloadEventStart = 0,+ .unloadEventEnd = 0,+ .domInteractive = self._dom_interactive,+ .domContentLoadedEventStart = self._dom_content_loaded_event_start,+ .domContentLoadedEventEnd = self._dom_content_loaded_event_end,+ .domComplete = self._dom_complete,+ .loadEventStart = self._load_event_start,+ .loadEventEnd = self._load_event_end,+ .type = @tagName(self._type),+ .redirectCount = self._redirect_count,+ };+ }++ pub const JsApi = struct {+ pub const bridge = js.Bridge(NavigationTiming);++ pub const Meta = struct {+ pub const name = "PerformanceNavigationTiming";+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const unloadEventStart = bridge.accessor(NavigationTiming.getUnloadEventStart, null, .{});+ pub const unloadEventEnd = bridge.accessor(NavigationTiming.getUnloadEventEnd, null, .{});+ pub const domInteractive = bridge.accessor(NavigationTiming.getDomInteractive, null, .{});+ pub const domContentLoadedEventStart = bridge.accessor(NavigationTiming.getDomContentLoadedEventStart, null, .{});+ pub const domContentLoadedEventEnd = bridge.accessor(NavigationTiming.getDomContentLoadedEventEnd, null, .{});+ pub const domComplete = bridge.accessor(NavigationTiming.getDomComplete, null, .{});+ pub const loadEventStart = bridge.accessor(NavigationTiming.getLoadEventStart, null, .{});+ pub const loadEventEnd = bridge.accessor(NavigationTiming.getLoadEventEnd, null, .{});+ pub const @"type" = bridge.accessor(NavigationTiming.getType, null, .{});+ pub const redirectCount = bridge.accessor(NavigationTiming.getRedirectCount, null, .{});+ pub const toJSON = bridge.function(NavigationTiming.toJSON, .{});+ };+};+/// PerformanceTiming — Navigation Timing Level 1 (legacy, but widely used)./// https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming/// All properties return 0 as stub values; the object must not be undefined@@ -1278,6 +1512,10 @@ test "WebApi: Performance.resource_timing" {try testing.htmlRunner("performance_resource_timing_buffer_full.html", .{});}+test "WebApi: Performance.navigation_timing" {+ try testing.htmlRunner("performance_navigation_timing.html", .{});+}+test "Performance: minimizeMimeType" {// The WPT table: /mimesniff/mime-types/resources/mime-types-minimized.jsonconst cases = [_][2][]const u8{diff --git a/src/browser/webapi/PerformanceObserver.zig b/src/browser/webapi/PerformanceObserver.zigindex db8f737f3..42d8d29fc 100644--- a/src/browser/webapi/PerformanceObserver.zig+++ b/src/browser/webapi/PerformanceObserver.zig@@ -170,7 +170,7 @@ pub fn takeRecords(self: *PerformanceObserver) ![]*Performance.Entry {}fn getSupportedEntryTypes() []const []const u8 {- return &.{ "mark", "measure", "resource" };+ return &.{ "mark", "measure", "navigation", "resource" };}/// Returns true if observer interested with given entry.diff --git a/src/network/HttpClient.zig b/src/network/HttpClient.zigindex b3cc57ae2..896e63392 100644--- a/src/network/HttpClient.zig+++ b/src/network/HttpClient.zig@@ -3422,6 +3422,7 @@ pub const Transfer = struct {}t.redirect_end = now;t.fetch_start = now;+ t.redirect_count +|= 1;if (t.timing_allow) {const target = self.timingTarget() orelse return;t.timing_allow = timingAllowPassed(target.origin, self.req.url, headers, t.tainted);@@ -3431,6 +3432,9 @@ pub const Transfer = struct {// If A -> B -> A, we sent the tainted flag (on the B -> A transition) so// that we know how to apply the timing-allow-origin header.fn redirectTaint(self: *Transfer, url: []const u8) void {+ if (!URL.isSameOrigin(url, self.req.url)) {+ self._timing.cross_origin_redirect = true;+ }const target = self.timingTarget() orelse return;const origin = target.origin orelse "null";if (!URL.isSameOrigin(self.req.url, origin) and !URL.isSameOrigin(url, self.req.url)) {@@ -3482,7 +3486,16 @@ pub const Transfer = struct {return;}t.recorded = true;- const target = self.timingTarget() orelse return;+ const target = self.timingTarget();+ // A document is also its own frame's navigation entry.+ const navigation: ?*Performance = blk: {+ if (self.req.resource_type != .document) break :blk null;+ const owner = self.owner orelse break :blk null;+ break :blk owner.scope.performance();+ };+ if (target == null and navigation == null) {+ return;+ }if (t.response_end == 0) {// Cache hit, interceptor-fulfilled, or failed: delivered now.@@ -3497,11 +3510,9 @@ pub const Transfer = struct {var status: u16 = 0;var content_type: []const u8 = "";- var timing_allow = false;if (self.res.header) |*rh| {status = rh.status;content_type = rh.contentType() orelse "";- timing_allow = t.timing_allow and timingAllowPassed(target.origin, self.req.url, self.res.headers, t.tainted);}// A cached body is stored decoded; its wire size is long gone. A@@ -3516,7 +3527,7 @@ pub const Transfer = struct {encoded_body_size = known;}- target.performance.addResource(.{+ var info: Performance.ResourceInfo = .{.name = t.url,.initiator = switch (self.req.resource_type) {// A document fetch only makes the timeline as a child frame.@@ -3555,10 +3566,31 @@ pub const Transfer = struct {.content_type = content_type,.content_encoding = self.responseHeader("content-encoding") orelse "",.from_cache = t.cache != .none,- .timing_allow = timing_allow,- }) catch |err| {- log.err(.http, "resource timing", .{ .err = err, .req = self });+ .timing_allow = false,+ .redirect_count = t.redirect_count,};++ if (target) |tt| {+ info.timing_allow = self.res.header != null and t.timing_allow and timingAllowPassed(tt.origin, self.req.url, self.res.headers, t.tainted);+ tt.performance.addResource(info) catch |err| {+ log.err(.http, "resource timing", .{ .err = err, .req = self });+ };+ }++ if (navigation) |perf| {+ // Named after the final URL, as document.URL is. The document+ // times its own fetch, so no Timing-Allow-Origin applies.+ info.name = self.req.url;+ info.timing_allow = self.res.header != null;+ if (t.cross_origin_redirect) {+ info.redirect_start = 0;+ info.redirect_end = 0;+ info.redirect_count = 0;+ }+ perf.addNavigation(info) catch |err| {+ log.err(.http, "navigation timing", .{ .err = err, .req = self });+ };+ }}fn deliversHeaderBeforeError(self: *const Transfer, conn: *const http.Connection) !bool {@@ -4673,6 +4705,9 @@ const ResourceTiming = struct {// https://fetch.spec.whatwg.org/#concept-request-tainted-origintainted: bool = false,recorded: bool = false,+ redirect_count: u16 = 0,+ // A navigation only exposes its redirects if they all stayed on one origin.+ cross_origin_redirect: bool = false,const CacheState = enum { none, local, validated };