Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: Make Worker a proper DedicatedWorkerGlobalScope

Karl Seguine1a8e036c6c0
diff --git a/src/browser/Factory.zig b/src/browser/Factory.zig
index 248ededab..6f74483ce 100644
--- a/src/browser/Factory.zig
+++ b/src/browser/Factory.zig
@@ -32,6 +32,7 @@ const MouseEvent = @import("webapi/event/MouseEvent.zig");
const Element = @import("webapi/Element.zig");
const Document = @import("webapi/Document.zig");
const EventTarget = @import("webapi/EventTarget.zig");
+const WorkerGlobalScope = @import("webapi/WorkerGlobalScope.zig");
const XMLHttpRequestEventTarget = @import("webapi/net/XMLHttpRequestEventTarget.zig");
const Blob = @import("webapi/Blob.zig");
const AbstractRange = @import("webapi/AbstractRange.zig");
diff --git a/src/browser/Page.zig b/src/browser/Page.zig
index 5b19e01c8..3336e4111 100644
--- a/src/browser/Page.zig
+++ b/src/browser/Page.zig
@@ -336,7 +336,7 @@ fn appendFrameExecutions(frame: *Frame, origin: []const u8, arena: Allocator, li
}
}
for (frame.workers.items) |worker| {
- const wgs = worker._worker_scope;
+ const wgs = worker._worker_scope._proto;
if (wgs.origin) |wo| {
if (std.mem.eql(u8, wo, origin)) {
try list.append(arena, &wgs.js.execution);
diff --git a/src/browser/ScriptManagerBase.zig b/src/browser/ScriptManagerBase.zig
index 225c26fef..07d9e16bb 100644
--- a/src/browser/ScriptManagerBase.zig
+++ b/src/browser/ScriptManagerBase.zig
@@ -53,15 +53,13 @@ pub const Owner = union(enum) {
pub fn frameId(self: Owner) u32 {
return switch (self) {
- .frame => |f| f._frame_id,
- .worker => |w| w._worker._frame_id,
+ inline else => |g| g._frame_id,
};
}
pub fn loaderId(self: Owner) u32 {
return switch (self) {
- .frame => |f| f._loader_id,
- .worker => |w| w._worker._loader_id,
+ inline else => |g| g._loader_id,
};
}
diff --git a/src/browser/js/Env.zig b/src/browser/js/Env.zig
index b50679c42..4ba3d3dd3 100644
--- a/src/browser/js/Env.zig
+++ b/src/browser/js/Env.zig
@@ -31,9 +31,11 @@ const App = @import("../../App.zig");
const Frame = @import("../Frame.zig");
const Window = @import("../webapi/Window.zig");
const WorkerGlobalScope = @import("../webapi/WorkerGlobalScope.zig");
+const DedicatedWorkerGlobalScope = @import("../webapi/DedicatedWorkerGlobalScope.zig");
const v8 = js.v8;
const log = lp.log;
+
const JsApis = bridge.JsApis;
const Allocator = std.mem.Allocator;
const IS_DEBUG = builtin.mode == .Debug;
@@ -287,9 +289,9 @@ fn _createContext(self: *Env, global: anytype, params: ContextParams) !*Context
.prototype_len = @intCast(Window.JsApi.Meta.prototype_chain.len),
.subtype = .node,
} else .{
- .value = @ptrCast(global),
- .prototype_chain = (&WorkerGlobalScope.JsApi.Meta.prototype_chain).ptr,
- .prototype_len = @intCast(WorkerGlobalScope.JsApi.Meta.prototype_chain.len),
+ .value = @ptrCast(global._type.dedicated),
+ .prototype_chain = (&DedicatedWorkerGlobalScope.JsApi.Meta.prototype_chain).ptr,
+ .prototype_len = @intCast(DedicatedWorkerGlobalScope.JsApi.Meta.prototype_chain.len),
.subtype = null,
};
v8.v8__Object__SetAlignedPointerInInternalField(global_obj, 0, tao);
@@ -336,7 +338,7 @@ fn _createContext(self: *Env, global: anytype, params: ContextParams) !*Context
// Register in the identity map. Multiple contexts can be created for the
// same global (via CDP), so we only register the first one.
- const identity_ptr = if (comptime is_frame) @intFromPtr(global.window) else @intFromPtr(global);
+ const identity_ptr = if (comptime is_frame) @intFromPtr(global.window) else @intFromPtr(global._type.dedicated);
const gop = try params.identity.identity_map.getOrPut(params.identity_arena, identity_ptr);
if (gop.found_existing == false) {
var global_global: v8.Global = undefined;
@@ -650,11 +652,30 @@ test "Env: Worker context " {
const worker = try @import("../webapi/Worker.zig").init("http://localhost:9582/src/browser/tests/testing.js", null, frame);
var ls: js.Local.Scope = undefined;
- worker._worker_scope.js.localScope(&ls);
+ worker._worker_scope._proto.js.localScope(&ls);
defer ls.deinit();
try testing.expectEqual(true, (try ls.local.exec("typeof Node === 'undefined'", null)).isTrue());
try testing.expectEqual(true, (try ls.local.exec("typeof WorkerGlobalScope !== 'undefined'", null)).isTrue());
+
+ // A dedicated worker's global is a DedicatedWorkerGlobalScope, which inherits
+ // from WorkerGlobalScope. Both instanceof checks must hold (real sites, e.g.
+ // Shopify's Web Pixel sandbox, use `self instanceof DedicatedWorkerGlobalScope`
+ // to tell a worker apart from an iframe).
+ try testing.expectEqual(true, (try ls.local.exec("typeof DedicatedWorkerGlobalScope !== 'undefined'", null)).isTrue());
+ try testing.expectEqual(true, (try ls.local.exec("self instanceof DedicatedWorkerGlobalScope", null)).isTrue());
+ try testing.expectEqual(true, (try ls.local.exec("self instanceof WorkerGlobalScope", null)).isTrue());
+ try testing.expectEqual(true, (try ls.local.exec("self.constructor.name === 'DedicatedWorkerGlobalScope'", null)).isTrue());
+ try testing.expectEqual(true, (try ls.local.exec("self === globalThis", null)).isTrue());
+
+ // postMessage/close/onmessage live on DedicatedWorkerGlobalScope.prototype
+ // (per spec), not on WorkerGlobalScope.prototype.
+ try testing.expectEqual(true, (try ls.local.exec("DedicatedWorkerGlobalScope.prototype.hasOwnProperty('postMessage')", null)).isTrue());
+ try testing.expectEqual(true, (try ls.local.exec("!WorkerGlobalScope.prototype.hasOwnProperty('postMessage')", null)).isTrue());
+
+ // AnimationFrameProvider mixin is exposed on the dedicated worker global.
+ try testing.expectEqual(true, (try ls.local.exec("typeof self.requestAnimationFrame === 'function'", null)).isTrue());
+ try testing.expectEqual(true, (try ls.local.exec("typeof self.cancelAnimationFrame === 'function'", null)).isTrue());
}
test "Env: Frame context" {
@@ -670,4 +691,5 @@ test "Env: Frame context" {
try testing.expectEqual(true, (try ls.local.exec("typeof Node !== 'undefined'", null)).isTrue());
try testing.expectEqual(true, (try ls.local.exec("typeof WorkerGlobalScope === 'undefined'", null)).isTrue());
+ try testing.expectEqual(true, (try ls.local.exec("typeof DedicatedWorkerGlobalScope === 'undefined'", null)).isTrue());
}
diff --git a/src/browser/js/Snapshot.zig b/src/browser/js/Snapshot.zig
index 1c9eb026f..d0d606bbf 100644
--- a/src/browser/js/Snapshot.zig
+++ b/src/browser/js/Snapshot.zig
@@ -203,8 +203,8 @@ pub fn create() !Snapshot {
}
{
- const WorkerGlobalScope = @import("../webapi/WorkerGlobalScope.zig");
- const index = try createSnapshotContext(.worker, &WorkerJsApis, WorkerGlobalScope.JsApi, isolate, snapshot_creator.?, &templates);
+ const DedicatedWorkerGlobalScope = @import("../webapi/DedicatedWorkerGlobalScope.zig");
+ const index = try createSnapshotContext(.worker, &WorkerJsApis, DedicatedWorkerGlobalScope.JsApi, isolate, snapshot_creator.?, &templates);
std.debug.assert(index == 1);
}
}
diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zig
index 0b31451f2..0afc1c85e 100644
--- a/src/browser/js/bridge.zig
+++ b/src/browser/js/bridge.zig
@@ -1007,6 +1007,7 @@ pub const PageJsApis = flattenTypes(&.{
// This is a subset of PageJsApis plus WorkerGlobalScope.
// TODO: Expand this list to include all worker-appropriate APIs.
pub const WorkerJsApis = flattenTypes(&.{
+ @import("../webapi/DedicatedWorkerGlobalScope.zig"),
@import("../webapi/WorkerGlobalScope.zig"),
@import("../webapi/WorkerLocation.zig"),
@import("../webapi/Navigator.zig"),
@@ -1068,6 +1069,7 @@ pub const WorkerJsApis = flattenTypes(&.{
// subsets (PageJsApis, WorkerSnapshot.JsApis).
pub const JsApis = blk: {
const base = PageJsApis ++ [_]type{
+ @import("../webapi/DedicatedWorkerGlobalScope.zig").JsApi,
@import("../webapi/WorkerGlobalScope.zig").JsApi,
@import("../webapi/WorkerLocation.zig").JsApi,
};
diff --git a/src/browser/webapi/DedicatedWorkerGlobalScope.zig b/src/browser/webapi/DedicatedWorkerGlobalScope.zig
new file mode 100644
index 000000000..479f7c2bc
--- /dev/null
+++ b/src/browser/webapi/DedicatedWorkerGlobalScope.zig
@@ -0,0 +1,256 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// The global object of a dedicated worker. Per the HTML spec this is the most
+// derived interface of a dedicated worker's global, inheriting from
+// WorkerGlobalScope (-> EventTarget). It is the actual JS global object (`self`);
+// the WorkerGlobalScope base holds all of the state and implementation, reached
+// here through `_proto`. Sites branch on `self instanceof DedicatedWorkerGlobalScope`
+// to tell a worker apart from an iframe (e.g. Shopify's Web Pixel sandbox).
+
+const std = @import("std");
+const lp = @import("lightpanda");
+
+const js = @import("../js/js.zig");
+
+const Worker = @import("Worker.zig");
+const WorkerGlobalScope = @import("WorkerGlobalScope.zig");
+
+const MessageEvent = @import("event/MessageEvent.zig");
+
+const Allocator = std.mem.Allocator;
+
+const DedicatedWorkerGlobalScope = @This();
+
+_proto: *WorkerGlobalScope,
+_worker: *Worker,
+_closed: bool = false,
+_on_message: ?js.Function.Global = null,
+_on_messageerror: ?js.Function.Global = null,
+
+// Messages received before the worker script finished evaluating. Per the
+// HTML spec, postMessage'd data is buffered while the worker is loading
+// and delivered once the worker is ready (i.e. once onmessage can be set).
+// Drained by drainPendingMessages, called from Worker.loadInitialScript
+// after the initial script has been evaluated.
+_pending_messages: std.ArrayList(?js.Value.Temp) = .empty,
+
+pub fn init(worker: *Worker, url: [:0]const u8) !*DedicatedWorkerGlobalScope {
+ const self = try worker._arena.create(DedicatedWorkerGlobalScope);
+ const proto = try WorkerGlobalScope.init(
+ worker._arena,
+ url,
+ .{ .dedicated = self },
+ worker._type == .module,
+ worker._frame_id,
+ worker._loader_id,
+ worker._frame,
+ );
+ self.* = .{
+ ._worker = worker,
+ ._proto = proto,
+ };
+ return self;
+}
+
+pub fn deinit(self: *DedicatedWorkerGlobalScope) void {
+ for (self._pending_messages.items) |maybe_data| {
+ if (maybe_data) |d| {
+ d.release();
+ }
+ }
+ self._proto.deinit();
+}
+
+pub fn postMessage(self: *DedicatedWorkerGlobalScope, data: js.Value) !void {
+ try self._worker.receiveMessage(data);
+}
+
+pub fn close(self: *DedicatedWorkerGlobalScope) void {
+ // TOOD: we should also stop new tasks from being scheduled
+ self._proto.js.scheduler.reset();
+ self._closed = true;
+}
+
+pub fn getOnMessage(self: *const DedicatedWorkerGlobalScope) ?js.Function.Global {
+ return self._on_message;
+}
+
+pub fn setOnMessage(self: *DedicatedWorkerGlobalScope, setter: ?WorkerGlobalScope.FunctionSetter) void {
+ self._on_message = WorkerGlobalScope.getFunctionFromSetter(setter);
+}
+
+pub fn getOnMessageError(self: *const DedicatedWorkerGlobalScope) ?js.Function.Global {
+ return self._on_messageerror;
+}
+
+pub fn setOnMessageError(self: *DedicatedWorkerGlobalScope, setter: ?WorkerGlobalScope.FunctionSetter) void {
+ self._on_messageerror = WorkerGlobalScope.getFunctionFromSetter(setter);
+}
+
+pub fn requestAnimationFrame(self: *DedicatedWorkerGlobalScope, cb: js.Function.Temp, exec: *js.Execution) !u32 {
+ return self._proto._timers.schedule(exec, cb, 5, .{
+ .repeat = false,
+ .params = &.{},
+ .mode = .animation_frame,
+ .name = "worker.requestAnimationFrame",
+ });
+}
+
+pub fn cancelAnimationFrame(self: *DedicatedWorkerGlobalScope, id: u32) void {
+ self._proto._timers.clear(id);
+}
+
+// Called internally by Worker when it wants to post a message to us
+pub fn receiveMessage(self: *DedicatedWorkerGlobalScope, data: js.Value) !void {
+ if (self._closed) {
+ return;
+ }
+
+ const cloned_data: ?js.Value.Temp = blk: {
+ // Enter our context to clone the message
+ var ls: js.Local.Scope = undefined;
+ self._proto.js.localScope(&ls);
+ defer ls.deinit();
+
+ // clones from where it currently is (the Worker's Page context) to our Context
+ const cloned = data.structuredCloneTo(&ls.local) catch break :blk null;
+ break :blk cloned.temp() catch break :blk null;
+ };
+
+ if (!self._worker._script_loaded) {
+ // Buffer until Worker.loadInitialScript calls drainPendingMessages.
+ // Without this, postMessage'd data races against the worker's
+ // script load: if onmessage hasn't been registered yet (because
+ // the worker hasn't been evaluated), the dispatched event finds
+ // no listener and the message is silently dropped.
+ try self._pending_messages.append(self._proto.arena, cloned_data);
+ return;
+ }
+
+ try self.scheduleMessage(cloned_data);
+}
+
+fn scheduleMessage(self: *DedicatedWorkerGlobalScope, cloned_data: ?js.Value.Temp) !void {
+ const wgs = self._proto;
+ const session = wgs._session;
+
+ const message_arena = try session.getArena(.tiny, "DedicatedWorkerGlobalScope.receiveMessage");
+ errdefer session.releaseArena(message_arena);
+
+ const callback = try message_arena.create(ReceiveMessageCallback);
+ callback.* = .{
+ .data = cloned_data,
+ .worker_scope = self,
+ .arena = message_arena,
+ };
+
+ try wgs.js.scheduler.add(callback, ReceiveMessageCallback.run, 0, .{
+ .name = "WorkerGlobalScope.receiveMessage",
+ .low_priority = false,
+ .finalizer = ReceiveMessageCallback.cancelled,
+ });
+}
+
+// Called by Worker.loadInitialScript once the initial script has been
+// evaluated and onmessage has had a chance to be registered. Any messages
+// that arrived while the worker was loading are scheduled for delivery in
+// the order they were received.
+pub fn drainPendingMessages(self: *DedicatedWorkerGlobalScope) void {
+ for (self._pending_messages.items) |cloned_data| {
+ self.scheduleMessage(cloned_data) catch |err| {
+ lp.log.warn(.browser, "worker drain msg failed", .{ .err = err });
+ if (cloned_data) |d| d.release();
+ };
+ }
+ self._pending_messages.clearRetainingCapacity();
+}
+
+const ReceiveMessageCallback = struct {
+ data: ?js.Value.Temp,
+ arena: Allocator,
+ worker_scope: *DedicatedWorkerGlobalScope,
+
+ fn cancelled(ctx: *anyopaque) void {
+ const self: *ReceiveMessageCallback = @ptrCast(@alignCast(ctx));
+ if (self.data) |d| {
+ d.release();
+ }
+ self.deinit();
+ }
+
+ fn deinit(self: *ReceiveMessageCallback) void {
+ self.worker_scope._proto._session.releaseArena(self.arena);
+ }
+
+ fn run(ctx: *anyopaque) !?u32 {
+ const self: *ReceiveMessageCallback = @ptrCast(@alignCast(ctx));
+ defer self.deinit();
+
+ const worker_scope = self.worker_scope;
+ const wsg = worker_scope._proto;
+ const target = wsg.asEventTarget();
+
+ // If data is null, structured clone failed - fire messageerror
+ if (self.data == null) {
+ const on_messageerror = worker_scope._on_messageerror;
+ if (!wsg._event_manager.hasDirectListeners(target, "messageerror", on_messageerror)) {
+ return null;
+ }
+ const event = (try MessageEvent.initTrusted(comptime .wrap("messageerror"), .{
+ .bubbles = false,
+ .cancelable = false,
+ }, wsg._page)).asEvent();
+ try wsg.dispatch(target, event, on_messageerror, .{});
+ return null;
+ }
+
+ const on_message = worker_scope._on_message;
+
+ // Check if there are any listeners before creating the event
+ if (!wsg._event_manager.hasDirectListeners(target, "message", on_message)) {
+ self.data.?.release();
+ return null;
+ }
+
+ const event = (try MessageEvent.initTrusted(comptime .wrap("message"), .{
+ .data = .{ .value = self.data.? },
+ .bubbles = false,
+ .cancelable = false,
+ }, wsg._page)).asEvent();
+ try wsg.dispatch(target, event, on_message, .{});
+ return null;
+ }
+};
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(DedicatedWorkerGlobalScope);
+
+ pub const Meta = struct {
+ pub const name = "DedicatedWorkerGlobalScope";
+ pub const prototype_chain = bridge.prototypeChain();
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const postMessage = bridge.function(DedicatedWorkerGlobalScope.postMessage, .{});
+ pub const close = bridge.function(DedicatedWorkerGlobalScope.close, .{});
+ pub const onmessage = bridge.accessor(DedicatedWorkerGlobalScope.getOnMessage, DedicatedWorkerGlobalScope.setOnMessage, .{});
+ pub const onmessageerror = bridge.accessor(DedicatedWorkerGlobalScope.getOnMessageError, DedicatedWorkerGlobalScope.setOnMessageError, .{});
+ pub const requestAnimationFrame = bridge.function(DedicatedWorkerGlobalScope.requestAnimationFrame, .{});
+ pub const cancelAnimationFrame = bridge.function(DedicatedWorkerGlobalScope.cancelAnimationFrame, .{});
+};
diff --git a/src/browser/webapi/Worker.zig b/src/browser/webapi/Worker.zig
index 552597fc8..9b2659ed7 100644
--- a/src/browser/webapi/Worker.zig
+++ b/src/browser/webapi/Worker.zig
@@ -28,7 +28,7 @@ const HttpClient = @import("../HttpClient.zig");
const EventTarget = @import("EventTarget.zig");
const MessageEvent = @import("event/MessageEvent.zig");
const ErrorEvent = @import("event/ErrorEvent.zig");
-const WorkerGlobalScope = @import("WorkerGlobalScope.zig");
+const DedicatedWorkerGlobalScope = @import("DedicatedWorkerGlobalScope.zig");
const log = lp.log;
const Allocator = std.mem.Allocator;
@@ -50,7 +50,7 @@ _loader_id: u32,
_proto: *EventTarget,
_frame: *Frame,
_arena: Allocator,
-_worker_scope: *WorkerGlobalScope,
+_worker_scope: *DedicatedWorkerGlobalScope,
_url: [:0]const u8,
_type: WorkerType = .classic,
@@ -84,8 +84,10 @@ pub fn init(url: []const u8, options: ?WorkerOptions, frame: *Frame) !*Worker {
._frame_id = session.nextFrameId(),
._loader_id = session.nextLoaderId(),
});
- self._worker_scope = try WorkerGlobalScope.init(self, resolved_url);
- errdefer self._worker_scope.deinit();
+ const dedicated_worker = try DedicatedWorkerGlobalScope.init(self, resolved_url);
+ errdefer dedicated_worker.deinit();
+
+ self._worker_scope = dedicated_worker;
try frame.trackWorker(self);
// `--disable-workers` (or `LP.configureLoading { worker: false }`):
@@ -182,7 +184,7 @@ fn httpDoneCallback(ctx: *anyopaque) !void {
}
fn loadInitialScript(self: *Worker, script: []const u8) !void {
- const js_context = self._worker_scope.js;
+ const js_context = self._worker_scope._proto.js;
if (js_context.env.terminatePending()) {
return;
@@ -248,7 +250,7 @@ fn httpErrorCallback(ctx: *anyopaque, err: anyerror) void {
self._http_response = null;
log.err(.browser, "worker fetch error", .{
- .url = self._worker_scope.url,
+ .url = self._url,
.err = err,
});
@@ -306,7 +308,7 @@ pub fn postMessage(self: *Worker, data: js.Value) !void {
try self._worker_scope.receiveMessage(data);
}
-// Called internally by WorkerGlobalScope when it wants to post a message to us
+// Called internally by DedicatedWorkerGlobalScope when it wants to post a message to us
pub fn receiveMessage(self: *Worker, data: js.Value) !void {
const frame = self._frame;
const cloned_data = blk: {
diff --git a/src/browser/webapi/WorkerGlobalScope.zig b/src/browser/webapi/WorkerGlobalScope.zig
index 5a589c992..b860996b4 100644
--- a/src/browser/webapi/WorkerGlobalScope.zig
+++ b/src/browser/webapi/WorkerGlobalScope.zig
@@ -26,6 +26,7 @@ const lp = @import("lightpanda");
const JS = @import("../js/js.zig");
const URL = @import("../URL.zig");
const Page = @import("../Page.zig");
+const Frame = @import("../Frame.zig");
const Factory = @import("../Factory.zig");
const Session = @import("../Session.zig");
const HttpClient = @import("../HttpClient.zig");
@@ -34,7 +35,6 @@ const ScriptManagerBase = @import("../ScriptManagerBase.zig");
const Blob = @import("Blob.zig");
const Event = @import("Event.zig");
-const Worker = @import("Worker.zig");
const Crypto = @import("Crypto.zig");
const Console = @import("Console.zig");
const Navigator = @import("Navigator.zig");
@@ -42,10 +42,10 @@ const Timers = @import("Timers.zig");
const EventTarget = @import("EventTarget.zig");
const Performance = @import("Performance.zig");
const WorkerLocation = @import("WorkerLocation.zig");
-const MessageEvent = @import("event/MessageEvent.zig");
const ErrorEvent = @import("event/ErrorEvent.zig");
const Fetch = @import("net/Fetch.zig");
const CookieStore = @import("storage/CookieStore.zig");
+const DedicatedWorkerGlobalScope = @import("DedicatedWorkerGlobalScope.zig");
const builtin = @import("builtin");
const IS_DEBUG = builtin.mode == .Debug;
@@ -55,6 +55,10 @@ const Allocator = std.mem.Allocator;
const WorkerGlobalScope = @This();
+_type: Type,
+_frame: *Frame,
+_is_module: bool,
+
// Meant to follow the same field naming as Page so that an anytype of generic
// can access these the same for a Page of a WGS.
// These fields represent the "Page"-like component of the WGS
@@ -77,12 +81,7 @@ js: *JS.Context,
// Blob URL registry for URL.createObjectURL/revokeObjectURL.
_blob_urls: std.StringHashMapUnmanaged(*Blob) = .{},
-// Reference back to the Worker object (for postMessage to frame)
-_worker: *Worker,
-
-// HTTP attribution. Mirrors Frame's fields so that generic code over
-// (Frame|WorkerGlobalScope) can read them uniformly. Populated from the
-// owning Worker at init.
+// HTTP attribution
_frame_id: u32,
_loader_id: u32,
@@ -93,12 +92,11 @@ _event_manager: EventManagerBase,
// workers don't have <script> tags.
_script_manager: ScriptManagerBase,
-// List of open BroadcastChannels, used to route postMessage between same-named
+// List of open BroadcastChannels, used to route HTTP attribution. Mirrors Frame's fiage between same-named
// channels in this worker's origin
_broadcast_channels: std.DoublyLinkedList = .{},
// These fields represent the "Window"-like component of the WGS
-_closed: bool = false,
_proto: *EventTarget,
_console: Console = .init,
_crypto: Crypto = .init,
@@ -107,50 +105,52 @@ _performance: Performance,
_on_error: ?JS.Function.Global = null,
_on_rejection_handled: ?JS.Function.Global = null,
_on_unhandled_rejection: ?JS.Function.Global = null,
-_on_message: ?JS.Function.Global = null,
-_on_messageerror: ?JS.Function.Global = null,
_cookie_store: ?*CookieStore = null,
_location: WorkerLocation,
_timers: Timers = .{},
-// Messages received before the worker script finished evaluating. Per the
-// HTML spec, postMessage'd data is buffered while the worker is loading
-// and delivered once the worker is ready (i.e. once onmessage can be set).
-// Drained by drainPendingMessages, called from Worker.loadInitialScript
-// after the initial script has been evaluated.
-_pending_messages: std.ArrayList(?JS.Value.Temp) = .empty,
+pub const Type = union(enum) {
+ dedicated: *DedicatedWorkerGlobalScope,
+};
-pub fn init(worker: *Worker, url: [:0]const u8) !*WorkerGlobalScope {
- const arena = worker._arena;
- const parent = worker._frame;
- const session = worker._frame._session;
+pub fn init(
+ arena: Allocator,
+ url: [:0]const u8,
+ child: Type,
+ is_module: bool,
+ frame_id: u32,
+ loader_id: u32,
+ frame: *Frame,
+) !*WorkerGlobalScope {
+ const session = frame._session;
const call_arena = try session.getArena(.small, "WorkerGlobalScope.call_arena");
errdefer session.releaseArena(call_arena);
- const factory = parent._factory;
+ const factory = frame._factory;
const self = try factory.eventTargetWithAllocator(arena, WorkerGlobalScope{
.url = url,
.arena = arena,
- .origin = parent.origin,
+ .origin = frame.origin,
.js = undefined,
.call_arena = call_arena,
+ ._frame = frame,
+ ._page = frame._page,
._session = session,
- ._page = parent._page,
._identity = .{},
+ ._type = child,
._proto = undefined,
._factory = factory,
- ._worker = worker,
- ._frame_id = worker._frame_id,
- ._loader_id = worker._loader_id,
+ ._is_module = is_module,
+ ._frame_id = frame_id,
+ ._loader_id = loader_id,
._event_manager = .init(arena),
._script_manager = undefined,
._location = .{ ._url = url },
._performance = .init(),
});
- errdefer factory.destroy(self);
self._http_owner.blob_urls = &self._blob_urls;
@@ -182,14 +182,6 @@ pub fn deinit(self: *WorkerGlobalScope) void {
browser.http_client.abortOwner(&self._http_owner);
- // Release any messages that were buffered while waiting for the
- // worker script to load but never got drained (e.g. worker script
- // failed to fetch). Backing array lives on self.arena so the storage
- // itself is freed with the arena.
- for (self._pending_messages.items) |maybe_data| {
- if (maybe_data) |d| d.release();
- }
-
self._identity.deinit();
self._script_manager.deinit();
@@ -235,7 +227,7 @@ pub fn hasDirectListeners(self: *WorkerGlobalScope, target: *EventTarget, typ: [
// Workers don't have their own Referer; per spec, dedicated worker requests
// use the parent document's URL. Delegate to the owning frame.
pub fn headersForRequest(self: *WorkerGlobalScope, headers: *HttpClient.Headers) !void {
- return self._worker._frame.headersForRequest(headers);
+ return self._frame.headersForRequest(headers);
}
pub fn isSameOrigin(self: *const WorkerGlobalScope, url: [:0]const u8) bool {
@@ -255,6 +247,10 @@ pub fn getSelf(self: *WorkerGlobalScope) *WorkerGlobalScope {
return self;
}
+pub fn setSelf(_: *WorkerGlobalScope, value: JS.Value) void {
+ replaceGlobalProperty(value, "self");
+}
+
pub fn getConsole(self: *WorkerGlobalScope) *Console {
return &self._console;
}
@@ -263,10 +259,6 @@ pub fn setConsole(_: *WorkerGlobalScope, value: JS.Value) void {
replaceGlobalProperty(value, "console");
}
-pub fn setSelf(_: *WorkerGlobalScope, value: JS.Value) void {
- replaceGlobalProperty(value, "self");
-}
-
pub fn getCrypto(self: *WorkerGlobalScope) *Crypto {
return &self._crypto;
}
@@ -314,92 +306,6 @@ pub fn setOnUnhandledRejection(self: *WorkerGlobalScope, setter: ?FunctionSetter
self._on_unhandled_rejection = getFunctionFromSetter(setter);
}
-pub fn getOnMessage(self: *const WorkerGlobalScope) ?JS.Function.Global {
- return self._on_message;
-}
-
-pub fn setOnMessage(self: *WorkerGlobalScope, setter: ?FunctionSetter) void {
- self._on_message = getFunctionFromSetter(setter);
-}
-
-pub fn getOnMessageError(self: *const WorkerGlobalScope) ?JS.Function.Global {
- return self._on_messageerror;
-}
-
-pub fn setOnMessageError(self: *WorkerGlobalScope, setter: ?FunctionSetter) void {
- self._on_messageerror = getFunctionFromSetter(setter);
-}
-
-// Posts a message from the worker back to the frame.
-// The message is cloned via structured clone and dispatched on the Worker object.
-pub fn postMessage(self: *WorkerGlobalScope, data: JS.Value) !void {
- try self._worker.receiveMessage(data);
-}
-
-// Called internally by Worker when it wants to post a message to us
-pub fn receiveMessage(self: *WorkerGlobalScope, data: JS.Value) !void {
- if (self._closed) {
- return;
- }
-
- const cloned_data: ?JS.Value.Temp = blk: {
- // Enter our context to clone the message
- var ls: JS.Local.Scope = undefined;
- self.js.localScope(&ls);
- defer ls.deinit();
-
- // clones from where it currently is (the Worker's Page context) to our Context
- const cloned = data.structuredCloneTo(&ls.local) catch break :blk null;
- break :blk cloned.temp() catch break :blk null;
- };
-
- if (!self._worker._script_loaded) {
- // Buffer until Worker.loadInitialScript calls drainPendingMessages.
- // Without this, postMessage'd data races against the worker's
- // script load: if onmessage hasn't been registered yet (because
- // the worker hasn't been evaluated), the dispatched event finds
- // no listener and the message is silently dropped.
- try self._pending_messages.append(self.arena, cloned_data);
- return;
- }
-
- try self.scheduleMessage(cloned_data);
-}
-
-fn scheduleMessage(self: *WorkerGlobalScope, cloned_data: ?JS.Value.Temp) !void {
- const session = self._session;
-
- const message_arena = try session.getArena(.tiny, "WorkerGlobalScope.receiveMessage");
- errdefer session.releaseArena(message_arena);
-
- const callback = try message_arena.create(ReceiveMessageCallback);
- callback.* = .{
- .data = cloned_data,
- .worker_scope = self,
- .arena = message_arena,
- };
-
- try self.js.scheduler.add(callback, ReceiveMessageCallback.run, 0, .{
- .name = "WorkerGlobalScope.receiveMessage",
- .low_priority = false,
- .finalizer = ReceiveMessageCallback.cancelled,
- });
-}
-
-// Called by Worker.loadInitialScript once the initial script has been
-// evaluated and onmessage has had a chance to be registered. Any messages
-// that arrived while the worker was loading are scheduled for delivery in
-// the order they were received.
-pub fn drainPendingMessages(self: *WorkerGlobalScope) void {
- for (self._pending_messages.items) |cloned_data| {
- self.scheduleMessage(cloned_data) catch |err| {
- log.warn(.browser, "worker drain msg failed", .{ .err = err });
- if (cloned_data) |d| d.release();
- };
- }
- self._pending_messages.clearRetainingCapacity();
-}
-
const base64 = @import("encoding/base64.zig");
pub fn btoa(_: *const WorkerGlobalScope, input: base64.BinInput, exec: *JS.Execution) ![]const u8 {
return base64.encode(exec.call_arena, input);
@@ -440,14 +346,8 @@ pub fn unhandledPromiseRejection(self: *WorkerGlobalScope, no_handler: bool, rej
}
}
-pub fn close(self: *WorkerGlobalScope) void {
- // TOOD: we should also stop new tasks from being scheduled
- self.js.scheduler.reset();
- self._closed = true;
-}
-
pub fn importScripts(self: *WorkerGlobalScope, urls: []const [:0]const u8) !void {
- if (self._worker._type == .module) {
+ if (self._is_module) {
// not allowed to be called when the worker type is module (scripts should
// use actual imports).
return error.TypeError;
@@ -596,20 +496,20 @@ pub fn clearInterval(self: *WorkerGlobalScope, id: u32) void {
self._timers.clear(id);
}
-// `console` and `self` are [Replaceable] assignment redefines them as own data
+// `console` and `self` are [Replaceable]: assignment redefines them as own data
// properties on the global rather than throwing through the getter-only accessor
-// in strict mode.
-fn replaceGlobalProperty(value: JS.Value, comptime name: []const u8) void {
+// in strict mode. Used here (console) and by DedicatedWorkerGlobalScope (self).
+pub fn replaceGlobalProperty(value: JS.Value, comptime name: []const u8) void {
const global = value.local.getGlobal();
_ = global.defineOwnProperty(name, value, 0);
}
-const FunctionSetter = union(enum) {
+pub const FunctionSetter = union(enum) {
func: JS.Function.Global,
anything: JS.Value,
};
-fn getFunctionFromSetter(setter_: ?FunctionSetter) ?JS.Function.Global {
+pub fn getFunctionFromSetter(setter_: ?FunctionSetter) ?JS.Function.Global {
const setter = setter_ orelse return null;
return switch (setter) {
.func => |func| func,
@@ -617,60 +517,6 @@ fn getFunctionFromSetter(setter_: ?FunctionSetter) ?JS.Function.Global {
};
}
-const ReceiveMessageCallback = struct {
- data: ?JS.Value.Temp,
- arena: Allocator,
- worker_scope: *WorkerGlobalScope,
-
- fn cancelled(ctx: *anyopaque) void {
- const self: *ReceiveMessageCallback = @ptrCast(@alignCast(ctx));
- if (self.data) |d| d.release();
- self.deinit();
- }
-
- fn deinit(self: *ReceiveMessageCallback) void {
- self.worker_scope._session.releaseArena(self.arena);
- }
-
- fn run(ctx: *anyopaque) !?u32 {
- const self: *ReceiveMessageCallback = @ptrCast(@alignCast(ctx));
- defer self.deinit();
-
- const worker_scope = self.worker_scope;
- const target = worker_scope.asEventTarget();
-
- // If data is null, structured clone failed - fire messageerror
- if (self.data == null) {
- const on_messageerror = worker_scope._on_messageerror;
- if (!worker_scope._event_manager.hasDirectListeners(target, "messageerror", on_messageerror)) {
- return null;
- }
- const event = (try MessageEvent.initTrusted(comptime .wrap("messageerror"), .{
- .bubbles = false,
- .cancelable = false,
- }, worker_scope._page)).asEvent();
- try worker_scope.dispatch(target, event, on_messageerror, .{});
- return null;
- }
-
- const on_message = worker_scope._on_message;
-
- // Check if there are any listeners before creating the event
- if (!worker_scope._event_manager.hasDirectListeners(target, "message", on_message)) {
- self.data.?.release();
- return null;
- }
-
- const event = (try MessageEvent.initTrusted(comptime .wrap("message"), .{
- .data = .{ .value = self.data.? },
- .bubbles = false,
- .cancelable = false,
- }, worker_scope._page)).asEvent();
- try worker_scope.dispatch(target, event, on_message, .{});
- return null;
- }
-};
-
pub const JsApi = struct {
pub const bridge = JS.Bridge(WorkerGlobalScope);
@@ -680,7 +526,6 @@ pub const JsApi = struct {
pub var class_id: bridge.ClassId = undefined;
};
- pub const self = bridge.accessor(WorkerGlobalScope.getSelf, WorkerGlobalScope.setSelf, .{});
pub const console = bridge.accessor(WorkerGlobalScope.getConsole, WorkerGlobalScope.setConsole, .{});
pub const crypto = bridge.accessor(WorkerGlobalScope.getCrypto, null, .{});
pub const navigator = bridge.accessor(WorkerGlobalScope.getNavigator, null, .{});
@@ -693,6 +538,7 @@ pub const JsApi = struct {
return wgs.performance();
}
}.wrap, null, .{});
+ pub const self = bridge.accessor(WorkerGlobalScope.getSelf, WorkerGlobalScope.setSelf, .{});
pub const location = bridge.accessor(WorkerGlobalScope.getLocation, null, .{});
pub const cookieStore = bridge.accessor(WorkerGlobalScope.getCookieStore, null, .{});
@@ -703,9 +549,7 @@ pub const JsApi = struct {
pub const btoa = bridge.function(WorkerGlobalScope.btoa, .{ .dom_exception = true });
pub const atob = bridge.function(WorkerGlobalScope.atob, .{ .dom_exception = true });
pub const structuredClone = bridge.function(WorkerGlobalScope.structuredClone, .{});
- pub const postMessage = bridge.function(WorkerGlobalScope.postMessage, .{});
pub const reportError = bridge.function(WorkerGlobalScope.reportError, .{});
- pub const close = bridge.function(WorkerGlobalScope.close, .{});
pub const fetch = bridge.function(WorkerGlobalScope.fetch, .{});
pub const importScripts = bridge.function(WorkerGlobalScope.importScripts, .{ .dom_exception = true });
pub const queueMicrotask = bridge.function(WorkerGlobalScope.queueMicrotask, .{});
@@ -714,9 +558,6 @@ pub const JsApi = struct {
pub const setInterval = bridge.function(WorkerGlobalScope.setInterval, .{});
pub const clearInterval = bridge.function(WorkerGlobalScope.clearInterval, .{});
- pub const onmessage = bridge.accessor(WorkerGlobalScope.getOnMessage, WorkerGlobalScope.setOnMessage, .{});
- pub const onmessageerror = bridge.accessor(WorkerGlobalScope.getOnMessageError, WorkerGlobalScope.setOnMessageError, .{});
-
// Return false since workers don't have secure-context-only APIs
pub const isSecureContext = bridge.property(false, .{ .template = false });
};