Skip to content

Lightpanda: the headless browser designed for AI and automation

design: TaggedOpaque fromJS is now offset based

Karl Seguina1a8fb6dc31f
diff --git a/src/browser/Factory.zig b/src/browser/Factory.zig
index 5abf4c3ef..f48477d38 100644
--- a/src/browser/Factory.zig
+++ b/src/browser/Factory.zig
@@ -76,13 +76,6 @@ pub fn eventTargetWithAllocator(_: *const Factory, allocator: Allocator, child:
return chain.get(1);
}
-pub fn standaloneEventTarget(self: *Factory, child: anytype) !*EventTarget {
- const allocator = self._slab.allocator();
- const et = try allocator.create(EventTarget);
- et.* = .{ ._type = unionInit(EventTarget.Type, child) };
- return et;
-}
-
// this is a root object
pub fn event(_: *const Factory, arena: Allocator, typ: String, child: anytype) !*@TypeOf(child) {
const chain = try PrototypeChain(
@@ -370,6 +363,53 @@ pub fn chainOffsetOf(comptime Leaf: type, comptime T: type) usize {
}
}
+// Byte delta from T down to its Proto within any chain allocation containing
+// them (the prefix layout is the same for every leaf).
+pub fn protoOffset(comptime T: type) usize {
+ const P = reflect.Proto(T).?;
+ return chainOffsetOf(T, T) - chainOffsetOf(T, P);
+}
+
+// Generic contiguous chain from explicit values, for chains whose middles
+// can't be default-initialized by AutoPrototypeChain. Callers pass every
+// level's value in root-to-leaf order, with `undefined` for `_proto` and for
+// any field that must point at another chain member, patching the latter on
+// the result.
+pub fn chained(self: *Factory, values: anytype) !*ChainedLeaf(@TypeOf(values)) {
+ return chainedWithAllocator(self._slab.allocator(), values);
+}
+
+pub fn chainedWithAllocator(allocator: Allocator, values: anytype) !*ChainedLeaf(@TypeOf(values)) {
+ const fields = @typeInfo(@TypeOf(values)).@"struct".fields;
+ const types = comptime blk: {
+ var types: [fields.len]type = undefined;
+ for (fields, 0..) |f, i| {
+ types[i] = f.type;
+ }
+ break :blk types;
+ };
+ comptime {
+ for (types[1..], 0..) |T, i| {
+ assert(reflect.Proto(T).? == types[i]);
+ }
+ }
+
+ const chain = try PrototypeChain(&types).allocate(allocator);
+ inline for (0..types.len) |i| {
+ const ptr = chain.get(i);
+ ptr.* = values[i];
+ if (i > 0) {
+ ptr._proto = chain.get(i - 1);
+ }
+ }
+ return chain.get(types.len - 1);
+}
+
+fn ChainedLeaf(comptime Values: type) type {
+ const fields = @typeInfo(Values).@"struct".fields;
+ return fields[fields.len - 1].type;
+}
+
pub fn document(self: *Factory, child: anytype) !*@TypeOf(child) {
const allocator = self._slab.allocator();
return try AutoPrototypeChain(
diff --git a/src/browser/Session.zig b/src/browser/Session.zig
index c3a741a7d..2dc42438b 100644
--- a/src/browser/Session.zig
+++ b/src/browser/Session.zig
@@ -25,6 +25,8 @@ const App = @import("../App.zig");
const History = @import("webapi/History.zig");
const storage = @import("webapi/storage/storage.zig");
const IdbManager = @import("webapi/storage/idb/idb.zig").Manager;
+const Factory = @import("Factory.zig");
+const EventTarget = @import("webapi/EventTarget.zig");
const Navigation = @import("webapi/navigation/Navigation.zig");
const Page = @import("Page.zig");
@@ -50,7 +52,7 @@ const Session = @This();
browser: *Browser,
arena: Allocator,
history: History,
-navigation: Navigation,
+navigation: *Navigation,
storage_shed: storage.Shed,
// Per-origin IndexedDB engines
idb: IdbManager,
@@ -161,12 +163,17 @@ pub fn init(self: *Session, browser: *Browser, notification: *Notification) !voi
const arena = try arena_pool.acquire(.small, "Session");
errdefer arena_pool.release(arena);
+ const navigation = try Factory.chainedWithAllocator(arena, .{
+ EventTarget{ ._type = undefined },
+ Navigation{ ._proto = undefined },
+ });
+ navigation._proto._type = .{ .navigation = navigation };
+
self.* = .{
.arena = arena,
.arena_pool = arena_pool,
.history = .{},
- // The prototype (EventTarget) for Navigation is created when a Frame is created.
- .navigation = .{ ._proto = undefined },
+ .navigation = navigation,
.storage_shed = .{},
.idb = IdbManager.init(allocator),
.browser = browser,
@@ -345,7 +352,6 @@ fn installNewActivePage(self: *Session, frame_id: u32) !*Frame {
errdefer _ = self.pages.pop();
const frame = &page.frame;
- try self.navigation.onNewFrame(frame);
// Inform CDP the main frame has been created such that additional
// context for other Worlds can be created as well.
self.notification.dispatch(.frame_created, frame);
@@ -896,9 +902,6 @@ pub fn commitPendingPage(self: *Session, replacement: *Page) !void {
// set, so the session still reports an in-flight nav and CDP's frameCreated
// skips the captured_responses / frame_arena reset that would wipe the
// response we just received.
- self.navigation.onNewFrame(&replacement.frame) catch |err| {
- log.err(.browser, "commitPendingPage onNewFrame", .{ .err = err });
- };
self.notification.dispatch(.frame_created, &replacement.frame);
// Step 3: promote — clear `replaces` and unlink OLD so `livePage()`
diff --git a/src/browser/js/Local.zig b/src/browser/js/Local.zig
index f3216a560..cc1343704 100644
--- a/src/browser/js/Local.zig
+++ b/src/browser/js/Local.zig
@@ -25,6 +25,7 @@ const Page = @import("../Page.zig");
const js = @import("js.zig");
const bridge = @import("bridge.zig");
+const Factory = @import("../Factory.zig");
const reflect = @import("../reflect.zig");
const Caller = @import("Caller.zig");
const Context = @import("Context.zig");
@@ -1295,6 +1296,9 @@ pub fn resolveValue(value: anytype) Resolved {
}
fn resolveT(comptime T: type, value: *T) Resolved {
+ if (comptime IS_DEBUG) {
+ assertChainContiguity(T, value);
+ }
const Meta = T.JsApi.Meta;
return .{
.ptr = value,
@@ -1386,6 +1390,16 @@ fn resolveT(comptime T: type, value: *T) Resolved {
};
}
+// Every wrapped chain must be contiguous — the TaggedOpaque walk upcasts by
+// pointer arithmetic. The stored _proto fields double as the canary.
+fn assertChainContiguity(comptime T: type, value: *T) void {
+ if (comptime reflect.Proto(T) != null) {
+ const P = comptime reflect.Proto(T).?;
+ std.debug.assert(@intFromPtr(value._proto) == @intFromPtr(value) - comptime Factory.protoOffset(T));
+ assertChainContiguity(P, value._proto);
+ }
+}
+
// Start at the "resolved" type (the most specific) and work our way up the
// prototype chain looking for the type that defines acquireRef
fn findFinalizerType(comptime T: type) ?type {
diff --git a/src/browser/js/TaggedOpaque.zig b/src/browser/js/TaggedOpaque.zig
index ca20b3ef5..092a08542 100644
--- a/src/browser/js/TaggedOpaque.zig
+++ b/src/browser/js/TaggedOpaque.zig
@@ -73,7 +73,9 @@ subtype: ?bridge.SubType,
pub const PrototypeChainEntry = struct {
index: bridge.JsApiLookup.BackingInt,
- offset: u16, // offset to the _proto field
+ // byte delta from the previous chain member down to this one; every
+ // member of a prototype chain lives in one contiguous factory allocation
+ offset: u16,
};
// Reverses the mapZigInstanceToJs, making sure that our TaggedOpaque
@@ -125,12 +127,10 @@ pub fn fromJS(comptime R: type, js_obj_handle: *const v8.Object) !R {
// Ok, let's walk up the chain
var ptr = @intFromPtr(tao.value);
for (prototype_chain[1..]) |proto| {
- ptr += proto.offset; // the offset to the _proto field
- const proto_ptr: **anyopaque = @ptrFromInt(ptr);
+ ptr -= proto.offset;
if (proto.index == expected_type_index) {
- return @ptrCast(@alignCast(proto_ptr.*));
+ return @ptrFromInt(ptr);
}
- ptr = @intFromPtr(proto_ptr.*);
}
return error.InvalidArgument;
}
diff --git a/src/browser/js/Value.zig b/src/browser/js/Value.zig
index c57f5ef26..d68452c51 100644
--- a/src/browser/js/Value.zig
+++ b/src/browser/js/Value.zig
@@ -531,12 +531,10 @@ const CloneDelegate = struct {
// closest cloneable supertype (mirrors TaggedOpaque.fromJS).
var ptr = @intFromPtr(tao.value);
for (prototype_chain[1..]) |proto| {
- ptr += proto.offset;
- const proto_ptr: **anyopaque = @ptrFromInt(ptr);
- if (writeCloneable(ctx, proto.index, proto_ptr.*)) |result| {
+ ptr -= proto.offset;
+ if (writeCloneable(ctx, proto.index, @ptrFromInt(ptr))) |result| {
return result;
}
- ptr = @intFromPtr(proto_ptr.*);
}
}
diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zig
index f0000c1a1..40fd0a7a2 100644
--- a/src/browser/js/bridge.zig
+++ b/src/browser/js/bridge.zig
@@ -20,6 +20,7 @@ const std = @import("std");
const lp = @import("lightpanda");
const Frame = @import("../Frame.zig");
+const Factory = @import("../Factory.zig");
const reflect = @import("../reflect.zig");
const js = @import("js.zig");
@@ -109,7 +110,7 @@ pub fn Builder(comptime T: type) type {
const Next = PrototypeType(Prototype).?;
entry.* = .{
.index = JsApiLookup.getId(Next.JsApi),
- .offset = @offsetOf(Prototype, "_proto"),
+ .offset = Factory.protoOffset(Prototype),
};
Prototype = Next;
}
diff --git a/src/browser/webapi/Blob.zig b/src/browser/webapi/Blob.zig
index becdbade0..b6b74d011 100644
--- a/src/browser/webapi/Blob.zig
+++ b/src/browser/webapi/Blob.zig
@@ -84,7 +84,15 @@ pub fn init(parts_: ?[]const js.Value, opts_: ?InitOptions, page: *Page) !*Blob
const arena = try session.getArena(.large, "Blob");
errdefer session.releaseArena(arena);
- const opts: InitOptions = opts_ orelse .{};
+ const self = try arena.create(Blob);
+ self.* = try buildValue(arena, parts_, opts_ orelse .{});
+ return self;
+}
+
+// The Blob value for `parts`, with everything it references copied to
+// `arena`. Callers either arena.create it (init) or embed it as the root of
+// a {Blob, File} chain.
+pub fn buildValue(arena: Allocator, parts_: ?[]const js.Value, opts: InitOptions) !Blob {
const mime = try Mime.serialize(arena, opts.type);
const data = blk: {
@@ -101,33 +109,32 @@ pub fn init(parts_: ?[]const js.Value, opts_: ?InitOptions, page: *Page) !*Blob
break :blk "";
};
- const self = try arena.create(Blob);
- self.* = .{
+ return .{
._rc = .{},
._arena = arena,
._type = .generic,
._slice = data,
._mime = mime,
};
- return self;
+}
+
+pub fn buildValueFromBytes(arena: Allocator, data: []const u8, content_type: []const u8) !Blob {
+ return .{
+ ._rc = .{},
+ ._arena = arena,
+ ._type = .generic,
+ ._slice = try arena.dupe(u8, data),
+ ._mime = try Mime.serialize(arena, content_type),
+ };
}
/// Creates a new Blob from raw byte slices (for internal Zig use).
pub fn initFromBytes(data: []const u8, content_type: []const u8, page: *Page) !*Blob {
- // + 256 because the arena might also be used by File
const arena = try page.getArena(data.len + content_type.len + 256, "Blob");
errdefer page.releaseArena(arena);
- const mime = try Mime.serialize(arena, content_type);
-
const self = try arena.create(Blob);
- self.* = .{
- ._rc = .{},
- ._arena = arena,
- ._type = .generic,
- ._slice = try arena.dupe(u8, data),
- ._mime = mime,
- };
+ self.* = try buildValueFromBytes(arena, data, content_type);
return self;
}
diff --git a/src/browser/webapi/DOMMatrix.zig b/src/browser/webapi/DOMMatrix.zig
index 8f915020c..30dd0072a 100644
--- a/src/browser/webapi/DOMMatrix.zig
+++ b/src/browser/webapi/DOMMatrix.zig
@@ -20,6 +20,7 @@ const std = @import("std");
const js = @import("../js/js.zig");
const Page = @import("../Page.zig");
+const Factory = @import("../Factory.zig");
const RO = @import("DOMMatrixReadOnly.zig");
const DOMMatrix = @This();
@@ -33,15 +34,15 @@ pub fn init(init_: ?js.Value, exec: *const js.Execution) !*DOMMatrix {
return create(parsed.m, parsed.is_2d, exec.page);
}
-// Builds the [DOMMatrixReadOnly, DOMMatrix] prototype chain on a single arena
-// (owned by the base) and cross-links them, the same way File wraps Blob.
pub fn create(m: [16]f64, is_2d: bool, page: *Page) !*DOMMatrix {
- const proto = try RO.createBare(m, is_2d, page);
- errdefer proto.deinit(page);
-
- const self = try proto._arena.create(DOMMatrix);
- self.* = .{ ._proto = proto };
- proto._type = .{ .mutable = self };
+ const arena = try page.getArena(.tiny, "DOMMatrix");
+ errdefer page.releaseArena(arena);
+
+ const self = try Factory.chainedWithAllocator(arena, .{
+ RO.buildValue(arena, m, is_2d),
+ DOMMatrix{ ._proto = undefined },
+ });
+ self._proto._type = .{ .mutable = self };
return self;
}
diff --git a/src/browser/webapi/DOMMatrixReadOnly.zig b/src/browser/webapi/DOMMatrixReadOnly.zig
index e70658e25..d25d8a0fb 100644
--- a/src/browser/webapi/DOMMatrixReadOnly.zig
+++ b/src/browser/webapi/DOMMatrixReadOnly.zig
@@ -85,14 +85,18 @@ pub fn createBare(m: [16]f64, is_2d: bool, page: *Page) !*DOMMatrixReadOnly {
errdefer page.releaseArena(arena);
const self = try arena.create(DOMMatrixReadOnly);
- self.* = .{
+ self.* = buildValue(arena, m, is_2d);
+ return self;
+}
+
+pub fn buildValue(arena: std.mem.Allocator, m: [16]f64, is_2d: bool) DOMMatrixReadOnly {
+ return .{
._rc = .{},
._arena = arena,
._type = .generic,
._m = m,
._is_2d = is_2d,
};
- return self;
}
pub fn getState(self: *const DOMMatrixReadOnly) State {
diff --git a/src/browser/webapi/DOMPoint.zig b/src/browser/webapi/DOMPoint.zig
index 02055669f..198673330 100644
--- a/src/browser/webapi/DOMPoint.zig
+++ b/src/browser/webapi/DOMPoint.zig
@@ -18,6 +18,7 @@
const js = @import("../js/js.zig");
const Page = @import("../Page.zig");
+const Factory = @import("../Factory.zig");
const RO = @import("DOMPointReadOnly.zig");
const DOMPoint = @This();
@@ -31,12 +32,14 @@ pub fn init(x_: ?f64, y_: ?f64, z_: ?f64, w_: ?f64, exec: *const js.Execution) !
}
pub fn create(x: f64, y: f64, z: f64, w: f64, page: *Page) !*DOMPoint {
- const proto = try RO.createBare(x, y, z, w, page);
- errdefer proto.deinit(page);
-
- const self = try proto._arena.create(DOMPoint);
- self.* = .{ ._proto = proto };
- proto._type = .{ .mutable = self };
+ const arena = try page.getArena(.tiny, "DOMPoint");
+ errdefer page.releaseArena(arena);
+
+ const self = try Factory.chainedWithAllocator(arena, .{
+ RO.buildValue(arena, x, y, z, w),
+ DOMPoint{ ._proto = undefined },
+ });
+ self._proto._type = .{ .mutable = self };
return self;
}
@@ -50,13 +53,11 @@ pub fn structuredSerialize(self: *const DOMPoint, writer: *js.StructuredWriter)
}
pub fn structuredDeserialize(reader: *js.StructuredReader, page: *Page) !*DOMPoint {
- const proto = try RO.structuredDeserialize(reader, page);
- errdefer proto.deinit(page);
-
- const self = try proto._arena.create(DOMPoint);
- self.* = .{ ._proto = proto };
- proto._type = .{ .mutable = self };
- return self;
+ const x: f64 = @bitCast(try reader.readUint64());
+ const y: f64 = @bitCast(try reader.readUint64());
+ const z: f64 = @bitCast(try reader.readUint64());
+ const w: f64 = @bitCast(try reader.readUint64());
+ return create(x, y, z, w, page);
}
// DOMPoint redeclares x/y/z/w as writable (`inherit attribute` in the IDL), so
diff --git a/src/browser/webapi/DOMPointReadOnly.zig b/src/browser/webapi/DOMPointReadOnly.zig
index a0bf84a2f..277c57b2b 100644
--- a/src/browser/webapi/DOMPointReadOnly.zig
+++ b/src/browser/webapi/DOMPointReadOnly.zig
@@ -89,7 +89,12 @@ pub fn createBare(x: f64, y: f64, z: f64, w: f64, page: *Page) !*DOMPointReadOnl
errdefer page.releaseArena(arena);
const self = try arena.create(DOMPointReadOnly);
- self.* = .{
+ self.* = buildValue(arena, x, y, z, w);
+ return self;
+}
+
+pub fn buildValue(arena: Allocator, x: f64, y: f64, z: f64, w: f64) DOMPointReadOnly {
+ return .{
._rc = .{},
._arena = arena,
._type = .generic,
@@ -98,7 +103,6 @@ pub fn createBare(x: f64, y: f64, z: f64, w: f64, page: *Page) !*DOMPointReadOnl
._z = z,
._w = w,
};
- return self;
}
pub fn fromPoint(other_: ?DOMPointInit, page: *Page) !*DOMPointReadOnly {
diff --git a/src/browser/webapi/DedicatedWorkerGlobalScope.zig b/src/browser/webapi/DedicatedWorkerGlobalScope.zig
index 90e07154e..c1704477b 100644
--- a/src/browser/webapi/DedicatedWorkerGlobalScope.zig
+++ b/src/browser/webapi/DedicatedWorkerGlobalScope.zig
@@ -53,21 +53,19 @@ _on_messageerror: ?js.Function.Global = null,
_pending_messages: std.ArrayList(?js.Value.Global) = .empty,
pub fn init(worker: *Worker, url: [:0]const u8) !*DedicatedWorkerGlobalScope {
- const self = try worker._arena.create(DedicatedWorkerGlobalScope);
- const proto = try WorkerGlobalScope.init(
+ return WorkerGlobalScope.init(
worker._arena,
url,
- .{ .dedicated = self },
+ .dedicated,
+ DedicatedWorkerGlobalScope{
+ ._worker = worker,
+ ._proto = undefined,
+ },
worker._type == .module,
worker._frame_id,
worker._loader_id,
worker._frame,
);
- self.* = .{
- ._worker = worker,
- ._proto = proto,
- };
- return self;
}
pub fn deinit(self: *DedicatedWorkerGlobalScope) void {
diff --git a/src/browser/webapi/File.zig b/src/browser/webapi/File.zig
index 4ccd54437..a99f34cfa 100644
--- a/src/browser/webapi/File.zig
+++ b/src/browser/webapi/File.zig
@@ -20,6 +20,7 @@ const lp = @import("lightpanda");
const js = @import("../js/js.zig");
const Page = @import("../Page.zig");
+const Factory = @import("../Factory.zig");
const Blob = @import("Blob.zig");
@@ -44,20 +45,22 @@ pub fn init(
page: *Page,
) !*File {
const opts = opts_ orelse InitOptions{};
- const blob = try Blob.init(parts_, .{
- .type = opts.type,
- .endings = opts.endings,
- }, page);
-
- errdefer blob.deinit(page);
-
- const file = try blob._arena.create(File);
- file.* = .{
- ._proto = blob,
- ._name = try blob._arena.dupe(u8, name),
- ._last_modified = opts.lastModified orelse @intCast(lp.datetime.milliTimestamp(.real)),
- };
- blob._type = .{ .file = file };
+ const session = page.session;
+ const arena = try session.getArena(.large, "Blob");
+ errdefer session.releaseArena(arena);
+
+ const file = try Factory.chainedWithAllocator(arena, .{
+ try Blob.buildValue(arena, parts_, .{
+ .type = opts.type,
+ .endings = opts.endings,
+ }),
+ File{
+ ._proto = undefined,
+ ._name = try arena.dupe(u8, name),
+ ._last_modified = opts.lastModified orelse @intCast(lp.datetime.milliTimestamp(.real)),
+ },
+ });
+ file._proto._type = .{ .file = file };
return file;
}
@@ -81,19 +84,30 @@ pub fn structuredSerialize(self: *const File, writer: *js.StructuredWriter) !voi
}
pub fn structuredDeserialize(reader: *js.StructuredReader, page: *Page) !*File {
- const blob = try Blob.structuredDeserialize(reader, page);
- errdefer blob.deinit(page);
-
+ const mime = try reader.readBytes();
+ const data = try reader.readBytes();
const name = try reader.readBytes();
const last_modified = try reader.readUint64();
- const file = try blob._arena.create(File);
- file.* = .{
- ._proto = blob,
- ._name = try blob._arena.dupe(u8, name),
- ._last_modified = @bitCast(last_modified),
- };
- blob._type = .{ .file = file };
+ const arena = try page.getArena(data.len + mime.len + name.len + 256, "Blob.clone");
+ errdefer page.releaseArena(arena);
+
+ const file = try Factory.chainedWithAllocator(arena, .{
+ Blob{
+ ._rc = .{},
+ ._arena = arena,
+ ._type = undefined,
+ ._slice = try arena.dupe(u8, data),
+ // the serialized mime is already in normalized form; copy it verbatim
+ ._mime = try arena.dupe(u8, mime),
+ },
+ File{
+ ._proto = undefined,
+ ._name = try arena.dupe(u8, name),
+ ._last_modified = @bitCast(last_modified),
+ },
+ });
+ file._proto._type = .{ .file = file };
return file;
}
diff --git a/src/browser/webapi/Performance.zig b/src/browser/webapi/Performance.zig
index 0d1ba01b5..f3d6b4f6d 100644
--- a/src/browser/webapi/Performance.zig
+++ b/src/browser/webapi/Performance.zig
@@ -460,17 +460,18 @@ pub const Mark = struct {
}
const detail = if (maybe_detail) |d| try d.persist() else null;
- const m = try exec._factory.create(Mark{
- ._proto = undefined,
- ._detail = detail,
+ const m = try exec._factory.chained(.{
+ Entry{
+ ._start_time = start_time,
+ ._name = try exec.dupeString(name),
+ ._type = undefined,
+ },
+ Mark{
+ ._proto = undefined,
+ ._detail = detail,
+ },
});
-
- const entry = try exec._factory.create(Entry{
- ._start_time = start_time,
- ._name = try exec.dupeString(name),
- ._type = .{ .mark = m },
- });
- m._proto = entry;
+ m._proto._type = .{ .mark = m };
return m;
}
@@ -522,18 +523,19 @@ pub const Measure = struct {
}
const detail = if (maybe_detail) |d| try d.persist() else null;
- const m = try exec._factory.create(Measure{
- ._proto = undefined,
- ._detail = detail,
- });
-
- const entry = try exec._factory.create(Entry{
- ._start_time = start_timestamp,
- ._duration = duration,
- ._name = try exec.dupeString(name),
- ._type = .{ .measure = m },
+ const m = try exec._factory.chained(.{
+ Entry{
+ ._start_time = start_timestamp,
+ ._duration = duration,
+ ._name = try exec.dupeString(name),
+ ._type = undefined,
+ },
+ Measure{
+ ._proto = undefined,
+ ._detail = detail,
+ },
});
- m._proto = entry;
+ m._proto._type = .{ .measure = m };
return m;
}
diff --git a/src/browser/webapi/SharedWorkerGlobalScope.zig b/src/browser/webapi/SharedWorkerGlobalScope.zig
index e3bd25930..9a30447b1 100644
--- a/src/browser/webapi/SharedWorkerGlobalScope.zig
+++ b/src/browser/webapi/SharedWorkerGlobalScope.zig
@@ -71,25 +71,27 @@ pub fn init(frame: *Frame, url: [:0]const u8, name: []const u8, worker_type: Wor
errdefer session.releaseArena(arena);
const owned_url = try arena.dupeZ(u8, url);
- const self = try arena.create(SharedWorkerGlobalScope);
- const proto = try WorkerGlobalScope.init(
+ const frame_id = session.nextFrameId();
+ const loader_id = session.nextLoaderId();
+ const self = try WorkerGlobalScope.init(
arena,
owned_url,
- .{ .shared = self },
+ .shared,
+ SharedWorkerGlobalScope{
+ ._proto = undefined,
+ ._arena = arena,
+ ._url = owned_url,
+ ._name = try arena.dupe(u8, name),
+ ._type = worker_type,
+ ._frame_id = frame_id,
+ ._loader_id = loader_id,
+ },
worker_type == .module,
- session.nextFrameId(),
- session.nextLoaderId(),
+ frame_id,
+ loader_id,
frame,
);
- self.* = .{
- ._proto = proto,
- ._arena = arena,
- ._url = owned_url,
- ._name = try arena.dupe(u8, name),
- ._type = worker_type,
- ._frame_id = proto._frame_id,
- ._loader_id = proto._loader_id,
- };
+ const proto = self._proto;
errdefer proto.deinit();
if (!session.worker_loading_enabled) {
diff --git a/src/browser/webapi/Window.zig b/src/browser/webapi/Window.zig
index cc4207408..542b65a68 100644
--- a/src/browser/webapi/Window.zig
+++ b/src/browser/webapi/Window.zig
@@ -344,7 +344,7 @@ pub fn getHistory(_: *Window, frame: *Frame) *History {
}
pub fn getNavigation(_: *Window, frame: *Frame) *Navigation {
- return &frame._session.navigation;
+ return frame._session.navigation;
}
pub fn setNavigation(self: *Window, value: js.Value) void {
diff --git a/src/browser/webapi/WorkerGlobalScope.zig b/src/browser/webapi/WorkerGlobalScope.zig
index 8610156e1..dc2fc02c5 100644
--- a/src/browser/webapi/WorkerGlobalScope.zig
+++ b/src/browser/webapi/WorkerGlobalScope.zig
@@ -125,12 +125,13 @@ pub const Type = union(enum) {
pub fn init(
arena: Allocator,
url: [:0]const u8,
- child: Type,
+ comptime tag: std.meta.Tag(Type),
+ leaf_value: anytype,
is_module: bool,
frame_id: u32,
loader_id: u32,
frame: *Frame,
-) !*WorkerGlobalScope {
+) !*@TypeOf(leaf_value) {
const session = frame._session;
const call_arena = try session.getArena(.small, "WorkerGlobalScope.call_arena");
@@ -140,29 +141,36 @@ pub fn init(
errdefer session.releaseArena(local_arena);
const factory = frame._factory;
- const self = try factory.eventTargetWithAllocator(arena, WorkerGlobalScope{
- .url = url,
- .arena = arena,
- .origin = frame.origin,
- .js = undefined,
- .call_arena = call_arena,
- .local_arena = local_arena,
- ._frame = frame,
- ._page = frame._page,
- ._session = session,
- ._identity = .{},
- ._type = child,
- ._proto = undefined,
- ._factory = factory,
- ._is_module = is_module,
- ._frame_id = frame_id,
- ._loader_id = loader_id,
- ._event_manager = .init(arena),
- ._script_manager = undefined,
- ._location = .{ ._url = url },
- ._performance = .init(),
- ._http_owner = undefined,
+ const leaf = try Factory.chainedWithAllocator(arena, .{
+ EventTarget{ ._type = undefined },
+ WorkerGlobalScope{
+ .url = url,
+ .arena = arena,
+ .origin = frame.origin,
+ .js = undefined,
+ .call_arena = call_arena,
+ .local_arena = local_arena,
+ ._frame = frame,
+ ._page = frame._page,
+ ._session = session,
+ ._identity = .{},
+ ._type = undefined,
+ ._proto = undefined,
+ ._factory = factory,
+ ._is_module = is_module,
+ ._frame_id = frame_id,
+ ._loader_id = loader_id,
+ ._event_manager = .init(arena),
+ ._script_manager = undefined,
+ ._location = .{ ._url = url },
+ ._performance = .init(),
+ ._http_owner = undefined,
+ },
+ leaf_value,
});
+ const self = leaf._proto;
+ self._type = @unionInit(Type, @tagName(tag), leaf);
+ self._proto._type = .{ .worker_global_scope = self };
self._http_owner = .init(&frame._page.blob_urls, &self.origin);
@@ -185,7 +193,7 @@ pub fn init(
// features like BroadcastChannel can reach across the page/worker boundary.
try self.js.setOrigin(self.origin);
- return self;
+ return leaf;
}
pub fn deinit(self: *WorkerGlobalScope) void {
diff --git a/src/browser/webapi/collections/HTMLCollection.zig b/src/browser/webapi/collections/HTMLCollection.zig
index 57969c406..b203ae5b8 100644
--- a/src/browser/webapi/collections/HTMLCollection.zig
+++ b/src/browser/webapi/collections/HTMLCollection.zig
@@ -21,6 +21,7 @@ const lp = @import("lightpanda");
const js = @import("../../js/js.zig");
const Page = @import("../../Page.zig");
+const Factory = @import("../../Factory.zig");
const Frame = @import("../../Frame.zig");
const Element = @import("../Element.zig");
const TreeWalker = @import("../TreeWalker.zig");
@@ -46,6 +47,8 @@ const Mode = enum {
const HTMLCollection = @This();
+pub const _prototype_root = true;
+
_data: union(Mode) {
tag: NodeLive(.tag),
tag_name: NodeLive(.tag_name),
@@ -63,9 +66,22 @@ _data: union(Mode) {
empty: void,
},
_rc: lp.RC = .{},
+// The refcount is shared with the chain leaf (when there is one), so the
+// last release can dispatch deinit through either pointer. The root must
+// know its allocation shape to destroy the right thing.
+_chained: enum(u8) { standalone, form_controls, options } = .standalone,
pub fn deinit(self: *HTMLCollection, page: *Page) void {
- page.factory.destroy(self);
+ switch (self._chained) {
+ .standalone => page.factory.destroyStandalone(self),
+ .form_controls => page.factory.destroy(self.chainLeaf(@import("HTMLFormControlsCollection.zig"))),
+ .options => page.factory.destroy(self.chainLeaf(@import("HTMLOptionsCollection.zig"))),
+ }
+}
+
+fn chainLeaf(self: *HTMLCollection, comptime Leaf: type) *Leaf {
+ const offset = comptime Factory.chainOffsetOf(Leaf, Leaf) - Factory.chainOffsetOf(Leaf, HTMLCollection);
+ return @ptrFromInt(@intFromPtr(self) + offset);
}
pub fn releaseRef(self: *HTMLCollection, page: *Page) void {
diff --git a/src/browser/webapi/collections/HTMLFormControlsCollection.zig b/src/browser/webapi/collections/HTMLFormControlsCollection.zig
index 3a2bd5951..c842bdcc7 100644
--- a/src/browser/webapi/collections/HTMLFormControlsCollection.zig
+++ b/src/browser/webapi/collections/HTMLFormControlsCollection.zig
@@ -34,13 +34,10 @@ pub const Proto = HTMLCollection;
_proto: *HTMLCollection,
-// The refcount lives on the proto, but anchoring the finalizer here lets
-// deinit reclaim this struct's slot along with the proto's.
+// The refcount lives on the proto, but the finalizer anchors here so deinit
+// destroys the whole {HTMLCollection, self} chain from its leaf.
pub fn deinit(self: *HTMLFormControlsCollection, page: *Page) void {
- self._proto.deinit(page);
- // Not destroy(): the proto is a separate slab allocation, not a
- // contiguous factory chain.
- page.factory.destroyStandalone(self);
+ page.factory.destroy(self);
}
pub fn acquireRef(self: *HTMLFormControlsCollection) void {
@@ -99,13 +96,15 @@ pub fn namedItem(self: *HTMLFormControlsCollection, name: []const u8, frame: *Fr
count += 1;
if (count == 2) {
- const radio_node_list = try frame._factory.create(RadioNodeList{
- ._proto = undefined,
- ._form_collection = self,
- ._name = try frame.dupeString(name),
+ const radio_node_list = try frame._factory.chained(.{
+ NodeList{ ._data = undefined },
+ RadioNodeList{
+ ._proto = undefined,
+ ._form_collection = self,
+ ._name = try frame.dupeString(name),
+ },
});
-
- radio_node_list._proto = try frame._factory.create(NodeList{ ._data = .{ .radio_node_list = radio_node_list } });
+ radio_node_list._proto._data = .{ .radio_node_list = radio_node_list };
// The RadioNodeList outlives this call; its NodeList releases
// the ref in deinit.
diff --git a/src/browser/webapi/collections/HTMLOptionsCollection.zig b/src/browser/webapi/collections/HTMLOptionsCollection.zig
index 123d56214..7a1f638ae 100644
--- a/src/browser/webapi/collections/HTMLOptionsCollection.zig
+++ b/src/browser/webapi/collections/HTMLOptionsCollection.zig
@@ -30,13 +30,10 @@ pub const Proto = HTMLCollection;
_proto: *HTMLCollection,
_select: *@import("../element/html/Select.zig"),
-// The refcount lives on the proto, but anchoring the finalizer here lets
-// deinit reclaim this struct's slot along with the proto's.
+// The refcount lives on the proto, but the finalizer anchors here so deinit
+// destroys the whole {HTMLCollection, self} chain from its leaf.
pub fn deinit(self: *HTMLOptionsCollection, page: *Page) void {
- self._proto.deinit(page);
- // Not destroy(): the proto is a separate slab allocation, not a
- // contiguous factory chain.
- page.factory.destroyStandalone(self);
+ page.factory.destroy(self);
}
pub fn acquireRef(self: *HTMLOptionsCollection) void {
diff --git a/src/browser/webapi/collections/node_live.zig b/src/browser/webapi/collections/node_live.zig
index 3dd18ac88..320f6e082 100644
--- a/src/browser/webapi/collections/node_live.zig
+++ b/src/browser/webapi/collections/node_live.zig
@@ -400,23 +400,29 @@ pub fn NodeLive(comptime mode: Mode) type {
const NodeList = @import("NodeList.zig");
pub fn runtimeGenericWrap(self: Self, frame: *Frame) !if (mode == .name) *NodeList else *HTMLCollection {
- const collection = switch (mode) {
- .name => return frame._factory.create(NodeList{ ._data = .{ .name = self } }),
- .tag => HTMLCollection{ ._data = .{ .tag = self } },
- .tag_name => HTMLCollection{ ._data = .{ .tag_name = self } },
- .tag_name_ns => HTMLCollection{ ._data = .{ .tag_name_ns = self } },
- .class_name => HTMLCollection{ ._data = .{ .class_name = self } },
- .all_elements => HTMLCollection{ ._data = .{ .all_elements = self } },
- .child_elements => HTMLCollection{ ._data = .{ .child_elements = self } },
- .child_tag => HTMLCollection{ ._data = .{ .child_tag = self } },
- .cells => HTMLCollection{ ._data = .{ .cells = self } },
- .select_options => HTMLCollection{ ._data = .{ .select_options = self } },
- .selected_options => HTMLCollection{ ._data = .{ .selected_options = self } },
- .links => HTMLCollection{ ._data = .{ .links = self } },
- .anchors => HTMLCollection{ ._data = .{ .anchors = self } },
- .form => HTMLCollection{ ._data = .{ .form = self } },
+ if (comptime mode == .name) {
+ return frame._factory.create(NodeList{ ._data = .{ .name = self } });
+ }
+ return frame._factory.create(self.htmlCollectionValue());
+ }
+
+ pub fn htmlCollectionValue(self: Self) HTMLCollection {
+ return switch (mode) {
+ .name => @compileError("name mode wraps as a NodeList"),
+ .tag => .{ ._data = .{ .tag = self } },
+ .tag_name => .{ ._data = .{ .tag_name = self } },
+ .tag_name_ns => .{ ._data = .{ .tag_name_ns = self } },
+ .class_name => .{ ._data = .{ .class_name = self } },
+ .all_elements => .{ ._data = .{ .all_elements = self } },
+ .child_elements => .{ ._data = .{ .child_elements = self } },
+ .child_tag => .{ ._data = .{ .child_tag = self } },
+ .cells => .{ ._data = .{ .cells = self } },
+ .select_options => .{ ._data = .{ .select_options = self } },
+ .selected_options => .{ ._data = .{ .selected_options = self } },
+ .links => .{ ._data = .{ .links = self } },
+ .anchors => .{ ._data = .{ .anchors = self } },
+ .form => .{ ._data = .{ .form = self } },
};
- return frame._factory.create(collection);
}
};
}
diff --git a/src/browser/webapi/css/CSSStyleDeclaration.zig b/src/browser/webapi/css/CSSStyleDeclaration.zig
index 23d919132..e05f9c221 100644
--- a/src/browser/webapi/css/CSSStyleDeclaration.zig
+++ b/src/browser/webapi/css/CSSStyleDeclaration.zig
@@ -35,27 +35,20 @@ _element: ?*Element = null,
_properties: std.DoublyLinkedList = .{},
_is_computed: bool = false,
-pub fn init(element: ?*Element, is_computed: bool, frame: *Frame) !*CSSStyleDeclaration {
- const self = try frame._factory.create(CSSStyleDeclaration{
- ._element = element,
- ._is_computed = is_computed,
- });
-
- // Parse the element's existing style attribute into _properties so that
- // subsequent JS reads and writes see all CSS properties, not just newly
- // added ones. Computed styles have no inline attribute to parse.
- if (!is_computed) {
- if (element) |el| {
- if (el.getAttributeSafe(comptime .wrap("style"))) |attr_value| {
- var it = CssParser.parseDeclarationsList(attr_value);
- while (it.next()) |declaration| {
- try self.applyParsedDeclaration(declaration, frame);
- }
- }
+// Parse the element's existing style attribute into _properties so that
+// subsequent JS reads and writes see all CSS properties, not just newly
+// added ones. Computed styles have no inline attribute to parse.
+pub fn parseInlineStyle(self: *CSSStyleDeclaration, frame: *Frame) !void {
+ if (self._is_computed) {
+ return;
+ }
+ const el = self._element orelse return;
+ if (el.getAttributeSafe(comptime .wrap("style"))) |attr_value| {
+ var it = CssParser.parseDeclarationsList(attr_value);
+ while (it.next()) |declaration| {
+ try self.applyParsedDeclaration(declaration, frame);
}
}
-
- return self;
}
pub fn length(self: *const CSSStyleDeclaration) u32 {
diff --git a/src/browser/webapi/css/CSSStyleProperties.zig b/src/browser/webapi/css/CSSStyleProperties.zig
index 79fe583f7..265108a4a 100644
--- a/src/browser/webapi/css/CSSStyleProperties.zig
+++ b/src/browser/webapi/css/CSSStyleProperties.zig
@@ -30,9 +30,15 @@ pub const Proto = CSSStyleDeclaration;
_proto: *CSSStyleDeclaration,
pub fn init(element: ?*Element, is_computed: bool, frame: *Frame) !*CSSStyleProperties {
- return frame._factory.create(CSSStyleProperties{
- ._proto = try CSSStyleDeclaration.init(element, is_computed, frame),
+ const self = try frame._factory.chained(.{
+ CSSStyleDeclaration{
+ ._element = element,
+ ._is_computed = is_computed,
+ },
+ CSSStyleProperties{ ._proto = undefined },
});
+ try self._proto.parseInlineStyle(frame);
+ return self;
}
pub fn asCSSStyleDeclaration(self: *CSSStyleProperties) *CSSStyleDeclaration {
diff --git a/src/browser/webapi/css/CSSStyleRule.zig b/src/browser/webapi/css/CSSStyleRule.zig
index 1fbe265b1..db7c20589 100644
--- a/src/browser/webapi/css/CSSStyleRule.zig
+++ b/src/browser/webapi/css/CSSStyleRule.zig
@@ -13,10 +13,11 @@ _selector_text: []const u8 = "",
_style: ?*CSSStyleProperties = null,
pub fn init(frame: *Frame) !*CSSStyleRule {
- const style_rule = try frame._factory.create(CSSStyleRule{
- ._proto = undefined,
+ const style_rule = try frame._factory.chained(.{
+ CSSRule{ ._type = undefined },
+ CSSStyleRule{ ._proto = undefined },
});
- style_rule._proto = try CSSRule.init(.{ .style = style_rule }, frame);
+ style_rule._proto._type = .{ .style = style_rule };
return style_rule;
}
diff --git a/src/browser/webapi/element/html/Form.zig b/src/browser/webapi/element/html/Form.zig
index 05e8cbbf1..c48b1a9f7 100644
--- a/src/browser/webapi/element/html/Form.zig
+++ b/src/browser/webapi/element/html/Form.zig
@@ -98,11 +98,12 @@ pub fn setMethod(self: *Form, method: []const u8, frame: *Frame) !void {
pub fn getElements(self: *Form, frame: *Frame) !*collections.HTMLFormControlsCollection {
const node_live = self.iterator(frame);
- const html_collection = try node_live.runtimeGenericWrap(frame);
-
- return frame._factory.create(collections.HTMLFormControlsCollection{
- ._proto = html_collection,
+ const elements = try frame._factory.chained(.{
+ node_live.htmlCollectionValue(),
+ collections.HTMLFormControlsCollection{ ._proto = undefined },
});
+ elements._proto._chained = .form_controls;
+ return elements;
}
pub fn iterator(self: *Form, frame: *Frame) collections.NodeLive(.form) {
diff --git a/src/browser/webapi/element/html/Select.zig b/src/browser/webapi/element/html/Select.zig
index 0f5e03c4c..d89c2f732 100644
--- a/src/browser/webapi/element/html/Select.zig
+++ b/src/browser/webapi/element/html/Select.zig
@@ -247,13 +247,15 @@ pub fn getOptions(self: *Select, frame: *Frame) !*collections.HTMLOptionsCollect
// select_options mode is the select's list of options: option children
// plus the option children of optgroup children.
const node_live = collections.NodeLive(.select_options).init(self.asNode(), {}, frame);
- const html_collection = try node_live.runtimeGenericWrap(frame);
-
- // Create and return HTMLOptionsCollection
- return frame._factory.create(collections.HTMLOptionsCollection{
- ._proto = html_collection,
- ._select = self,
+ const options = try frame._factory.chained(.{
+ node_live.htmlCollectionValue(),
+ collections.HTMLOptionsCollection{
+ ._proto = undefined,
+ ._select = self,
+ },
});
+ options._proto._chained = .options;
+ return options;
}
pub fn getLength(self: *Select) u32 {
diff --git a/src/browser/webapi/navigation/Navigation.zig b/src/browser/webapi/navigation/Navigation.zig
index 82dcf3a4f..82649aac3 100644
--- a/src/browser/webapi/navigation/Navigation.zig
+++ b/src/browser/webapi/navigation/Navigation.zig
@@ -22,6 +22,7 @@ const URL = @import("../URL.zig");
const js = @import("../../js/js.zig");
const Frame = @import("../../Frame.zig");
+const Factory = @import("../../Factory.zig");
const Event = @import("../Event.zig");
const EventTarget = @import("../EventTarget.zig");
@@ -57,21 +58,12 @@ fn asEventTarget(self: *Navigation) *EventTarget {
}
pub fn onRemoveFrame(self: *Navigation) void {
- self._proto = undefined;
if (self._on_currententrychange) |cb| cb.release();
self._on_currententrychange = null;
for (self._entries.items) |entry| {
if (entry._on_dispose) |cb| cb.release();
entry._on_dispose = null;
- entry._proto = undefined;
- }
-}
-
-pub fn onNewFrame(self: *Navigation, frame: *Frame) !void {
- self._proto = try frame._factory.standaloneEventTarget(self);
- for (self._entries.items) |entry| {
- entry._proto = try frame._factory.standaloneEventTarget(entry);
}
}
@@ -223,14 +215,17 @@ pub fn pushEntry(
const id_str = try std.fmt.allocPrint(arena, "{d}", .{id});
- const entry = try arena.create(NavigationHistoryEntry);
- entry.* = NavigationHistoryEntry{
- ._proto = try frame._factory.standaloneEventTarget(entry),
- ._id = id_str,
- ._key = id_str,
- ._url = url,
- ._state = state,
- };
+ const entry = try Factory.chainedWithAllocator(arena, .{
+ EventTarget{ ._type = undefined },
+ NavigationHistoryEntry{
+ ._proto = undefined,
+ ._id = id_str,
+ ._key = id_str,
+ ._url = url,
+ ._state = state,
+ },
+ });
+ entry._proto._type = .{ .navigation_history_entry = entry };
// we don't always have a current entry...
const previous = if (self._entries.items.len > 0) self.getCurrentEntry() else null;
@@ -267,14 +262,17 @@ pub fn replaceEntry(
self._next_entry_id += 1;
const id_str = try std.fmt.allocPrint(arena, "{d}", .{id});
- const entry = try arena.create(NavigationHistoryEntry);
- entry.* = NavigationHistoryEntry{
- ._proto = try frame._factory.standaloneEventTarget(entry),
- ._id = id_str,
- ._key = previous._key,
- ._url = url,
- ._state = state,
- };
+ const entry = try Factory.chainedWithAllocator(arena, .{
+ EventTarget{ ._type = undefined },
+ NavigationHistoryEntry{
+ ._proto = undefined,
+ ._id = id_str,
+ ._key = previous._key,
+ ._url = url,
+ ._state = state,
+ },
+ });
+ entry._proto._type = .{ .navigation_history_entry = entry };
const old_entry = self._entries.items[self._index];
self._entries.items[self._index] = entry;
diff --git a/src/browser/webapi/navigation/NavigationHistoryEntry.zig b/src/browser/webapi/navigation/NavigationHistoryEntry.zig
index 841c1c3c1..970004a7d 100644
--- a/src/browser/webapi/navigation/NavigationHistoryEntry.zig
+++ b/src/browser/webapi/navigation/NavigationHistoryEntry.zig
@@ -46,7 +46,7 @@ pub fn id(self: *const NavigationHistoryEntry) []const u8 {
}
pub fn index(self: *const NavigationHistoryEntry, frame: *Frame) i32 {
- const navigation = &frame._session.navigation;
+ const navigation = frame._session.navigation;
for (navigation._entries.items, 0..) |entry, i| {
if (std.mem.eql(u8, entry._id, self._id)) {
diff --git a/src/browser/webapi/net/FormData.zig b/src/browser/webapi/net/FormData.zig
index 6335ba068..ecf5609a8 100644
--- a/src/browser/webapi/net/FormData.zig
+++ b/src/browser/webapi/net/FormData.zig
@@ -21,6 +21,7 @@ const lp = @import("lightpanda");
const js = @import("../../js/js.zig");
const Page = @import("../../Page.zig");
+const Factory = @import("../../Factory.zig");
const Frame = @import("../../Frame.zig");
const Form = @import("../element/html/Form.zig");
const Element = @import("../Element.zig");
@@ -208,17 +209,19 @@ pub fn append(self: *FormData, name: []const u8, value: EntryValue, filename: ?[
// but over bytes we already hold rather than JS parts. Returned at refcount 1:
// the entry owns that reference and deleteByName releases it.
fn fileFrom(source: *Blob, name: []const u8, page: *Page) !*File {
- const blob = try Blob.initFromBytes(source._slice, source._mime, page);
- errdefer blob.deinit(page);
-
- const file = try blob._arena.create(File);
- file.* = .{
- ._proto = blob,
- ._name = try blob._arena.dupe(u8, name),
- ._last_modified = @intCast(lp.datetime.milliTimestamp(.real)),
- };
- blob._type = .{ .file = file };
- blob.acquireRef();
+ const arena = try page.getArena(source._slice.len + source._mime.len + 256, "Blob");
+ errdefer page.releaseArena(arena);
+
+ const file = try Factory.chainedWithAllocator(arena, .{
+ try Blob.buildValueFromBytes(arena, source._slice, source._mime),
+ File{
+ ._proto = undefined,
+ ._name = try arena.dupe(u8, name),
+ ._last_modified = @intCast(lp.datetime.milliTimestamp(.real)),
+ },
+ });
+ file._proto._type = .{ .file = file };
+ file._proto.acquireRef();
return file;
}
@@ -652,14 +655,17 @@ test "FormData: multipart empty body" {
}
fn buildTestFile(arena: Allocator, page: *@import("../../Page.zig"), name: []const u8, mime: []const u8, body: []const u8) !*File {
- const blob = try Blob.initFromBytes(body, mime, page);
- blob.acquireRef();
- const file = try arena.create(File);
- file.* = .{
- ._proto = blob,
- ._name = try arena.dupe(u8, name),
- ._last_modified = 0,
- };
+ const blob_arena = try page.getArena(body.len + mime.len + 256, "Blob");
+ const file = try Factory.chainedWithAllocator(blob_arena, .{
+ try Blob.buildValueFromBytes(blob_arena, body, mime),
+ File{
+ ._proto = undefined,
+ ._name = try arena.dupe(u8, name),
+ ._last_modified = 0,
+ },
+ });
+ file._proto._type = .{ .file = file };
+ file._proto.acquireRef();
return file;
}
diff --git a/src/browser/webapi/storage/idb/IDBCursor.zig b/src/browser/webapi/storage/idb/IDBCursor.zig
index c5559e1fc..b1a62290a 100644
--- a/src/browser/webapi/storage/idb/IDBCursor.zig
+++ b/src/browser/webapi/storage/idb/IDBCursor.zig
@@ -21,6 +21,7 @@ const lp = @import("lightpanda");
const js = @import("../../../js/js.zig");
const Page = @import("../../../Page.zig");
+const Factory = @import("../../../Factory.zig");
const Key = @import("Key.zig");
const Engine = @import("Engine.zig");
@@ -122,8 +123,7 @@ fn _init(store: *IDBObjectStore, txn: *IDBTransaction, index_id: ?i64, source: S
try txn.assertActive();
const request = try txn.newRequest();
- const self = try txn._arena.create(IDBCursor);
- self.* = .{
+ const cursor_value = IDBCursor{
._engine = store._engine,
._store = store,
._txn = txn,
@@ -135,13 +135,23 @@ fn _init(store: *IDBObjectStore, txn: *IDBTransaction, index_id: ?i64, source: S
._js = undefined,
._source = source,
};
- request._cursor = self;
const local = exec.js.local.?;
- const public: js.Value = if (key_only)
- try local.zigValueToJs(self, .{})
- else
- try local.zigValueToJs(try IDBCursorWithValue.init(self), .{});
+ var self: *IDBCursor = undefined;
+ var public: js.Value = undefined;
+ if (key_only) {
+ self = try txn._arena.create(IDBCursor);
+ self.* = cursor_value;
+ public = try local.zigValueToJs(self, .{});
+ } else {
+ const with_value = try Factory.chainedWithAllocator(txn._arena, .{
+ cursor_value,
+ IDBCursorWithValue{ ._proto = undefined },
+ });
+ self = with_value._proto;
+ public = try local.zigValueToJs(with_value, .{});
+ }
+ request._cursor = self;
// Pre-converted and cached because it's the request value on every iteration,
// avoiding the bridge's pointer -> js.Value lookup each time.
diff --git a/src/browser/webapi/storage/idb/IDBCursorWithValue.zig b/src/browser/webapi/storage/idb/IDBCursorWithValue.zig
index 69de483bc..2e91d7cb9 100644
--- a/src/browser/webapi/storage/idb/IDBCursorWithValue.zig
+++ b/src/browser/webapi/storage/idb/IDBCursorWithValue.zig
@@ -28,12 +28,6 @@ pub const Proto = IDBCursor;
_proto: *IDBCursor,
-pub fn init(cursor: *IDBCursor) !*IDBCursorWithValue {
- const self = try cursor._txn._arena.create(IDBCursorWithValue);
- self.* = .{ ._proto = cursor };
- return self;
-}
-
pub fn getValue(self: *const IDBCursorWithValue, exec: *Execution) !?js.Value {
return self._proto.getValueJs(exec);
}
diff --git a/src/cdp/domains/dom.zig b/src/cdp/domains/dom.zig
index 7bf1c3220..101ca6061 100644
--- a/src/cdp/domains/dom.zig
+++ b/src/cdp/domains/dom.zig
@@ -31,6 +31,7 @@ const xpath = @import("../../browser/xpath/Evaluator.zig");
const Input = @import("../../browser/webapi/element/html/Input.zig");
const File = @import("../../browser/webapi/File.zig");
const Blob = @import("../../browser/webapi/Blob.zig");
+const Factory = @import("../../browser/Factory.zig");
const Page = @import("../../browser/Page.zig");
const log = lp.log;
@@ -660,20 +661,21 @@ fn fileFromDiskPath(path: []const u8, page: *Page) !*File {
const stat = try std.Io.Dir.cwd().statFile(lp.io, path, .{});
const basename = std.fs.path.basename(path);
- const blob = try arena.create(Blob);
- const file = try arena.create(File);
- blob.* = .{
- ._rc = .{},
- ._arena = arena,
- ._type = .{ .file = file },
- ._slice = data,
- ._mime = mimeFromExtension(basename),
- };
- file.* = .{
- ._proto = blob,
- ._name = try arena.dupe(u8, basename),
- ._last_modified = stat.mtime.toMilliseconds(),
- };
+ const file = try Factory.chainedWithAllocator(arena, .{
+ Blob{
+ ._rc = .{},
+ ._arena = arena,
+ ._type = undefined,
+ ._slice = data,
+ ._mime = mimeFromExtension(basename),
+ },
+ File{
+ ._proto = undefined,
+ ._name = try arena.dupe(u8, basename),
+ ._last_modified = stat.mtime.toMilliseconds(),
+ },
+ });
+ file._proto._type = .{ .file = file };
return file;
}
diff --git a/src/cdp/domains/page.zig b/src/cdp/domains/page.zig
index aa7b53a08..4a24ea45f 100644
--- a/src/cdp/domains/page.zig
+++ b/src/cdp/domains/page.zig
@@ -363,7 +363,7 @@ fn getNavigationHistory(cmd: *CDP.Command) !void {
return error.SessionIdNotLoaded;
}
- const nav = &bc.session.navigation;
+ const nav = bc.session.navigation;
const entries_in = nav._entries.items;
const entries_out = try cmd.arena.alloc(NavigationEntry, entries_in.len);
@@ -398,7 +398,7 @@ fn navigateToHistoryEntry(cmd: *CDP.Command) !void {
}
const session = bc.session;
- const nav = &session.navigation;
+ const nav = session.navigation;
var target_index: ?usize = null;
var target_url: ?[:0]const u8 = null;