mirror of
https://github.com/lightpanda-io/browser.git
synced 2026-03-30 17:18:57 +00:00
Compare commits
49 Commits
remove_cdp
...
http-cache
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6d9f83a76b | ||
|
|
ae72d1d288 | ||
|
|
ad350d05da | ||
|
|
7aa21aa200 | ||
|
|
39c09b7b5f | ||
|
|
621ea49cb6 | ||
|
|
28e5b9b46e | ||
|
|
8fa8190f09 | ||
|
|
e3eaf4042a | ||
|
|
87b771f4b0 | ||
|
|
fa01f36f96 | ||
|
|
d9d04bb17f | ||
|
|
f7e254c9ee | ||
|
|
86c75a1617 | ||
|
|
e2df3b39e5 | ||
|
|
649b9bc76f | ||
|
|
b13b08055f | ||
|
|
800c4ecda9 | ||
|
|
6cea8e18f7 | ||
|
|
b5bf608f37 | ||
|
|
a12ae507c9 | ||
|
|
2bad6c590b | ||
|
|
9438ccf948 | ||
|
|
0c96645a3f | ||
|
|
d517005aaf | ||
|
|
269fa49696 | ||
|
|
d13fdcb2a7 | ||
|
|
cafa16d190 | ||
|
|
a5ed3cdaee | ||
|
|
b473f0e681 | ||
|
|
be7226fc7b | ||
|
|
5cd356631c | ||
|
|
8723ecdd2d | ||
|
|
451178558a | ||
|
|
70dc0f6b95 | ||
|
|
d99599fa21 | ||
|
|
20e62a5551 | ||
|
|
e083d4a3d1 | ||
|
|
7a23686cbd | ||
|
|
25889ff918 | ||
|
|
b4e3f246ca | ||
|
|
f60e5cce6d | ||
|
|
81d4bdb157 | ||
|
|
cf5e4d7d1e | ||
|
|
9f81d7d3ff | ||
|
|
269924090a | ||
|
|
ad54437ca3 | ||
|
|
01ecb296e5 | ||
|
|
1f22462f13 |
@@ -36,8 +36,8 @@ Lightpanda is the open-source browser made for headless usage:
|
|||||||
|
|
||||||
Fast web automation for AI agents, LLM training, scraping and testing:
|
Fast web automation for AI agents, LLM training, scraping and testing:
|
||||||
|
|
||||||
- Ultra-low memory footprint (9x less than Chrome)
|
- Ultra-low memory footprint (16x less than Chrome)
|
||||||
- Exceptionally fast execution (11x faster than Chrome)
|
- Exceptionally fast execution (9x faster than Chrome)
|
||||||
- Instant startup
|
- Instant startup
|
||||||
|
|
||||||
[^1]: **Playwright support disclaimer:**
|
[^1]: **Playwright support disclaimer:**
|
||||||
|
|||||||
11
SECURITY.md
Normal file
11
SECURITY.md
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
# Reporting security issues
|
||||||
|
|
||||||
|
## Supported Versions
|
||||||
|
|
||||||
|
Security fixes are applied to the latest `main` branch.
|
||||||
|
|
||||||
|
## Reporting a Vulnerability
|
||||||
|
|
||||||
|
Please **DO NOT** file a public issue, instead send your report privately to security@lightpanda.io.
|
||||||
|
|
||||||
|
Security reports are greatly appreciated and we will publicly thank you for it, although we keep your name confidential if you request it.
|
||||||
@@ -55,7 +55,7 @@ pub fn init(allocator: Allocator, config: *const Config) !*App {
|
|||||||
.arena_pool = undefined,
|
.arena_pool = undefined,
|
||||||
};
|
};
|
||||||
|
|
||||||
app.network = try Network.init(allocator, config);
|
app.network = try Network.init(allocator, app, config);
|
||||||
errdefer app.network.deinit();
|
errdefer app.network.deinit();
|
||||||
|
|
||||||
app.platform = try Platform.init();
|
app.platform = try Platform.init();
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ const log = @import("log.zig");
|
|||||||
const dump = @import("browser/dump.zig");
|
const dump = @import("browser/dump.zig");
|
||||||
|
|
||||||
const WebBotAuthConfig = @import("network/WebBotAuth.zig").Config;
|
const WebBotAuthConfig = @import("network/WebBotAuth.zig").Config;
|
||||||
|
const mcp = @import("mcp.zig");
|
||||||
|
|
||||||
pub const RunMode = enum {
|
pub const RunMode = enum {
|
||||||
help,
|
help,
|
||||||
@@ -156,6 +157,13 @@ pub fn userAgentSuffix(self: *const Config) ?[]const u8 {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn cacheDir(self: *const Config) ?[]const u8 {
|
||||||
|
return switch (self.mode) {
|
||||||
|
inline .serve, .fetch, .mcp => |opts| opts.common.cache_dir,
|
||||||
|
else => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
pub fn cdpTimeout(self: *const Config) usize {
|
pub fn cdpTimeout(self: *const Config) usize {
|
||||||
return switch (self.mode) {
|
return switch (self.mode) {
|
||||||
.serve => |opts| if (opts.timeout > 604_800) 604_800_000 else @as(usize, opts.timeout) * 1000,
|
.serve => |opts| if (opts.timeout > 604_800) 604_800_000 else @as(usize, opts.timeout) * 1000,
|
||||||
@@ -222,6 +230,7 @@ pub const Serve = struct {
|
|||||||
|
|
||||||
pub const Mcp = struct {
|
pub const Mcp = struct {
|
||||||
common: Common = .{},
|
common: Common = .{},
|
||||||
|
version: mcp.Version = .default,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const DumpFormat = enum {
|
pub const DumpFormat = enum {
|
||||||
@@ -264,6 +273,7 @@ pub const Common = struct {
|
|||||||
log_format: ?log.Format = null,
|
log_format: ?log.Format = null,
|
||||||
log_filter_scopes: ?[]log.Scope = null,
|
log_filter_scopes: ?[]log.Scope = null,
|
||||||
user_agent_suffix: ?[]const u8 = null,
|
user_agent_suffix: ?[]const u8 = null,
|
||||||
|
cache_dir: ?[]const u8 = null,
|
||||||
|
|
||||||
web_bot_auth_key_file: ?[]const u8 = null,
|
web_bot_auth_key_file: ?[]const u8 = null,
|
||||||
web_bot_auth_keyid: ?[]const u8 = null,
|
web_bot_auth_keyid: ?[]const u8 = null,
|
||||||
@@ -453,6 +463,12 @@ pub fn printUsageAndExit(self: *const Config, success: bool) void {
|
|||||||
\\Starts an MCP (Model Context Protocol) server over stdio
|
\\Starts an MCP (Model Context Protocol) server over stdio
|
||||||
\\Example: {s} mcp
|
\\Example: {s} mcp
|
||||||
\\
|
\\
|
||||||
|
\\Options:
|
||||||
|
\\--version
|
||||||
|
\\ Override the reported MCP version.
|
||||||
|
\\ Valid: 2024-11-05, 2025-03-26, 2025-06-18, 2025-11-25.
|
||||||
|
\\ Defaults to "2024-11-05".
|
||||||
|
\\
|
||||||
++ common_options ++
|
++ common_options ++
|
||||||
\\
|
\\
|
||||||
\\version command
|
\\version command
|
||||||
@@ -640,10 +656,22 @@ fn parseMcpArgs(
|
|||||||
allocator: Allocator,
|
allocator: Allocator,
|
||||||
args: *std.process.ArgIterator,
|
args: *std.process.ArgIterator,
|
||||||
) !Mcp {
|
) !Mcp {
|
||||||
var mcp: Mcp = .{};
|
var result: Mcp = .{};
|
||||||
|
|
||||||
while (args.next()) |opt| {
|
while (args.next()) |opt| {
|
||||||
if (try parseCommonArg(allocator, opt, args, &mcp.common)) {
|
if (std.mem.eql(u8, "--version", opt)) {
|
||||||
|
const str = args.next() orelse {
|
||||||
|
log.fatal(.mcp, "missing argument value", .{ .arg = opt });
|
||||||
|
return error.InvalidArgument;
|
||||||
|
};
|
||||||
|
result.version = std.meta.stringToEnum(mcp.Version, str) orelse {
|
||||||
|
log.fatal(.mcp, "invalid protocol version", .{ .value = str });
|
||||||
|
return error.InvalidArgument;
|
||||||
|
};
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (try parseCommonArg(allocator, opt, args, &result.common)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -651,7 +679,7 @@ fn parseMcpArgs(
|
|||||||
return error.UnkownOption;
|
return error.UnkownOption;
|
||||||
}
|
}
|
||||||
|
|
||||||
return mcp;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parseFetchArgs(
|
fn parseFetchArgs(
|
||||||
@@ -980,5 +1008,14 @@ fn parseCommonArg(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (std.mem.eql(u8, "--cache_dir", opt)) {
|
||||||
|
const str = args.next() orelse {
|
||||||
|
log.fatal(.app, "missing argument value", .{ .arg = "--cache_dir" });
|
||||||
|
return error.InvalidArgument;
|
||||||
|
};
|
||||||
|
common.cache_dir = try allocator.dupe(u8, str);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ pub fn dispatch(self: *EventManager, target: *EventTarget, event: *Event) Dispat
|
|||||||
|
|
||||||
pub fn dispatchOpts(self: *EventManager, target: *EventTarget, event: *Event, comptime opts: DispatchOpts) DispatchError!void {
|
pub fn dispatchOpts(self: *EventManager, target: *EventTarget, event: *Event, comptime opts: DispatchOpts) DispatchError!void {
|
||||||
event.acquireRef();
|
event.acquireRef();
|
||||||
defer event.deinit(false, self.page._session);
|
defer _ = event.releaseRef(self.page._session);
|
||||||
|
|
||||||
if (comptime IS_DEBUG) {
|
if (comptime IS_DEBUG) {
|
||||||
log.debug(.event, "eventManager.dispatch", .{ .type = event._type_string.str(), .bubbles = event._bubbles });
|
log.debug(.event, "eventManager.dispatch", .{ .type = event._type_string.str(), .bubbles = event._bubbles });
|
||||||
@@ -240,7 +240,7 @@ pub fn dispatchDirect(self: *EventManager, target: *EventTarget, event: *Event,
|
|||||||
defer window._current_event = prev_event;
|
defer window._current_event = prev_event;
|
||||||
|
|
||||||
event.acquireRef();
|
event.acquireRef();
|
||||||
defer event.deinit(false, page._session);
|
defer _ = event.releaseRef(page._session);
|
||||||
|
|
||||||
if (comptime IS_DEBUG) {
|
if (comptime IS_DEBUG) {
|
||||||
log.debug(.event, "dispatchDirect", .{ .type = event._type_string, .context = opts.context });
|
log.debug(.event, "dispatchDirect", .{ .type = event._type_string, .context = opts.context });
|
||||||
|
|||||||
@@ -239,7 +239,7 @@ fn eventInit(arena: Allocator, typ: String, value: anytype) !Event {
|
|||||||
const time_stamp = (raw_timestamp / 2) * 2;
|
const time_stamp = (raw_timestamp / 2) * 2;
|
||||||
|
|
||||||
return .{
|
return .{
|
||||||
._rc = 0,
|
._rc = .{},
|
||||||
._arena = arena,
|
._arena = arena,
|
||||||
._type = unionInit(Event.Type, value),
|
._type = unionInit(Event.Type, value),
|
||||||
._type_string = typ,
|
._type_string = typ,
|
||||||
@@ -255,6 +255,7 @@ pub fn blob(_: *const Factory, arena: Allocator, child: anytype) !*@TypeOf(child
|
|||||||
|
|
||||||
const blob_ptr = chain.get(0);
|
const blob_ptr = chain.get(0);
|
||||||
blob_ptr.* = .{
|
blob_ptr.* = .{
|
||||||
|
._rc = .{},
|
||||||
._arena = arena,
|
._arena = arena,
|
||||||
._type = unionInit(Blob.Type, chain.get(1)),
|
._type = unionInit(Blob.Type, chain.get(1)),
|
||||||
._slice = "",
|
._slice = "",
|
||||||
@@ -271,7 +272,7 @@ pub fn abstractRange(_: *const Factory, arena: Allocator, child: anytype, page:
|
|||||||
const doc = page.document.asNode();
|
const doc = page.document.asNode();
|
||||||
const abstract_range = chain.get(0);
|
const abstract_range = chain.get(0);
|
||||||
abstract_range.* = AbstractRange{
|
abstract_range.* = AbstractRange{
|
||||||
._rc = 0,
|
._rc = .{},
|
||||||
._arena = arena,
|
._arena = arena,
|
||||||
._page_id = page.id,
|
._page_id = page.id,
|
||||||
._type = unionInit(AbstractRange.Type, chain.get(1)),
|
._type = unionInit(AbstractRange.Type, chain.get(1)),
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ const CookieJar = @import("webapi/storage/Cookie.zig").Jar;
|
|||||||
const http = @import("../network/http.zig");
|
const http = @import("../network/http.zig");
|
||||||
const Runtime = @import("../network/Runtime.zig");
|
const Runtime = @import("../network/Runtime.zig");
|
||||||
const Robots = @import("../network/Robots.zig");
|
const Robots = @import("../network/Robots.zig");
|
||||||
|
const Cache = @import("../network/cache/Cache.zig");
|
||||||
|
const CacheMetadata = Cache.CachedMetadata;
|
||||||
|
const CachedResponse = Cache.CachedResponse;
|
||||||
|
|
||||||
const IS_DEBUG = builtin.mode == .Debug;
|
const IS_DEBUG = builtin.mode == .Debug;
|
||||||
|
|
||||||
@@ -311,7 +314,69 @@ pub fn request(self: *Client, req: Request) !void {
|
|||||||
return self.fetchRobotsThenProcessRequest(robots_url, req);
|
return self.fetchRobotsThenProcessRequest(robots_url, req);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn serveFromCache(req: Request, cached: *const CachedResponse) !void {
|
||||||
|
const response = Response.fromCached(req.ctx, cached);
|
||||||
|
|
||||||
|
if (req.start_callback) |cb| {
|
||||||
|
try cb(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
const proceed = try req.header_callback(response);
|
||||||
|
if (!proceed) {
|
||||||
|
switch (cached.data) {
|
||||||
|
.buffer => |_| {},
|
||||||
|
.file => |file| file.close(),
|
||||||
|
}
|
||||||
|
req.error_callback(req.ctx, error.Abort);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (cached.data) {
|
||||||
|
.buffer => |data| {
|
||||||
|
if (data.len > 0) {
|
||||||
|
try req.data_callback(response, data);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
.file => |file| {
|
||||||
|
defer file.close();
|
||||||
|
var buf: [1024]u8 = undefined;
|
||||||
|
var file_reader = file.reader(&buf);
|
||||||
|
|
||||||
|
const reader = &file_reader.interface;
|
||||||
|
var read_buf: [1024]u8 = undefined;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const curr = try reader.readSliceShort(&read_buf);
|
||||||
|
if (curr == 0) break;
|
||||||
|
try req.data_callback(response, read_buf[0..curr]);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try req.done_callback(req.ctx);
|
||||||
|
}
|
||||||
|
|
||||||
fn processRequest(self: *Client, req: Request) !void {
|
fn processRequest(self: *Client, req: Request) !void {
|
||||||
|
if (self.network.cache) |*cache| {
|
||||||
|
if (req.method == .GET) {
|
||||||
|
const arena = try self.network.app.arena_pool.acquire(.{ .debug = "HttpClient.processRequest.cache" });
|
||||||
|
defer self.network.app.arena_pool.release(arena);
|
||||||
|
|
||||||
|
if (cache.get(arena, .{ .url = req.url, .timestamp = std.time.timestamp() })) |cached| {
|
||||||
|
log.debug(.browser, "http.cache.get", .{
|
||||||
|
.url = req.url,
|
||||||
|
.found = true,
|
||||||
|
.metadata = cached.metadata,
|
||||||
|
});
|
||||||
|
|
||||||
|
defer req.headers.deinit();
|
||||||
|
return serveFromCache(req, &cached);
|
||||||
|
} else {
|
||||||
|
log.debug(.browser, "http.cache.get", .{ .url = req.url, .found = false });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const transfer = try self.makeTransfer(req);
|
const transfer = try self.makeTransfer(req);
|
||||||
|
|
||||||
transfer.req.notification.dispatch(.http_request_start, &.{ .transfer = transfer });
|
transfer.req.notification.dispatch(.http_request_start, &.{ .transfer = transfer });
|
||||||
@@ -399,8 +464,10 @@ fn fetchRobotsThenProcessRequest(self: *Client, robots_url: [:0]const u8, req: R
|
|||||||
try entry.value_ptr.append(self.allocator, req);
|
try entry.value_ptr.append(self.allocator, req);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn robotsHeaderCallback(transfer: *Transfer) !bool {
|
fn robotsHeaderCallback(response: Response) !bool {
|
||||||
const ctx: *RobotsRequestContext = @ptrCast(@alignCast(transfer.ctx));
|
const ctx: *RobotsRequestContext = @ptrCast(@alignCast(response.ctx));
|
||||||
|
// Robots callbacks only happen on real live requests.
|
||||||
|
const transfer = response.inner.transfer;
|
||||||
|
|
||||||
if (transfer.response_header) |hdr| {
|
if (transfer.response_header) |hdr| {
|
||||||
log.debug(.browser, "robots status", .{ .status = hdr.status, .robots_url = ctx.robots_url });
|
log.debug(.browser, "robots status", .{ .status = hdr.status, .robots_url = ctx.robots_url });
|
||||||
@@ -414,8 +481,8 @@ fn robotsHeaderCallback(transfer: *Transfer) !bool {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn robotsDataCallback(transfer: *Transfer, data: []const u8) !void {
|
fn robotsDataCallback(response: Response, data: []const u8) !void {
|
||||||
const ctx: *RobotsRequestContext = @ptrCast(@alignCast(transfer.ctx));
|
const ctx: *RobotsRequestContext = @ptrCast(@alignCast(response.ctx));
|
||||||
try ctx.buffer.appendSlice(ctx.client.allocator, data);
|
try ctx.buffer.appendSlice(ctx.client.allocator, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -634,13 +701,43 @@ fn makeTransfer(self: *Client, req: Request) !*Transfer {
|
|||||||
.id = id,
|
.id = id,
|
||||||
.url = req.url,
|
.url = req.url,
|
||||||
.req = req,
|
.req = req,
|
||||||
.ctx = req.ctx,
|
|
||||||
.client = self,
|
.client = self,
|
||||||
.max_response_size = self.network.config.httpMaxResponseSize(),
|
.max_response_size = self.network.config.httpMaxResponseSize(),
|
||||||
};
|
};
|
||||||
return transfer;
|
return transfer;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn requestFailed(transfer: *Transfer, err: anyerror, comptime execute_callback: bool) void {
|
||||||
|
if (transfer._notified_fail) {
|
||||||
|
// we can force a failed request within a callback, which will eventually
|
||||||
|
// result in this being called again in the more general loop. We do this
|
||||||
|
// because we can raise a more specific error inside a callback in some cases
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
transfer._notified_fail = true;
|
||||||
|
|
||||||
|
transfer.req.notification.dispatch(.http_request_fail, &.{
|
||||||
|
.transfer = transfer,
|
||||||
|
.err = err,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (execute_callback) {
|
||||||
|
transfer.req.error_callback(transfer.req.ctx, err);
|
||||||
|
} else if (transfer.req.shutdown_callback) |cb| {
|
||||||
|
cb(transfer.req.ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same restriction as changeProxy. Should be ok since this is only called on
|
||||||
|
// BrowserContext deinit.
|
||||||
|
pub fn restoreOriginalProxy(self: *Client) !void {
|
||||||
|
try self.ensureNoActiveConnection();
|
||||||
|
|
||||||
|
self.http_proxy = self.network.config.httpProxy();
|
||||||
|
self.use_proxy = self.http_proxy != null;
|
||||||
|
}
|
||||||
|
|
||||||
fn makeRequest(self: *Client, conn: *http.Connection, transfer: *Transfer) anyerror!void {
|
fn makeRequest(self: *Client, conn: *http.Connection, transfer: *Transfer) anyerror!void {
|
||||||
{
|
{
|
||||||
// Reset per-response state for retries (auth challenge, queue).
|
// Reset per-response state for retries (auth challenge, queue).
|
||||||
@@ -674,7 +771,7 @@ fn makeRequest(self: *Client, conn: *http.Connection, transfer: *Transfer) anyer
|
|||||||
self.active += 1;
|
self.active += 1;
|
||||||
|
|
||||||
if (transfer.req.start_callback) |cb| {
|
if (transfer.req.start_callback) |cb| {
|
||||||
cb(transfer) catch |err| {
|
cb(Response.fromTransfer(transfer)) catch |err| {
|
||||||
transfer.deinit();
|
transfer.deinit();
|
||||||
return err;
|
return err;
|
||||||
};
|
};
|
||||||
@@ -742,7 +839,10 @@ fn processOneMessage(self: *Client, msg: http.Handles.MultiMessage, transfer: *T
|
|||||||
// TODO give a way to configure the number of auth retries.
|
// TODO give a way to configure the number of auth retries.
|
||||||
if (transfer._auth_challenge != null and transfer._tries < 10) {
|
if (transfer._auth_challenge != null and transfer._tries < 10) {
|
||||||
var wait_for_interception = false;
|
var wait_for_interception = false;
|
||||||
transfer.req.notification.dispatch(.http_request_auth_required, &.{ .transfer = transfer, .wait_for_interception = &wait_for_interception });
|
transfer.req.notification.dispatch(
|
||||||
|
.http_request_auth_required,
|
||||||
|
&.{ .transfer = transfer, .wait_for_interception = &wait_for_interception },
|
||||||
|
);
|
||||||
if (wait_for_interception) {
|
if (wait_for_interception) {
|
||||||
self.intercepted += 1;
|
self.intercepted += 1;
|
||||||
if (comptime IS_DEBUG) {
|
if (comptime IS_DEBUG) {
|
||||||
@@ -821,16 +921,16 @@ fn processOneMessage(self: *Client, msg: http.Handles.MultiMessage, transfer: *T
|
|||||||
break :blk std.ascii.eqlIgnoreCase(hdr.value, "close");
|
break :blk std.ascii.eqlIgnoreCase(hdr.value, "close");
|
||||||
};
|
};
|
||||||
|
|
||||||
if (msg.err != null and !is_conn_close_recv) {
|
|
||||||
transfer.requestFailed(transfer._callback_error orelse msg.err.?, true);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// make sure the transfer can't be immediately aborted from a callback
|
// make sure the transfer can't be immediately aborted from a callback
|
||||||
// since we still need it here.
|
// since we still need it here.
|
||||||
transfer._performing = true;
|
transfer._performing = true;
|
||||||
defer transfer._performing = false;
|
defer transfer._performing = false;
|
||||||
|
|
||||||
|
if (msg.err != null and !is_conn_close_recv) {
|
||||||
|
transfer.requestFailed(transfer._callback_error orelse msg.err.?, true);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
if (!transfer._header_done_called) {
|
if (!transfer._header_done_called) {
|
||||||
// In case of request w/o data, we need to call the header done
|
// In case of request w/o data, we need to call the header done
|
||||||
// callback now.
|
// callback now.
|
||||||
@@ -841,10 +941,11 @@ fn processOneMessage(self: *Client, msg: http.Handles.MultiMessage, transfer: *T
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const body = transfer._stream_buffer.items;
|
||||||
|
|
||||||
// Replay buffered body through user's data_callback.
|
// Replay buffered body through user's data_callback.
|
||||||
if (transfer._stream_buffer.items.len > 0) {
|
if (transfer._stream_buffer.items.len > 0) {
|
||||||
const body = transfer._stream_buffer.items;
|
try transfer.req.data_callback(Response.fromTransfer(transfer), body);
|
||||||
try transfer.req.data_callback(transfer, body);
|
|
||||||
|
|
||||||
transfer.req.notification.dispatch(.http_response_data, &.{
|
transfer.req.notification.dispatch(.http_response_data, &.{
|
||||||
.data = body,
|
.data = body,
|
||||||
@@ -857,11 +958,42 @@ fn processOneMessage(self: *Client, msg: http.Handles.MultiMessage, transfer: *T
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const allocator = transfer.arena.allocator();
|
||||||
|
var header_list: std.ArrayList(http.Header) = .empty;
|
||||||
|
|
||||||
|
var it = transfer.responseHeaderIterator();
|
||||||
|
while (it.next()) |hdr| {
|
||||||
|
header_list.append(
|
||||||
|
allocator,
|
||||||
|
.{
|
||||||
|
.name = try allocator.dupe(u8, hdr.name),
|
||||||
|
.value = try allocator.dupe(u8, hdr.value),
|
||||||
|
},
|
||||||
|
) catch |err| {
|
||||||
|
log.warn(.http, "cache header collect failed", .{ .err = err });
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// release conn ASAP so that it's available; some done_callbacks
|
// release conn ASAP so that it's available; some done_callbacks
|
||||||
// will load more resources.
|
// will load more resources.
|
||||||
transfer.releaseConn();
|
transfer.releaseConn();
|
||||||
|
|
||||||
try transfer.req.done_callback(transfer.ctx);
|
try transfer.req.done_callback(transfer.req.ctx);
|
||||||
|
|
||||||
|
if (transfer._pending_cache_metadata) |metadata| {
|
||||||
|
const cache = &self.network.cache.?;
|
||||||
|
|
||||||
|
// TODO: Support Vary Keying
|
||||||
|
const cache_key = transfer.req.url;
|
||||||
|
|
||||||
|
log.debug(.browser, "http cache", .{ .key = cache_key, .metadata = metadata });
|
||||||
|
cache.put(metadata, body) catch |err| {
|
||||||
|
log.warn(.http, "cache put failed", .{ .err = err });
|
||||||
|
};
|
||||||
|
log.debug(.browser, "http.cache.put", .{ .url = transfer.req.url });
|
||||||
|
}
|
||||||
|
|
||||||
transfer.req.notification.dispatch(.http_request_done, &.{
|
transfer.req.notification.dispatch(.http_request_done, &.{
|
||||||
.transfer = transfer,
|
.transfer = transfer,
|
||||||
});
|
});
|
||||||
@@ -873,7 +1005,6 @@ fn processMessages(self: *Client) !bool {
|
|||||||
var processed = false;
|
var processed = false;
|
||||||
while (self.handles.readMessage()) |msg| {
|
while (self.handles.readMessage()) |msg| {
|
||||||
const transfer = try Transfer.fromConnection(&msg.conn);
|
const transfer = try Transfer.fromConnection(&msg.conn);
|
||||||
|
|
||||||
const done = self.processOneMessage(msg, transfer) catch |err| blk: {
|
const done = self.processOneMessage(msg, transfer) catch |err| blk: {
|
||||||
log.err(.http, "process_messages", .{ .err = err, .req = transfer });
|
log.err(.http, "process_messages", .{ .err = err, .req = transfer });
|
||||||
transfer.requestFailed(err, true);
|
transfer.requestFailed(err, true);
|
||||||
@@ -940,9 +1071,9 @@ pub const Request = struct {
|
|||||||
// arbitrary data that can be associated with this request
|
// arbitrary data that can be associated with this request
|
||||||
ctx: *anyopaque = undefined,
|
ctx: *anyopaque = undefined,
|
||||||
|
|
||||||
start_callback: ?*const fn (transfer: *Transfer) anyerror!void = null,
|
start_callback: ?*const fn (response: Response) anyerror!void = null,
|
||||||
header_callback: *const fn (transfer: *Transfer) anyerror!bool,
|
header_callback: *const fn (response: Response) anyerror!bool,
|
||||||
data_callback: *const fn (transfer: *Transfer, data: []const u8) anyerror!void,
|
data_callback: *const fn (response: Response, data: []const u8) anyerror!void,
|
||||||
done_callback: *const fn (ctx: *anyopaque) anyerror!void,
|
done_callback: *const fn (ctx: *anyopaque) anyerror!void,
|
||||||
error_callback: *const fn (ctx: *anyopaque, err: anyerror) void,
|
error_callback: *const fn (ctx: *anyopaque, err: anyerror) void,
|
||||||
shutdown_callback: ?*const fn (ctx: *anyopaque) void = null,
|
shutdown_callback: ?*const fn (ctx: *anyopaque) void = null,
|
||||||
@@ -968,16 +1099,84 @@ pub const Request = struct {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub const Response = struct {
|
||||||
|
ctx: *anyopaque,
|
||||||
|
inner: union(enum) {
|
||||||
|
transfer: *Transfer,
|
||||||
|
cached: *const CachedResponse,
|
||||||
|
},
|
||||||
|
|
||||||
|
pub fn fromTransfer(transfer: *Transfer) Response {
|
||||||
|
return .{ .ctx = transfer.req.ctx, .inner = .{ .transfer = transfer } };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fromCached(ctx: *anyopaque, resp: *const CachedResponse) Response {
|
||||||
|
return .{ .ctx = ctx, .inner = .{ .cached = resp } };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn status(self: Response) ?u16 {
|
||||||
|
return switch (self.inner) {
|
||||||
|
.transfer => |t| if (t.response_header) |rh| rh.status else null,
|
||||||
|
.cached => |c| c.metadata.status,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contentType(self: Response) ?[]const u8 {
|
||||||
|
return switch (self.inner) {
|
||||||
|
.transfer => |t| if (t.response_header) |*rh| rh.contentType() else null,
|
||||||
|
.cached => |c| c.metadata.content_type,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contentLength(self: Response) ?u32 {
|
||||||
|
return switch (self.inner) {
|
||||||
|
.transfer => |t| t.getContentLength(),
|
||||||
|
.cached => |c| switch (c.data) {
|
||||||
|
.buffer => |buf| @intCast(buf.len),
|
||||||
|
.file => |f| @intCast(f.getEndPos() catch 0),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn redirectCount(self: Response) ?u32 {
|
||||||
|
return switch (self.inner) {
|
||||||
|
.transfer => |t| if (t.response_header) |rh| rh.redirect_count else null,
|
||||||
|
.cached => 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn url(self: Response) [:0]const u8 {
|
||||||
|
return switch (self.inner) {
|
||||||
|
.transfer => |t| t.url,
|
||||||
|
.cached => |c| c.metadata.url,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn headerIterator(self: Response) HeaderIterator {
|
||||||
|
return switch (self.inner) {
|
||||||
|
.transfer => |t| t.responseHeaderIterator(),
|
||||||
|
.cached => |c| HeaderIterator{ .list = .{ .list = c.metadata.headers } },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn abort(self: Response, err: anyerror) void {
|
||||||
|
switch (self.inner) {
|
||||||
|
.transfer => |t| t.abort(err),
|
||||||
|
.cached => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
pub const Transfer = struct {
|
pub const Transfer = struct {
|
||||||
arena: ArenaAllocator,
|
arena: ArenaAllocator,
|
||||||
id: u32 = 0,
|
id: u32 = 0,
|
||||||
req: Request,
|
req: Request,
|
||||||
url: [:0]const u8,
|
url: [:0]const u8,
|
||||||
ctx: *anyopaque, // copied from req.ctx to make it easier for callback handlers
|
|
||||||
client: *Client,
|
client: *Client,
|
||||||
// total bytes received in the response, including the response status line,
|
// total bytes received in the response, including the response status line,
|
||||||
// the headers, and the [encoded] body.
|
// the headers, and the [encoded] body.
|
||||||
bytes_received: usize = 0,
|
bytes_received: usize = 0,
|
||||||
|
_pending_cache_metadata: ?CacheMetadata = null,
|
||||||
|
|
||||||
aborted: bool = false,
|
aborted: bool = false,
|
||||||
|
|
||||||
@@ -1066,8 +1265,26 @@ pub const Transfer = struct {
|
|||||||
// as abort (doesn't send a notification, doesn't invoke an error callback)
|
// as abort (doesn't send a notification, doesn't invoke an error callback)
|
||||||
fn kill(self: *Transfer) void {
|
fn kill(self: *Transfer) void {
|
||||||
if (self.req.shutdown_callback) |cb| {
|
if (self.req.shutdown_callback) |cb| {
|
||||||
cb(self.ctx);
|
cb(self.req.ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (self._performing or self.client.performing) {
|
||||||
|
// We're currently inside of a callback. This client, and libcurl
|
||||||
|
// generally don't expect a transfer to become deinitialized during
|
||||||
|
// a callback. We can flag the transfer as aborted (which is what
|
||||||
|
// we do when transfer.abort() is called in this condition) AND,
|
||||||
|
// since this "kill()"should prevent any future callbacks, the best
|
||||||
|
// we can do is null/noop them.
|
||||||
|
self.aborted = true;
|
||||||
|
self.req.start_callback = null;
|
||||||
|
self.req.shutdown_callback = null;
|
||||||
|
self.req.header_callback = Noop.headerCallback;
|
||||||
|
self.req.data_callback = Noop.dataCallback;
|
||||||
|
self.req.done_callback = Noop.doneCallback;
|
||||||
|
self.req.error_callback = Noop.errorCallback;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
self.deinit();
|
self.deinit();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1084,7 +1301,7 @@ pub const Transfer = struct {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (execute_callback) {
|
if (execute_callback) {
|
||||||
self.req.error_callback(self.ctx, err);
|
self.req.error_callback(self.req.ctx, err);
|
||||||
} else if (self.req.shutdown_callback) |cb| {
|
} else if (self.req.shutdown_callback) |cb| {
|
||||||
cb(self.ctx);
|
cb(self.ctx);
|
||||||
}
|
}
|
||||||
@@ -1325,11 +1542,45 @@ pub const Transfer = struct {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const proceed = transfer.req.header_callback(transfer) catch |err| {
|
const proceed = transfer.req.header_callback(Response.fromTransfer(transfer)) catch |err| {
|
||||||
log.err(.http, "header_callback", .{ .err = err, .req = transfer });
|
log.err(.http, "header_callback", .{ .err = err, .req = transfer });
|
||||||
return err;
|
return err;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (transfer.client.network.cache != null and transfer.req.method == .GET) {
|
||||||
|
const rh = &transfer.response_header.?;
|
||||||
|
const allocator = transfer.arena.allocator();
|
||||||
|
|
||||||
|
const maybe_cm = try Cache.tryCache(
|
||||||
|
allocator,
|
||||||
|
std.time.timestamp(),
|
||||||
|
transfer.url,
|
||||||
|
rh.status,
|
||||||
|
rh.contentType(),
|
||||||
|
if (conn.getResponseHeader("cache-control", 0)) |h| h.value else null,
|
||||||
|
if (conn.getResponseHeader("vary", 0)) |h| h.value else null,
|
||||||
|
if (conn.getResponseHeader("etag", 0)) |h| h.value else null,
|
||||||
|
if (conn.getResponseHeader("last-modified", 0)) |h| h.value else null,
|
||||||
|
if (conn.getResponseHeader("age", 0)) |h| h.value else null,
|
||||||
|
conn.getResponseHeader("set-cookie", 0) != null,
|
||||||
|
conn.getResponseHeader("authorization", 0) != null,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (maybe_cm) |cm| {
|
||||||
|
var header_list: std.ArrayList(http.Header) = .empty;
|
||||||
|
var it = transfer.responseHeaderIterator();
|
||||||
|
while (it.next()) |hdr| {
|
||||||
|
try header_list.append(allocator, .{
|
||||||
|
.name = try allocator.dupe(u8, hdr.name),
|
||||||
|
.value = try allocator.dupe(u8, hdr.value),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
transfer._pending_cache_metadata = cm;
|
||||||
|
transfer._pending_cache_metadata.?.headers = header_list.items;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
transfer.req.notification.dispatch(.http_response_header_done, &.{
|
transfer.req.notification.dispatch(.http_response_header_done, &.{
|
||||||
.transfer = transfer,
|
.transfer = transfer,
|
||||||
});
|
});
|
||||||
@@ -1432,7 +1683,7 @@ pub const Transfer = struct {
|
|||||||
fn _fulfill(transfer: *Transfer, status: u16, headers: []const http.Header, body: ?[]const u8) !void {
|
fn _fulfill(transfer: *Transfer, status: u16, headers: []const http.Header, body: ?[]const u8) !void {
|
||||||
const req = &transfer.req;
|
const req = &transfer.req;
|
||||||
if (req.start_callback) |cb| {
|
if (req.start_callback) |cb| {
|
||||||
try cb(transfer);
|
try cb(Response.fromTransfer(transfer));
|
||||||
}
|
}
|
||||||
|
|
||||||
transfer.response_header = .{
|
transfer.response_header = .{
|
||||||
@@ -1451,13 +1702,13 @@ pub const Transfer = struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
lp.assert(transfer._header_done_called == false, "Transfer.fulfill header_done_called", .{});
|
lp.assert(transfer._header_done_called == false, "Transfer.fulfill header_done_called", .{});
|
||||||
if (try req.header_callback(transfer) == false) {
|
if (try req.header_callback(Response.fromTransfer(transfer)) == false) {
|
||||||
transfer.abort(error.Abort);
|
transfer.abort(error.Abort);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (body) |b| {
|
if (body) |b| {
|
||||||
try req.data_callback(transfer, b);
|
try req.data_callback(Response.fromTransfer(transfer), b);
|
||||||
}
|
}
|
||||||
|
|
||||||
try req.done_callback(req.ctx);
|
try req.done_callback(req.ctx);
|
||||||
@@ -1492,3 +1743,12 @@ pub const Transfer = struct {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const Noop = struct {
|
||||||
|
fn headerCallback(_: Response) !bool {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
fn dataCallback(_: Response, _: []const u8) !void {}
|
||||||
|
fn doneCallback(_: *anyopaque) !void {}
|
||||||
|
fn errorCallback(_: *anyopaque, _: anyerror) void {}
|
||||||
|
};
|
||||||
|
|||||||
@@ -27,6 +27,9 @@ charset: [41]u8 = default_charset,
|
|||||||
charset_len: usize = default_charset_len,
|
charset_len: usize = default_charset_len,
|
||||||
is_default_charset: bool = true,
|
is_default_charset: bool = true,
|
||||||
|
|
||||||
|
type_buf: [127]u8 = @splat(0),
|
||||||
|
sub_type_buf: [127]u8 = @splat(0),
|
||||||
|
|
||||||
/// String "UTF-8" continued by null characters.
|
/// String "UTF-8" continued by null characters.
|
||||||
const default_charset = .{ 'U', 'T', 'F', '-', '8' } ++ .{0} ** 36;
|
const default_charset = .{ 'U', 'T', 'F', '-', '8' } ++ .{0} ** 36;
|
||||||
const default_charset_len = 5;
|
const default_charset_len = 5;
|
||||||
@@ -61,7 +64,10 @@ pub const ContentType = union(ContentTypeEnum) {
|
|||||||
image_webp: void,
|
image_webp: void,
|
||||||
application_json: void,
|
application_json: void,
|
||||||
unknown: void,
|
unknown: void,
|
||||||
other: struct { type: []const u8, sub_type: []const u8 },
|
other: struct {
|
||||||
|
type: []const u8,
|
||||||
|
sub_type: []const u8,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn contentTypeString(mime: *const Mime) []const u8 {
|
pub fn contentTypeString(mime: *const Mime) []const u8 {
|
||||||
@@ -112,17 +118,18 @@ fn parseCharset(value: []const u8) error{ CharsetTooBig, Invalid }![]const u8 {
|
|||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parse(input: []u8) !Mime {
|
pub fn parse(input: []const u8) !Mime {
|
||||||
if (input.len > 255) {
|
if (input.len > 255) {
|
||||||
return error.TooBig;
|
return error.TooBig;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Zig's trim API is broken. The return type is always `[]const u8`,
|
var buf: [255]u8 = undefined;
|
||||||
// even if the input type is `[]u8`. @constCast is safe here.
|
const normalized = std.ascii.lowerString(&buf, std.mem.trim(u8, input, &std.ascii.whitespace));
|
||||||
var normalized = @constCast(std.mem.trim(u8, input, &std.ascii.whitespace));
|
|
||||||
_ = std.ascii.lowerString(normalized, normalized);
|
_ = std.ascii.lowerString(normalized, normalized);
|
||||||
|
|
||||||
const content_type, const type_len = try parseContentType(normalized);
|
var mime = Mime{ .content_type = undefined };
|
||||||
|
|
||||||
|
const content_type, const type_len = try parseContentType(normalized, &mime.type_buf, &mime.sub_type_buf);
|
||||||
if (type_len >= normalized.len) {
|
if (type_len >= normalized.len) {
|
||||||
return .{ .content_type = content_type };
|
return .{ .content_type = content_type };
|
||||||
}
|
}
|
||||||
@@ -163,13 +170,12 @@ pub fn parse(input: []u8) !Mime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return .{
|
mime.params = params;
|
||||||
.params = params,
|
mime.charset = charset;
|
||||||
.charset = charset,
|
mime.charset_len = charset_len;
|
||||||
.charset_len = charset_len,
|
mime.content_type = content_type;
|
||||||
.content_type = content_type,
|
mime.is_default_charset = !has_explicit_charset;
|
||||||
.is_default_charset = !has_explicit_charset,
|
return mime;
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Prescan the first 1024 bytes of an HTML document for a charset declaration.
|
/// Prescan the first 1024 bytes of an HTML document for a charset declaration.
|
||||||
@@ -395,7 +401,7 @@ pub fn isText(mime: *const Mime) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// we expect value to be lowercase
|
// we expect value to be lowercase
|
||||||
fn parseContentType(value: []const u8) !struct { ContentType, usize } {
|
fn parseContentType(value: []const u8, type_buf: []u8, sub_type_buf: []u8) !struct { ContentType, usize } {
|
||||||
const end = std.mem.indexOfScalarPos(u8, value, 0, ';') orelse value.len;
|
const end = std.mem.indexOfScalarPos(u8, value, 0, ';') orelse value.len;
|
||||||
const type_name = trimRight(value[0..end]);
|
const type_name = trimRight(value[0..end]);
|
||||||
const attribute_start = end + 1;
|
const attribute_start = end + 1;
|
||||||
@@ -444,10 +450,18 @@ fn parseContentType(value: []const u8) !struct { ContentType, usize } {
|
|||||||
return error.Invalid;
|
return error.Invalid;
|
||||||
}
|
}
|
||||||
|
|
||||||
return .{ .{ .other = .{
|
@memcpy(type_buf[0..main_type.len], main_type);
|
||||||
.type = main_type,
|
@memcpy(sub_type_buf[0..sub_type.len], sub_type);
|
||||||
.sub_type = sub_type,
|
|
||||||
} }, attribute_start };
|
return .{
|
||||||
|
.{
|
||||||
|
.other = .{
|
||||||
|
.type = type_buf[0..main_type.len],
|
||||||
|
.sub_type = sub_type_buf[0..sub_type.len],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
attribute_start,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const VALID_CODEPOINTS = blk: {
|
const VALID_CODEPOINTS = blk: {
|
||||||
@@ -461,6 +475,13 @@ const VALID_CODEPOINTS = blk: {
|
|||||||
break :blk v;
|
break :blk v;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub fn typeString(self: *const Mime) []const u8 {
|
||||||
|
return switch (self.content_type) {
|
||||||
|
.other => |o| o.type[0..o.type_len],
|
||||||
|
else => "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
fn validType(value: []const u8) bool {
|
fn validType(value: []const u8) bool {
|
||||||
for (value) |b| {
|
for (value) |b| {
|
||||||
if (VALID_CODEPOINTS[b] == false) {
|
if (VALID_CODEPOINTS[b] == false) {
|
||||||
|
|||||||
@@ -854,12 +854,10 @@ fn notifyParentLoadComplete(self: *Page) void {
|
|||||||
parent.iframeCompletedLoading(self.iframe.?);
|
parent.iframeCompletedLoading(self.iframe.?);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pageHeaderDoneCallback(transfer: *HttpClient.Transfer) !bool {
|
fn pageHeaderDoneCallback(response: HttpClient.Response) !bool {
|
||||||
var self: *Page = @ptrCast(@alignCast(transfer.ctx));
|
var self: *Page = @ptrCast(@alignCast(response.ctx));
|
||||||
|
|
||||||
const header = &transfer.response_header.?;
|
const response_url = response.url();
|
||||||
|
|
||||||
const response_url = std.mem.span(header.url);
|
|
||||||
if (std.mem.eql(u8, response_url, self.url) == false) {
|
if (std.mem.eql(u8, response_url, self.url) == false) {
|
||||||
// would be different than self.url in the case of a redirect
|
// would be different than self.url in the case of a redirect
|
||||||
self.url = try self.arena.dupeZ(u8, response_url);
|
self.url = try self.arena.dupeZ(u8, response_url);
|
||||||
@@ -873,8 +871,8 @@ fn pageHeaderDoneCallback(transfer: *HttpClient.Transfer) !bool {
|
|||||||
if (comptime IS_DEBUG) {
|
if (comptime IS_DEBUG) {
|
||||||
log.debug(.page, "navigate header", .{
|
log.debug(.page, "navigate header", .{
|
||||||
.url = self.url,
|
.url = self.url,
|
||||||
.status = header.status,
|
.status = response.status(),
|
||||||
.content_type = header.contentType(),
|
.content_type = response.contentType(),
|
||||||
.type = self._type,
|
.type = self._type,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -882,14 +880,14 @@ fn pageHeaderDoneCallback(transfer: *HttpClient.Transfer) !bool {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pageDataCallback(transfer: *HttpClient.Transfer, data: []const u8) !void {
|
fn pageDataCallback(response: HttpClient.Response, data: []const u8) !void {
|
||||||
var self: *Page = @ptrCast(@alignCast(transfer.ctx));
|
var self: *Page = @ptrCast(@alignCast(response.ctx));
|
||||||
|
|
||||||
if (self._parse_state == .pre) {
|
if (self._parse_state == .pre) {
|
||||||
// we lazily do this, because we might need the first chunk of data
|
// we lazily do this, because we might need the first chunk of data
|
||||||
// to sniff the content type
|
// to sniff the content type
|
||||||
var mime: Mime = blk: {
|
var mime: Mime = blk: {
|
||||||
if (transfer.response_header.?.contentType()) |ct| {
|
if (response.contentType()) |ct| {
|
||||||
break :blk try Mime.parse(ct);
|
break :blk try Mime.parse(ct);
|
||||||
}
|
}
|
||||||
break :blk Mime.sniff(data);
|
break :blk Mime.sniff(data);
|
||||||
@@ -3392,7 +3390,7 @@ pub fn handleClick(self: *Page, target: *Node) !void {
|
|||||||
pub fn triggerKeyboard(self: *Page, keyboard_event: *KeyboardEvent) !void {
|
pub fn triggerKeyboard(self: *Page, keyboard_event: *KeyboardEvent) !void {
|
||||||
const event = keyboard_event.asEvent();
|
const event = keyboard_event.asEvent();
|
||||||
const element = self.window._document._active_element orelse {
|
const element = self.window._document._active_element orelse {
|
||||||
keyboard_event.deinit(false, self._session);
|
_ = event.releaseRef(self._session);
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -3488,7 +3486,7 @@ pub fn submitForm(self: *Page, submitter_: ?*Element, form_: ?*Element.Html.Form
|
|||||||
|
|
||||||
// so submit_event is still valid when we check _prevent_default
|
// so submit_event is still valid when we check _prevent_default
|
||||||
submit_event.acquireRef();
|
submit_event.acquireRef();
|
||||||
defer submit_event.deinit(false, self._session);
|
defer _ = submit_event.releaseRef(self._session);
|
||||||
|
|
||||||
try self._event_manager.dispatch(form_element.asEventTarget(), submit_event);
|
try self._event_manager.dispatch(form_element.asEventTarget(), submit_event);
|
||||||
// If the submit event was prevented, don't submit the form
|
// If the submit event was prevented, don't submit the form
|
||||||
|
|||||||
@@ -694,32 +694,33 @@ pub const Script = struct {
|
|||||||
self.manager.page.releaseArena(self.arena);
|
self.manager.page.releaseArena(self.arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn startCallback(transfer: *HttpClient.Transfer) !void {
|
fn startCallback(response: HttpClient.Response) !void {
|
||||||
log.debug(.http, "script fetch start", .{ .req = transfer });
|
log.debug(.http, "script fetch start", .{ .req = response });
|
||||||
}
|
}
|
||||||
|
|
||||||
fn headerCallback(transfer: *HttpClient.Transfer) !bool {
|
fn headerCallback(response: HttpClient.Response) !bool {
|
||||||
const self: *Script = @ptrCast(@alignCast(transfer.ctx));
|
const self: *Script = @ptrCast(@alignCast(response.ctx));
|
||||||
const header = &transfer.response_header.?;
|
|
||||||
self.status = header.status;
|
self.status = response.status().?;
|
||||||
if (header.status != 200) {
|
if (response.status() != 200) {
|
||||||
log.info(.http, "script header", .{
|
log.info(.http, "script header", .{
|
||||||
.req = transfer,
|
.req = response,
|
||||||
.status = header.status,
|
.status = response.status(),
|
||||||
.content_type = header.contentType(),
|
.content_type = response.contentType(),
|
||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (comptime IS_DEBUG) {
|
if (comptime IS_DEBUG) {
|
||||||
log.debug(.http, "script header", .{
|
log.debug(.http, "script header", .{
|
||||||
.req = transfer,
|
.req = response,
|
||||||
.status = header.status,
|
.status = response.status(),
|
||||||
.content_type = header.contentType(),
|
.content_type = response.contentType(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
switch (response.inner) {
|
||||||
|
.transfer => |transfer| {
|
||||||
// temp debug, trying to figure out why the next assert sometimes
|
// temp debug, trying to figure out why the next assert sometimes
|
||||||
// fails. Is the buffer just corrupt or is headerCallback really
|
// fails. Is the buffer just corrupt or is headerCallback really
|
||||||
// being called twice?
|
// being called twice?
|
||||||
@@ -751,25 +752,28 @@ pub const Script = struct {
|
|||||||
self.debug_transfer_intercept_state = @intFromEnum(transfer._intercept_state);
|
self.debug_transfer_intercept_state = @intFromEnum(transfer._intercept_state);
|
||||||
self.debug_transfer_auth_challenge = transfer._auth_challenge != null;
|
self.debug_transfer_auth_challenge = transfer._auth_challenge != null;
|
||||||
self.debug_transfer_easy_id = if (transfer._conn) |c| @intFromPtr(c._easy) else 0;
|
self.debug_transfer_easy_id = if (transfer._conn) |c| @intFromPtr(c._easy) else 0;
|
||||||
|
},
|
||||||
|
else => {},
|
||||||
}
|
}
|
||||||
|
|
||||||
lp.assert(self.source.remote.capacity == 0, "ScriptManager.Header buffer", .{ .capacity = self.source.remote.capacity });
|
lp.assert(self.source.remote.capacity == 0, "ScriptManager.Header buffer", .{ .capacity = self.source.remote.capacity });
|
||||||
var buffer: std.ArrayList(u8) = .empty;
|
var buffer: std.ArrayList(u8) = .empty;
|
||||||
if (transfer.getContentLength()) |cl| {
|
if (response.contentLength()) |cl| {
|
||||||
try buffer.ensureTotalCapacity(self.arena, cl);
|
try buffer.ensureTotalCapacity(self.arena, cl);
|
||||||
}
|
}
|
||||||
self.source = .{ .remote = buffer };
|
self.source = .{ .remote = buffer };
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dataCallback(transfer: *HttpClient.Transfer, data: []const u8) !void {
|
fn dataCallback(response: HttpClient.Response, data: []const u8) !void {
|
||||||
const self: *Script = @ptrCast(@alignCast(transfer.ctx));
|
const self: *Script = @ptrCast(@alignCast(response.ctx));
|
||||||
self._dataCallback(transfer, data) catch |err| {
|
self._dataCallback(response, data) catch |err| {
|
||||||
log.err(.http, "SM.dataCallback", .{ .err = err, .transfer = transfer, .len = data.len });
|
log.err(.http, "SM.dataCallback", .{ .err = err, .transfer = response, .len = data.len });
|
||||||
return err;
|
return err;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
fn _dataCallback(self: *Script, _: *HttpClient.Transfer, data: []const u8) !void {
|
|
||||||
|
fn _dataCallback(self: *Script, _: HttpClient.Response, data: []const u8) !void {
|
||||||
try self.source.remote.appendSlice(self.arena, data);
|
try self.source.remote.appendSlice(self.arena, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -71,6 +71,18 @@ origins: std.StringHashMapUnmanaged(*js.Origin) = .empty,
|
|||||||
// ensuring object identity works across same-origin frames.
|
// ensuring object identity works across same-origin frames.
|
||||||
identity: js.Identity = .{},
|
identity: js.Identity = .{},
|
||||||
|
|
||||||
|
// Shared finalizer callbacks across all Identities. Keyed by Zig instance ptr.
|
||||||
|
// This ensures objects are only freed when ALL v8 wrappers are gone.
|
||||||
|
finalizer_callbacks: std.AutoHashMapUnmanaged(usize, *FinalizerCallback) = .empty,
|
||||||
|
|
||||||
|
// Tracked global v8 objects that need to be released on cleanup.
|
||||||
|
// Lives at Session level so objects can outlive individual Identities.
|
||||||
|
globals: std.ArrayList(v8.Global) = .empty,
|
||||||
|
|
||||||
|
// Temporary v8 globals that can be released early. Key is global.data_ptr.
|
||||||
|
// Lives at Session level so objects holding Temps can outlive individual Identities.
|
||||||
|
temps: std.AutoHashMapUnmanaged(usize, v8.Global) = .empty,
|
||||||
|
|
||||||
// Shared resources for all pages in this session.
|
// Shared resources for all pages in this session.
|
||||||
// These live for the duration of the page tree (root + frames).
|
// These live for the duration of the page tree (root + frames).
|
||||||
arena_pool: *ArenaPool,
|
arena_pool: *ArenaPool,
|
||||||
@@ -224,6 +236,30 @@ pub fn releaseOrigin(self: *Session, origin: *js.Origin) void {
|
|||||||
/// Reset page_arena and factory for a clean slate.
|
/// Reset page_arena and factory for a clean slate.
|
||||||
/// Called when root page is removed.
|
/// Called when root page is removed.
|
||||||
fn resetPageResources(self: *Session) void {
|
fn resetPageResources(self: *Session) void {
|
||||||
|
// Force cleanup all remaining finalized objects
|
||||||
|
{
|
||||||
|
var it = self.finalizer_callbacks.valueIterator();
|
||||||
|
while (it.next()) |fc| {
|
||||||
|
fc.*.deinit(self);
|
||||||
|
}
|
||||||
|
self.finalizer_callbacks = .empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
for (self.globals.items) |*global| {
|
||||||
|
v8.v8__Global__Reset(global);
|
||||||
|
}
|
||||||
|
self.globals = .empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
var it = self.temps.valueIterator();
|
||||||
|
while (it.next()) |global| {
|
||||||
|
v8.v8__Global__Reset(global);
|
||||||
|
}
|
||||||
|
self.temps = .empty;
|
||||||
|
}
|
||||||
|
|
||||||
self.identity.deinit();
|
self.identity.deinit();
|
||||||
self.identity = .{};
|
self.identity = .{};
|
||||||
|
|
||||||
@@ -457,35 +493,25 @@ pub fn nextPageId(self: *Session) u32 {
|
|||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A type that has a finalizer can have its finalizer called one of two ways.
|
// Every finalizable instance of Zig gets 1 FinalizerCallback registered in the
|
||||||
// The first is from V8 via the WeakCallback we give to weakRef. But that isn't
|
// session. This is to ensure that, if v8 doesn't finalize the value, we can
|
||||||
// guaranteed to fire, so we track this in finalizer_callbacks and call them on
|
// release on page reset.
|
||||||
// page reset.
|
|
||||||
pub const FinalizerCallback = struct {
|
pub const FinalizerCallback = struct {
|
||||||
arena: Allocator,
|
arena: Allocator,
|
||||||
session: *Session,
|
session: *Session,
|
||||||
ptr: *anyopaque,
|
resolved_ptr_id: usize,
|
||||||
global: v8.Global,
|
finalizer_ptr_id: usize,
|
||||||
|
_deinit: *const fn (ptr_id: usize, session: *Session) void,
|
||||||
|
|
||||||
|
// For every FinalizerCallback we'll have 1+ FinalizerCallback.Identity: one
|
||||||
|
// for every identity that gets the instance. In most cases, that'l be 1.
|
||||||
|
pub const Identity = struct {
|
||||||
identity: *js.Identity,
|
identity: *js.Identity,
|
||||||
zig_finalizer: *const fn (ptr: *anyopaque, session: *Session) void,
|
fc: *Session.FinalizerCallback,
|
||||||
|
};
|
||||||
pub fn deinit(self: *FinalizerCallback) void {
|
|
||||||
self.zig_finalizer(self.ptr, self.session);
|
|
||||||
self.session.releaseArena(self.arena);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Release this item from the identity tracking maps (called after finalizer runs from V8)
|
|
||||||
pub fn releaseIdentity(self: *FinalizerCallback) void {
|
|
||||||
const session = self.session;
|
|
||||||
const id = @intFromPtr(self.ptr);
|
|
||||||
|
|
||||||
if (self.identity.identity_map.fetchRemove(id)) |kv| {
|
|
||||||
var global = kv.value;
|
|
||||||
v8.v8__Global__Reset(&global);
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = self.identity.finalizer_callbacks.remove(id);
|
|
||||||
|
|
||||||
|
fn deinit(self: *FinalizerCallback, session: *Session) void {
|
||||||
|
self._deinit(self.finalizer_ptr_id, session);
|
||||||
session.releaseArena(self.arena);
|
session.releaseArena(self.arena);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ const lp = @import("lightpanda");
|
|||||||
const log = @import("../../log.zig");
|
const log = @import("../../log.zig");
|
||||||
|
|
||||||
const js = @import("js.zig");
|
const js = @import("js.zig");
|
||||||
|
const bridge = @import("bridge.zig");
|
||||||
const Env = @import("Env.zig");
|
const Env = @import("Env.zig");
|
||||||
const Origin = @import("Origin.zig");
|
const Origin = @import("Origin.zig");
|
||||||
const Scheduler = @import("Scheduler.zig");
|
const Scheduler = @import("Scheduler.zig");
|
||||||
@@ -213,48 +214,11 @@ pub fn setOrigin(self: *Context, key: ?[]const u8) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn trackGlobal(self: *Context, global: v8.Global) !void {
|
pub fn trackGlobal(self: *Context, global: v8.Global) !void {
|
||||||
return self.identity.globals.append(self.identity_arena, global);
|
return self.session.globals.append(self.session.page_arena, global);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn trackTemp(self: *Context, global: v8.Global) !void {
|
pub fn trackTemp(self: *Context, global: v8.Global) !void {
|
||||||
return self.identity.temps.put(self.identity_arena, global.data_ptr, global);
|
return self.session.temps.put(self.session.page_arena, global.data_ptr, global);
|
||||||
}
|
|
||||||
|
|
||||||
pub fn weakRef(self: *Context, obj: anytype) void {
|
|
||||||
const resolved = js.Local.resolveValue(obj);
|
|
||||||
const fc = self.identity.finalizer_callbacks.get(@intFromPtr(resolved.ptr)) orelse {
|
|
||||||
if (comptime IS_DEBUG) {
|
|
||||||
// should not be possible
|
|
||||||
std.debug.assert(false);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
v8.v8__Global__SetWeakFinalizer(&fc.global, fc, resolved.finalizer_from_v8, v8.kParameter);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn safeWeakRef(self: *Context, obj: anytype) void {
|
|
||||||
const resolved = js.Local.resolveValue(obj);
|
|
||||||
const fc = self.identity.finalizer_callbacks.get(@intFromPtr(resolved.ptr)) orelse {
|
|
||||||
if (comptime IS_DEBUG) {
|
|
||||||
// should not be possible
|
|
||||||
std.debug.assert(false);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
v8.v8__Global__ClearWeak(&fc.global);
|
|
||||||
v8.v8__Global__SetWeakFinalizer(&fc.global, fc, resolved.finalizer_from_v8, v8.kParameter);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn strongRef(self: *Context, obj: anytype) void {
|
|
||||||
const resolved = js.Local.resolveValue(obj);
|
|
||||||
const fc = self.identity.finalizer_callbacks.get(@intFromPtr(resolved.ptr)) orelse {
|
|
||||||
if (comptime IS_DEBUG) {
|
|
||||||
// should not be possible
|
|
||||||
std.debug.assert(false);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
v8.v8__Global__ClearWeak(&fc.global);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const IdentityResult = struct {
|
pub const IdentityResult = struct {
|
||||||
@@ -270,35 +234,6 @@ pub fn addIdentity(self: *Context, ptr: usize) !IdentityResult {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn releaseTemp(self: *Context, global: v8.Global) void {
|
|
||||||
if (self.identity.temps.fetchRemove(global.data_ptr)) |kv| {
|
|
||||||
var g = kv.value;
|
|
||||||
v8.v8__Global__Reset(&g);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn createFinalizerCallback(
|
|
||||||
self: *Context,
|
|
||||||
global: v8.Global,
|
|
||||||
ptr: *anyopaque,
|
|
||||||
zig_finalizer: *const fn (ptr: *anyopaque, session: *Session) void,
|
|
||||||
) !*Session.FinalizerCallback {
|
|
||||||
const session = self.session;
|
|
||||||
const arena = try session.getArena(.{ .debug = "FinalizerCallback" });
|
|
||||||
errdefer session.releaseArena(arena);
|
|
||||||
const fc = try arena.create(Session.FinalizerCallback);
|
|
||||||
fc.* = .{
|
|
||||||
.arena = arena,
|
|
||||||
.session = session,
|
|
||||||
.ptr = ptr,
|
|
||||||
.global = global,
|
|
||||||
.zig_finalizer = zig_finalizer,
|
|
||||||
// Store identity pointer for cleanup when V8 GCs the object
|
|
||||||
.identity = self.identity,
|
|
||||||
};
|
|
||||||
return fc;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Any operation on the context have to be made from a local.
|
// Any operation on the context have to be made from a local.
|
||||||
pub fn localScope(self: *Context, ls: *js.Local.Scope) void {
|
pub fn localScope(self: *Context, ls: *js.Local.Scope) void {
|
||||||
const isolate = self.isolate;
|
const isolate = self.isolate;
|
||||||
|
|||||||
@@ -213,7 +213,7 @@ fn _persist(self: *const Function, comptime is_global: bool) !(if (is_global) Gl
|
|||||||
return .{ .handle = global, .temps = {} };
|
return .{ .handle = global, .temps = {} };
|
||||||
}
|
}
|
||||||
try ctx.trackTemp(global);
|
try ctx.trackTemp(global);
|
||||||
return .{ .handle = global, .temps = &ctx.identity.temps };
|
return .{ .handle = global, .temps = &ctx.session.temps };
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn tempWithThis(self: *const Function, value: anytype) !Temp {
|
pub fn tempWithThis(self: *const Function, value: anytype) !Temp {
|
||||||
|
|||||||
@@ -38,38 +38,9 @@ const Identity = @This();
|
|||||||
// Maps Zig instance pointers to their v8::Global(Object) wrappers.
|
// Maps Zig instance pointers to their v8::Global(Object) wrappers.
|
||||||
identity_map: std.AutoHashMapUnmanaged(usize, v8.Global) = .empty,
|
identity_map: std.AutoHashMapUnmanaged(usize, v8.Global) = .empty,
|
||||||
|
|
||||||
// Tracked global v8 objects that need to be released on cleanup.
|
|
||||||
globals: std.ArrayList(v8.Global) = .empty,
|
|
||||||
|
|
||||||
// Temporary v8 globals that can be released early. Key is global.data_ptr.
|
|
||||||
temps: std.AutoHashMapUnmanaged(usize, v8.Global) = .empty,
|
|
||||||
|
|
||||||
// Finalizer callbacks for weak references. Key is @intFromPtr of the Zig instance.
|
|
||||||
finalizer_callbacks: std.AutoHashMapUnmanaged(usize, *Session.FinalizerCallback) = .empty,
|
|
||||||
|
|
||||||
pub fn deinit(self: *Identity) void {
|
pub fn deinit(self: *Identity) void {
|
||||||
{
|
|
||||||
var it = self.finalizer_callbacks.valueIterator();
|
|
||||||
while (it.next()) |finalizer| {
|
|
||||||
finalizer.*.deinit();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
{
|
|
||||||
var it = self.identity_map.valueIterator();
|
var it = self.identity_map.valueIterator();
|
||||||
while (it.next()) |global| {
|
while (it.next()) |global| {
|
||||||
v8.v8__Global__Reset(global);
|
v8.v8__Global__Reset(global);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
for (self.globals.items) |*global| {
|
|
||||||
v8.v8__Global__Reset(global);
|
|
||||||
}
|
|
||||||
|
|
||||||
{
|
|
||||||
var it = self.temps.valueIterator();
|
|
||||||
while (it.next()) |global| {
|
|
||||||
v8.v8__Global__Reset(global);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,10 +17,11 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const Session = @import("../Session.zig");
|
|
||||||
const log = @import("../../log.zig");
|
const log = @import("../../log.zig");
|
||||||
const string = @import("../../string.zig");
|
const string = @import("../../string.zig");
|
||||||
|
|
||||||
|
const Session = @import("../Session.zig");
|
||||||
|
|
||||||
const js = @import("js.zig");
|
const js = @import("js.zig");
|
||||||
const bridge = @import("bridge.zig");
|
const bridge = @import("bridge.zig");
|
||||||
const Caller = @import("Caller.zig");
|
const Caller = @import("Caller.zig");
|
||||||
@@ -213,7 +214,8 @@ pub fn mapZigInstanceToJs(self: *const Local, js_obj_handle: ?*const v8.Object,
|
|||||||
.pointer => |ptr| {
|
.pointer => |ptr| {
|
||||||
const resolved = resolveValue(value);
|
const resolved = resolveValue(value);
|
||||||
|
|
||||||
const gop = try ctx.addIdentity(@intFromPtr(resolved.ptr));
|
const resolved_ptr_id = @intFromPtr(resolved.ptr);
|
||||||
|
const gop = try ctx.addIdentity(resolved_ptr_id);
|
||||||
if (gop.found_existing) {
|
if (gop.found_existing) {
|
||||||
// we've seen this instance before, return the same object
|
// we've seen this instance before, return the same object
|
||||||
return (js.Object.Global{ .handle = gop.value_ptr.* }).local(self);
|
return (js.Object.Global{ .handle = gop.value_ptr.* }).local(self);
|
||||||
@@ -262,31 +264,27 @@ pub fn mapZigInstanceToJs(self: *const Local, js_obj_handle: ?*const v8.Object,
|
|||||||
// dont' use js_obj.persist(), because we don't want to track this in
|
// dont' use js_obj.persist(), because we don't want to track this in
|
||||||
// context.global_objects, we want to track it in context.identity_map.
|
// context.global_objects, we want to track it in context.identity_map.
|
||||||
v8.v8__Global__New(isolate.handle, js_obj.handle, gop.value_ptr);
|
v8.v8__Global__New(isolate.handle, js_obj.handle, gop.value_ptr);
|
||||||
if (@hasDecl(JsApi.Meta, "finalizer")) {
|
if (resolved.finalizer) |finalizer| {
|
||||||
// It would be great if resolved knew the resolved type, but I
|
const finalizer_ptr_id = finalizer.ptr_id;
|
||||||
// can't figure out how to make that work, since it depends on
|
finalizer.acquireRef(finalizer_ptr_id);
|
||||||
// the [runtime] `value`.
|
|
||||||
// We need the resolved finalizer, which we have in resolved.
|
|
||||||
//
|
|
||||||
// The above if statement would be more clear as:
|
|
||||||
// if (resolved.finalizer_from_v8) |finalizer| {
|
|
||||||
// But that's a runtime check.
|
|
||||||
// Instead, we check if the base has finalizer. The assumption
|
|
||||||
// here is that if a resolve type has a finalizer, then the base
|
|
||||||
// should have a finalizer too.
|
|
||||||
const fc = try ctx.createFinalizerCallback(gop.value_ptr.*, resolved.ptr, resolved.finalizer_from_zig.?);
|
|
||||||
{
|
|
||||||
errdefer fc.deinit();
|
|
||||||
try ctx.identity.finalizer_callbacks.put(ctx.identity_arena, @intFromPtr(resolved.ptr), fc);
|
|
||||||
}
|
|
||||||
|
|
||||||
conditionallyReference(value);
|
const session = ctx.session;
|
||||||
if (@hasDecl(JsApi.Meta, "weak")) {
|
const finalizer_gop = try session.finalizer_callbacks.getOrPut(session.page_arena, finalizer_ptr_id);
|
||||||
if (comptime IS_DEBUG) {
|
if (finalizer_gop.found_existing == false) {
|
||||||
std.debug.assert(JsApi.Meta.weak == true);
|
// This is the first context (and very likely only one) to
|
||||||
}
|
// see this Zig instance. We need to create the FinalizerCallback
|
||||||
v8.v8__Global__SetWeakFinalizer(gop.value_ptr, fc, resolved.finalizer_from_v8, v8.kParameter);
|
// so that we can cleanup on page reset if v8 doesn't finalize.
|
||||||
|
errdefer _ = session.finalizer_callbacks.remove(finalizer_ptr_id);
|
||||||
|
finalizer_gop.value_ptr.* = try self.createFinalizerCallback(resolved_ptr_id, finalizer_ptr_id, finalizer.deinit);
|
||||||
}
|
}
|
||||||
|
const fc = finalizer_gop.value_ptr.*;
|
||||||
|
const identity_finalizer = try fc.arena.create(Session.FinalizerCallback.Identity);
|
||||||
|
identity_finalizer.* = .{
|
||||||
|
.fc = fc,
|
||||||
|
.identity = ctx.identity,
|
||||||
|
};
|
||||||
|
|
||||||
|
v8.v8__Global__SetWeakFinalizer(gop.value_ptr, identity_finalizer, finalizer.release, v8.kParameter);
|
||||||
}
|
}
|
||||||
return js_obj;
|
return js_obj;
|
||||||
},
|
},
|
||||||
@@ -1121,12 +1119,19 @@ fn jsUnsignedIntToZig(comptime T: type, max: comptime_int, maybe: u32) !T {
|
|||||||
// This function recursively walks the _type union field (if there is one) to
|
// This function recursively walks the _type union field (if there is one) to
|
||||||
// get the most specific class_id possible.
|
// get the most specific class_id possible.
|
||||||
const Resolved = struct {
|
const Resolved = struct {
|
||||||
weak: bool,
|
|
||||||
ptr: *anyopaque,
|
ptr: *anyopaque,
|
||||||
class_id: u16,
|
class_id: u16,
|
||||||
prototype_chain: []const @import("TaggedOpaque.zig").PrototypeChainEntry,
|
prototype_chain: []const @import("TaggedOpaque.zig").PrototypeChainEntry,
|
||||||
finalizer_from_v8: ?*const fn (handle: ?*const v8.WeakCallbackInfo) callconv(.c) void = null,
|
finalizer: ?Finalizer,
|
||||||
finalizer_from_zig: ?*const fn (ptr: *anyopaque, session: *Session) void = null,
|
|
||||||
|
const Finalizer = struct {
|
||||||
|
// Resolved.ptr is the most specific value in a chain (e.g. IFrame, not EventTarget, Node, ...)
|
||||||
|
// Finalizer.ptr_id is the most specific value in a chain that defines an acquireRef
|
||||||
|
ptr_id: usize,
|
||||||
|
deinit: *const fn (ptr_id: usize, session: *Session) void,
|
||||||
|
acquireRef: *const fn (ptr_id: usize) void,
|
||||||
|
release: *const fn (handle: ?*const v8.WeakCallbackInfo) callconv(.c) void,
|
||||||
|
};
|
||||||
};
|
};
|
||||||
pub fn resolveValue(value: anytype) Resolved {
|
pub fn resolveValue(value: anytype) Resolved {
|
||||||
const T = bridge.Struct(@TypeOf(value));
|
const T = bridge.Struct(@TypeOf(value));
|
||||||
@@ -1153,27 +1158,85 @@ pub fn resolveValue(value: anytype) Resolved {
|
|||||||
unreachable;
|
unreachable;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolveT(comptime T: type, value: *anyopaque) Resolved {
|
fn resolveT(comptime T: type, value: *T) Resolved {
|
||||||
const Meta = T.JsApi.Meta;
|
const Meta = T.JsApi.Meta;
|
||||||
return .{
|
return .{
|
||||||
.ptr = value,
|
.ptr = value,
|
||||||
.class_id = Meta.class_id,
|
.class_id = Meta.class_id,
|
||||||
.prototype_chain = &Meta.prototype_chain,
|
.prototype_chain = &Meta.prototype_chain,
|
||||||
.weak = if (@hasDecl(Meta, "weak")) Meta.weak else false,
|
.finalizer = blk: {
|
||||||
.finalizer_from_v8 = if (@hasDecl(Meta, "finalizer")) Meta.finalizer.from_v8 else null,
|
const FT = (comptime findFinalizerType(T)) orelse break :blk null;
|
||||||
.finalizer_from_zig = if (@hasDecl(Meta, "finalizer")) Meta.finalizer.from_zig else null,
|
const getFinalizerPtr = comptime finalizerPtrGetter(T, FT);
|
||||||
|
const finalizer_ptr = getFinalizerPtr(value);
|
||||||
|
|
||||||
|
const Wrap = struct {
|
||||||
|
fn deinit(ptr_id: usize, session: *Session) void {
|
||||||
|
FT.deinit(@ptrFromInt(ptr_id), session);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn acquireRef(ptr_id: usize) void {
|
||||||
|
FT.acquireRef(@ptrFromInt(ptr_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn release(handle: ?*const v8.WeakCallbackInfo) callconv(.c) void {
|
||||||
|
const ptr = v8.v8__WeakCallbackInfo__GetParameter(handle.?).?;
|
||||||
|
const identity_finalizer: *Session.FinalizerCallback.Identity = @ptrCast(@alignCast(ptr));
|
||||||
|
|
||||||
|
const fc = identity_finalizer.fc;
|
||||||
|
if (identity_finalizer.identity.identity_map.fetchRemove(fc.resolved_ptr_id)) |kv| {
|
||||||
|
var global = kv.value;
|
||||||
|
v8.v8__Global__Reset(&global);
|
||||||
|
}
|
||||||
|
|
||||||
|
FT.releaseRef(@ptrFromInt(fc.finalizer_ptr_id), fc.session);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
break :blk .{
|
||||||
|
.ptr_id = @intFromPtr(finalizer_ptr),
|
||||||
|
.deinit = Wrap.deinit,
|
||||||
|
.acquireRef = Wrap.acquireRef,
|
||||||
|
.release = Wrap.release,
|
||||||
|
};
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
fn conditionallyReference(value: anytype) void {
|
// Start at the "resolved" type (the most specific) and work our way up the
|
||||||
const T = bridge.Struct(@TypeOf(value));
|
// prototype chain looking for the type that defines acquireRef
|
||||||
if (@hasDecl(T, "acquireRef")) {
|
fn findFinalizerType(comptime T: type) ?type {
|
||||||
value.acquireRef();
|
const S = bridge.Struct(T);
|
||||||
return;
|
if (@hasDecl(S, "acquireRef")) {
|
||||||
|
return S;
|
||||||
}
|
}
|
||||||
if (@hasField(T, "_proto")) {
|
if (@hasField(S, "_proto")) {
|
||||||
conditionallyReference(value._proto);
|
const ProtoPtr = std.meta.fieldInfo(S, ._proto).type;
|
||||||
|
const ProtoChild = @typeInfo(ProtoPtr).pointer.child;
|
||||||
|
return findFinalizerType(ProtoChild);
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate a function that follows the _proto pointer chain to get to the finalizer type
|
||||||
|
fn finalizerPtrGetter(comptime T: type, comptime FT: type) *const fn (*T) *FT {
|
||||||
|
const S = bridge.Struct(T);
|
||||||
|
if (S == FT) {
|
||||||
|
return struct {
|
||||||
|
fn get(v: *T) *FT {
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
}.get;
|
||||||
|
}
|
||||||
|
if (@hasField(S, "_proto")) {
|
||||||
|
const ProtoPtr = std.meta.fieldInfo(S, ._proto).type;
|
||||||
|
const ProtoChild = @typeInfo(ProtoPtr).pointer.child;
|
||||||
|
const childGetter = comptime finalizerPtrGetter(ProtoChild, FT);
|
||||||
|
return struct {
|
||||||
|
fn get(v: *T) *FT {
|
||||||
|
return childGetter(v._proto);
|
||||||
|
}
|
||||||
|
}.get;
|
||||||
|
}
|
||||||
|
@compileError("Cannot find path from " ++ @typeName(T) ++ " to " ++ @typeName(FT));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn stackTrace(self: *const Local) !?[]const u8 {
|
pub fn stackTrace(self: *const Local) !?[]const u8 {
|
||||||
@@ -1381,6 +1444,34 @@ pub fn debugContextId(self: *const Local) i32 {
|
|||||||
return v8.v8__Context__DebugContextId(self.handle);
|
return v8.v8__Context__DebugContextId(self.handle);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn createFinalizerCallback(
|
||||||
|
self: *const Local,
|
||||||
|
|
||||||
|
// Key in identity map
|
||||||
|
// The most specific value (KeyboardEvent, not Event)
|
||||||
|
resolved_ptr_id: usize,
|
||||||
|
|
||||||
|
// The most specific value where finalizers are defined
|
||||||
|
// What actually gets acquired / released / deinit
|
||||||
|
finalizer_ptr_id: usize,
|
||||||
|
deinit: *const fn (ptr_id: usize, session: *Session) void,
|
||||||
|
) !*Session.FinalizerCallback {
|
||||||
|
const session = self.ctx.session;
|
||||||
|
|
||||||
|
const arena = try session.getArena(.{ .debug = "FinalizerCallback" });
|
||||||
|
errdefer session.releaseArena(arena);
|
||||||
|
|
||||||
|
const fc = try arena.create(Session.FinalizerCallback);
|
||||||
|
fc.* = .{
|
||||||
|
.arena = arena,
|
||||||
|
.session = session,
|
||||||
|
._deinit = deinit,
|
||||||
|
.resolved_ptr_id = resolved_ptr_id,
|
||||||
|
.finalizer_ptr_id = finalizer_ptr_id,
|
||||||
|
};
|
||||||
|
return fc;
|
||||||
|
}
|
||||||
|
|
||||||
// Encapsulates a Local and a HandleScope. When we're going from V8->Zig
|
// Encapsulates a Local and a HandleScope. When we're going from V8->Zig
|
||||||
// we easily get both a Local and a HandleScope via Caller.init.
|
// we easily get both a Local and a HandleScope via Caller.init.
|
||||||
// But when we're going from Zig -> V8, things are more complicated.
|
// But when we're going from Zig -> V8, things are more complicated.
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ fn _persist(self: *const Promise, comptime is_global: bool) !(if (is_global) Glo
|
|||||||
return .{ .handle = global, .temps = {} };
|
return .{ .handle = global, .temps = {} };
|
||||||
}
|
}
|
||||||
try ctx.trackTemp(global);
|
try ctx.trackTemp(global);
|
||||||
return .{ .handle = global, .temps = &ctx.identity.temps };
|
return .{ .handle = global, .temps = &ctx.session.temps };
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const Temp = G(.temp);
|
pub const Temp = G(.temp);
|
||||||
|
|||||||
@@ -303,7 +303,7 @@ fn _persist(self: *const Value, comptime is_global: bool) !(if (is_global) Globa
|
|||||||
return .{ .handle = global, .temps = {} };
|
return .{ .handle = global, .temps = {} };
|
||||||
}
|
}
|
||||||
try ctx.trackTemp(global);
|
try ctx.trackTemp(global);
|
||||||
return .{ .handle = global, .temps = &ctx.identity.temps };
|
return .{ .handle = global, .temps = &ctx.session.temps };
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn toZig(self: Value, comptime T: type) !T {
|
pub fn toZig(self: Value, comptime T: type) !T {
|
||||||
|
|||||||
@@ -101,34 +101,19 @@ pub fn Builder(comptime T: type) type {
|
|||||||
}
|
}
|
||||||
return entries;
|
return entries;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn finalizer(comptime func: *const fn (self: *T, shutdown: bool, session: *Session) void) Finalizer {
|
|
||||||
return .{
|
|
||||||
.from_zig = struct {
|
|
||||||
fn wrap(ptr: *anyopaque, session: *Session) void {
|
|
||||||
func(@ptrCast(@alignCast(ptr)), true, session);
|
|
||||||
}
|
|
||||||
}.wrap,
|
|
||||||
|
|
||||||
.from_v8 = struct {
|
|
||||||
fn wrap(handle: ?*const v8.WeakCallbackInfo) callconv(.c) void {
|
|
||||||
const ptr = v8.v8__WeakCallbackInfo__GetParameter(handle.?).?;
|
|
||||||
const fc: *Session.FinalizerCallback = @ptrCast(@alignCast(ptr));
|
|
||||||
|
|
||||||
const value_ptr = fc.ptr;
|
|
||||||
if (fc.identity.finalizer_callbacks.contains(@intFromPtr(value_ptr))) {
|
|
||||||
func(@ptrCast(@alignCast(value_ptr)), false, fc.session);
|
|
||||||
fc.releaseIdentity();
|
|
||||||
} else {
|
|
||||||
// A bit weird, but v8 _requires_ that we release it
|
|
||||||
// If we don't. We'll 100% crash.
|
|
||||||
v8.v8__Global__Reset(&fc.global);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}.wrap,
|
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn releaseRef(comptime T: type, ptr_id: usize, session: *Session) void {
|
||||||
|
if (@hasDecl(T, "releaseRef")) {
|
||||||
|
T.releaseRef(@ptrFromInt(ptr_id), session);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
};
|
if (@hasField(T, "_proto")) {
|
||||||
|
releaseRef(Struct(std.meta.fieldInfo(T, ._proto).type), ptr_id, session);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
@compileError(@typeName(T) ++ " marked with finalizer without an acquireRef in its prototype chain");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const Constructor = struct {
|
pub const Constructor = struct {
|
||||||
@@ -411,17 +396,6 @@ pub const Property = struct {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const Finalizer = struct {
|
|
||||||
// The finalizer wrapper when called from Zig. This is only called on
|
|
||||||
// Origin.deinit
|
|
||||||
from_zig: *const fn (ctx: *anyopaque, session: *Session) void,
|
|
||||||
|
|
||||||
// The finalizer wrapper when called from V8. This may never be called
|
|
||||||
// (hence why we fallback to calling in Origin.deinit). If it is called,
|
|
||||||
// it is only ever called after we SetWeak on the Global.
|
|
||||||
from_v8: *const fn (?*const v8.WeakCallbackInfo) callconv(.c) void,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub fn unknownWindowPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
pub fn unknownWindowPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8.PropertyCallbackInfo) callconv(.c) u8 {
|
||||||
const v8_isolate = v8.v8__PropertyCallbackInfo__GetIsolate(handle).?;
|
const v8_isolate = v8.v8__PropertyCallbackInfo__GetIsolate(handle).?;
|
||||||
var caller: Caller = undefined;
|
var caller: Caller = undefined;
|
||||||
|
|||||||
@@ -148,3 +148,13 @@
|
|||||||
|
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<script id=identity>
|
||||||
|
{
|
||||||
|
const element = document.createElement('canvas');
|
||||||
|
const ctx = element.getContext('2d');
|
||||||
|
|
||||||
|
testing.expectTrue(ctx === element.getContext('2d'));
|
||||||
|
testing.expectEqual(null, element.getContext('webgl'));
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|||||||
@@ -85,3 +85,13 @@
|
|||||||
loseContext.restoreContext();
|
loseContext.restoreContext();
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<script id=identity>
|
||||||
|
{
|
||||||
|
const element = document.createElement('canvas');
|
||||||
|
const ctx = element.getContext('webgl');
|
||||||
|
|
||||||
|
testing.expectTrue(ctx === element.getContext('webgl'));
|
||||||
|
testing.expectEqual(null, element.getContext('2d'));
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|||||||
@@ -17,6 +17,8 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
|
|
||||||
const js = @import("../js/js.zig");
|
const js = @import("../js/js.zig");
|
||||||
|
|
||||||
const Session = @import("../Session.zig");
|
const Session = @import("../Session.zig");
|
||||||
@@ -31,7 +33,7 @@ const AbstractRange = @This();
|
|||||||
|
|
||||||
pub const _prototype_root = true;
|
pub const _prototype_root = true;
|
||||||
|
|
||||||
_rc: u8,
|
_rc: lp.RC(u8) = .{},
|
||||||
_type: Type,
|
_type: Type,
|
||||||
_page_id: u32,
|
_page_id: u32,
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
@@ -44,24 +46,18 @@ _start_container: *Node,
|
|||||||
_range_link: std.DoublyLinkedList.Node = .{},
|
_range_link: std.DoublyLinkedList.Node = .{},
|
||||||
|
|
||||||
pub fn acquireRef(self: *AbstractRange) void {
|
pub fn acquireRef(self: *AbstractRange) void {
|
||||||
self._rc += 1;
|
self._rc.acquire();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *AbstractRange, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *AbstractRange, session: *Session) void {
|
||||||
_ = shutdown;
|
|
||||||
const rc = self._rc;
|
|
||||||
if (comptime IS_DEBUG) {
|
|
||||||
std.debug.assert(rc != 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rc == 1) {
|
|
||||||
if (session.findPageById(self._page_id)) |page| {
|
if (session.findPageById(self._page_id)) |page| {
|
||||||
page._live_ranges.remove(&self._range_link);
|
page._live_ranges.remove(&self._range_link);
|
||||||
}
|
}
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
self._rc = rc - 1;
|
pub fn releaseRef(self: *AbstractRange, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const Type = union(enum) {
|
pub const Type = union(enum) {
|
||||||
@@ -338,8 +334,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "AbstractRange";
|
pub const name = "AbstractRange";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(AbstractRange.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const startContainer = bridge.accessor(AbstractRange.getStartContainer, null, .{});
|
pub const startContainer = bridge.accessor(AbstractRange.getStartContainer, null, .{});
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const Writer = std.Io.Writer;
|
const lp = @import("lightpanda");
|
||||||
|
|
||||||
const js = @import("../js/js.zig");
|
const js = @import("../js/js.zig");
|
||||||
const Page = @import("../Page.zig");
|
const Page = @import("../Page.zig");
|
||||||
@@ -25,6 +25,7 @@ const Session = @import("../Session.zig");
|
|||||||
|
|
||||||
const Mime = @import("../Mime.zig");
|
const Mime = @import("../Mime.zig");
|
||||||
|
|
||||||
|
const Writer = std.Io.Writer;
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
|
|
||||||
/// https://w3c.github.io/FileAPI/#blob-section
|
/// https://w3c.github.io/FileAPI/#blob-section
|
||||||
@@ -34,6 +35,7 @@ const Blob = @This();
|
|||||||
pub const _prototype_root = true;
|
pub const _prototype_root = true;
|
||||||
|
|
||||||
_type: Type,
|
_type: Type,
|
||||||
|
_rc: lp.RC(u32),
|
||||||
|
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
|
|
||||||
@@ -120,6 +122,7 @@ pub fn initWithMimeValidation(
|
|||||||
|
|
||||||
const self = try arena.create(Blob);
|
const self = try arena.create(Blob);
|
||||||
self.* = .{
|
self.* = .{
|
||||||
|
._rc = .{},
|
||||||
._arena = arena,
|
._arena = arena,
|
||||||
._type = .generic,
|
._type = .generic,
|
||||||
._slice = data,
|
._slice = data,
|
||||||
@@ -128,11 +131,18 @@ pub fn initWithMimeValidation(
|
|||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *Blob, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *Blob, session: *Session) void {
|
||||||
_ = shutdown;
|
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *Blob, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *Blob) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
const largest_vector = @max(std.simd.suggestVectorLength(u8) orelse 1, 8);
|
const largest_vector = @max(std.simd.suggestVectorLength(u8) orelse 1, 8);
|
||||||
/// Array of possible vector sizes for the current arch in decrementing order.
|
/// Array of possible vector sizes for the current arch in decrementing order.
|
||||||
/// We may move this to some file for SIMD helpers in the future.
|
/// We may move this to some file for SIMD helpers in the future.
|
||||||
@@ -325,8 +335,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "Blob";
|
pub const name = "Blob";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(Blob.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(Blob.init, .{});
|
pub const constructor = bridge.constructor(Blob.init, .{});
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ pub fn fromError(err: anyerror) ?DOMException {
|
|||||||
error.TimeoutError => .{ ._code = .timeout_error },
|
error.TimeoutError => .{ ._code = .timeout_error },
|
||||||
error.InvalidNodeType => .{ ._code = .invalid_node_type_error },
|
error.InvalidNodeType => .{ ._code = .invalid_node_type_error },
|
||||||
error.DataClone => .{ ._code = .data_clone_error },
|
error.DataClone => .{ ._code = .data_clone_error },
|
||||||
|
error.InvalidAccessError => .{ ._code = .invalid_access_error },
|
||||||
else => null,
|
else => null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ _fonts: ?*FontFaceSet = null,
|
|||||||
_write_insertion_point: ?*Node = null,
|
_write_insertion_point: ?*Node = null,
|
||||||
_script_created_parser: ?Parser.Streaming = null,
|
_script_created_parser: ?Parser.Streaming = null,
|
||||||
_adopted_style_sheets: ?js.Object.Global = null,
|
_adopted_style_sheets: ?js.Object.Global = null,
|
||||||
_selection: Selection = .init,
|
_selection: Selection = .{ ._rc = .init(1) },
|
||||||
|
|
||||||
// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#throw-on-dynamic-markup-insertion-counter
|
// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#throw-on-dynamic-markup-insertion-counter
|
||||||
// Incremented during custom element reactions when parsing. When > 0,
|
// Incremented during custom element reactions when parsing. When > 0,
|
||||||
|
|||||||
@@ -17,6 +17,8 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
|
|
||||||
const js = @import("../js/js.zig");
|
const js = @import("../js/js.zig");
|
||||||
|
|
||||||
const Page = @import("../Page.zig");
|
const Page = @import("../Page.zig");
|
||||||
@@ -55,7 +57,7 @@ _is_trusted: bool = false,
|
|||||||
// - 0: no reference, always a transient state going to either 1 or about to be deinit'd
|
// - 0: no reference, always a transient state going to either 1 or about to be deinit'd
|
||||||
// - 1: either zig or v8 have a reference
|
// - 1: either zig or v8 have a reference
|
||||||
// - 2: both zig and v8 have a reference
|
// - 2: both zig and v8 have a reference
|
||||||
_rc: u8 = 0,
|
_rc: lp.RC(u8) = .{},
|
||||||
|
|
||||||
pub const EventPhase = enum(u8) {
|
pub const EventPhase = enum(u8) {
|
||||||
none = 0,
|
none = 0,
|
||||||
@@ -139,25 +141,16 @@ pub fn initEvent(
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn acquireRef(self: *Event) void {
|
pub fn acquireRef(self: *Event) void {
|
||||||
self._rc += 1;
|
self._rc.acquire();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *Event, shutdown: bool, session: *Session) void {
|
/// Force cleanup on Session shutdown.
|
||||||
if (shutdown) {
|
pub fn deinit(self: *Event, session: *Session) void {
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const rc = self._rc;
|
pub fn releaseRef(self: *Event, session: *Session) void {
|
||||||
if (comptime IS_DEBUG) {
|
self._rc.release(self, session);
|
||||||
std.debug.assert(rc != 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rc == 1) {
|
|
||||||
session.releaseArena(self._arena);
|
|
||||||
} else {
|
|
||||||
self._rc = rc - 1;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn as(self: *Event, comptime T: type) *T {
|
pub fn as(self: *Event, comptime T: type) *T {
|
||||||
@@ -440,8 +433,6 @@ pub const JsApi = struct {
|
|||||||
|
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(Event.deinit);
|
|
||||||
pub const enumerable = false;
|
pub const enumerable = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ pub fn dispatchEvent(self: *EventTarget, event: *Event, page: *Page) !bool {
|
|||||||
event._is_trusted = false;
|
event._is_trusted = false;
|
||||||
|
|
||||||
event.acquireRef();
|
event.acquireRef();
|
||||||
defer event.deinit(false, page._session);
|
defer _ = event.releaseRef(page._session);
|
||||||
try page._event_manager.dispatch(self, event);
|
try page._event_manager.dispatch(self, event);
|
||||||
return !event._cancelable or !event._prevent_default;
|
return !event._cancelable or !event._prevent_default;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
|
|
||||||
const js = @import("../js/js.zig");
|
const js = @import("../js/js.zig");
|
||||||
const Page = @import("../Page.zig");
|
const Page = @import("../Page.zig");
|
||||||
@@ -26,7 +27,6 @@ const Blob = @import("Blob.zig");
|
|||||||
|
|
||||||
const File = @This();
|
const File = @This();
|
||||||
|
|
||||||
/// `File` inherits `Blob`.
|
|
||||||
_proto: *Blob,
|
_proto: *Blob,
|
||||||
|
|
||||||
// TODO: Implement File API.
|
// TODO: Implement File API.
|
||||||
@@ -36,10 +36,6 @@ pub fn init(page: *Page) !*File {
|
|||||||
return page._factory.blob(arena, File{ ._proto = undefined });
|
return page._factory.blob(arena, File{ ._proto = undefined });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *File, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const JsApi = struct {
|
pub const JsApi = struct {
|
||||||
pub const bridge = js.Bridge(File);
|
pub const bridge = js.Bridge(File);
|
||||||
|
|
||||||
@@ -47,8 +43,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "File";
|
pub const name = "File";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(File.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(File.init, .{});
|
pub const constructor = bridge.constructor(File.init, .{});
|
||||||
|
|||||||
@@ -17,6 +17,8 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
|
|
||||||
const js = @import("../js/js.zig");
|
const js = @import("../js/js.zig");
|
||||||
|
|
||||||
const Page = @import("../Page.zig");
|
const Page = @import("../Page.zig");
|
||||||
@@ -31,6 +33,7 @@ const Allocator = std.mem.Allocator;
|
|||||||
/// https://developer.mozilla.org/en-US/docs/Web/API/FileReader
|
/// https://developer.mozilla.org/en-US/docs/Web/API/FileReader
|
||||||
const FileReader = @This();
|
const FileReader = @This();
|
||||||
|
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_page: *Page,
|
_page: *Page,
|
||||||
_proto: *EventTarget,
|
_proto: *EventTarget,
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
@@ -70,7 +73,7 @@ pub fn init(page: *Page) !*FileReader {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *FileReader, _: bool, session: *Session) void {
|
pub fn deinit(self: *FileReader, session: *Session) void {
|
||||||
if (self._on_abort) |func| func.release();
|
if (self._on_abort) |func| func.release();
|
||||||
if (self._on_error) |func| func.release();
|
if (self._on_error) |func| func.release();
|
||||||
if (self._on_load) |func| func.release();
|
if (self._on_load) |func| func.release();
|
||||||
@@ -81,6 +84,14 @@ pub fn deinit(self: *FileReader, _: bool, session: *Session) void {
|
|||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *FileReader, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *FileReader) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
fn asEventTarget(self: *FileReader) *EventTarget {
|
fn asEventTarget(self: *FileReader) *EventTarget {
|
||||||
return self._proto;
|
return self._proto;
|
||||||
}
|
}
|
||||||
@@ -309,8 +320,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "FileReader";
|
pub const name = "FileReader";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(FileReader.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(FileReader.init, .{});
|
pub const constructor = bridge.constructor(FileReader.init, .{});
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
// You should have received a copy of the GNU Affero General Public License
|
// 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/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
|
|
||||||
const js = @import("../js/js.zig");
|
const js = @import("../js/js.zig");
|
||||||
const log = @import("../../log.zig");
|
const log = @import("../../log.zig");
|
||||||
|
|
||||||
@@ -39,6 +41,7 @@ pub fn registerTypes() []const type {
|
|||||||
|
|
||||||
const IntersectionObserver = @This();
|
const IntersectionObserver = @This();
|
||||||
|
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
_callback: js.Function.Temp,
|
_callback: js.Function.Temp,
|
||||||
_observing: std.ArrayList(*Element) = .{},
|
_observing: std.ArrayList(*Element) = .{},
|
||||||
@@ -108,15 +111,22 @@ pub fn init(callback: js.Function.Temp, options: ?ObserverInit, page: *Page) !*I
|
|||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *IntersectionObserver, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *IntersectionObserver, session: *Session) void {
|
||||||
self._callback.release();
|
self._callback.release();
|
||||||
if ((comptime IS_DEBUG) and !shutdown) {
|
for (self._pending_entries.items) |entry| {
|
||||||
std.debug.assert(self._observing.items.len == 0);
|
entry.deinitIfUnused(session);
|
||||||
}
|
}
|
||||||
|
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *IntersectionObserver, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *IntersectionObserver) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn observe(self: *IntersectionObserver, target: *Element, page: *Page) !void {
|
pub fn observe(self: *IntersectionObserver, target: *Element, page: *Page) !void {
|
||||||
// Check if already observing this target
|
// Check if already observing this target
|
||||||
for (self._observing.items) |elem| {
|
for (self._observing.items) |elem| {
|
||||||
@@ -127,7 +137,7 @@ pub fn observe(self: *IntersectionObserver, target: *Element, page: *Page) !void
|
|||||||
|
|
||||||
// Register with page if this is our first observation
|
// Register with page if this is our first observation
|
||||||
if (self._observing.items.len == 0) {
|
if (self._observing.items.len == 0) {
|
||||||
page.js.strongRef(self);
|
self._rc._refs += 1;
|
||||||
try page.registerIntersectionObserver(self);
|
try page.registerIntersectionObserver(self);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,17 +154,19 @@ pub fn observe(self: *IntersectionObserver, target: *Element, page: *Page) !void
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn unobserve(self: *IntersectionObserver, target: *Element, page: *Page) void {
|
pub fn unobserve(self: *IntersectionObserver, target: *Element, page: *Page) void {
|
||||||
|
const original_length = self._observing.items.len;
|
||||||
for (self._observing.items, 0..) |elem, i| {
|
for (self._observing.items, 0..) |elem, i| {
|
||||||
if (elem == target) {
|
if (elem == target) {
|
||||||
_ = self._observing.swapRemove(i);
|
_ = self._observing.swapRemove(i);
|
||||||
_ = self._previous_states.remove(target);
|
_ = self._previous_states.remove(target);
|
||||||
|
|
||||||
// Remove any pending entries for this target
|
// Remove any pending entries for this target.
|
||||||
|
// Entries will be cleaned up by V8 GC via the finalizer.
|
||||||
var j: usize = 0;
|
var j: usize = 0;
|
||||||
while (j < self._pending_entries.items.len) {
|
while (j < self._pending_entries.items.len) {
|
||||||
if (self._pending_entries.items[j]._target == target) {
|
if (self._pending_entries.items[j]._target == target) {
|
||||||
const entry = self._pending_entries.swapRemove(j);
|
const entry = self._pending_entries.swapRemove(j);
|
||||||
entry.deinit(false, page._session);
|
entry.deinitIfUnused(page._session);
|
||||||
} else {
|
} else {
|
||||||
j += 1;
|
j += 1;
|
||||||
}
|
}
|
||||||
@@ -163,21 +175,26 @@ pub fn unobserve(self: *IntersectionObserver, target: *Element, page: *Page) voi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (self._observing.items.len == 0) {
|
if (original_length > 0 and self._observing.items.len == 0) {
|
||||||
page.js.safeWeakRef(self);
|
self._rc._refs -= 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn disconnect(self: *IntersectionObserver, page: *Page) void {
|
pub fn disconnect(self: *IntersectionObserver, page: *Page) void {
|
||||||
page.unregisterIntersectionObserver(self);
|
|
||||||
self._observing.clearRetainingCapacity();
|
|
||||||
self._previous_states.clearRetainingCapacity();
|
|
||||||
|
|
||||||
for (self._pending_entries.items) |entry| {
|
for (self._pending_entries.items) |entry| {
|
||||||
entry.deinit(false, page._session);
|
entry.deinitIfUnused(page._session);
|
||||||
}
|
}
|
||||||
self._pending_entries.clearRetainingCapacity();
|
self._pending_entries.clearRetainingCapacity();
|
||||||
page.js.safeWeakRef(self);
|
self._previous_states.clearRetainingCapacity();
|
||||||
|
|
||||||
|
const observing_count = self._observing.items.len;
|
||||||
|
self._observing.clearRetainingCapacity();
|
||||||
|
|
||||||
|
page.unregisterIntersectionObserver(self);
|
||||||
|
|
||||||
|
if (observing_count > 0) {
|
||||||
|
_ = self.releaseRef(page._session);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn takeRecords(self: *IntersectionObserver, page: *Page) ![]*IntersectionObserverEntry {
|
pub fn takeRecords(self: *IntersectionObserver, page: *Page) ![]*IntersectionObserverEntry {
|
||||||
@@ -268,7 +285,6 @@ fn checkIntersection(self: *IntersectionObserver, target: *Element, page: *Page)
|
|||||||
._bounding_client_rect = try page._factory.create(data.bounding_client_rect),
|
._bounding_client_rect = try page._factory.create(data.bounding_client_rect),
|
||||||
._intersection_ratio = data.intersection_ratio,
|
._intersection_ratio = data.intersection_ratio,
|
||||||
};
|
};
|
||||||
|
|
||||||
try self._pending_entries.append(self._arena, entry);
|
try self._pending_entries.append(self._arena, entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,6 +326,7 @@ pub fn deliverEntries(self: *IntersectionObserver, page: *Page) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub const IntersectionObserverEntry = struct {
|
pub const IntersectionObserverEntry = struct {
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
_time: f64,
|
_time: f64,
|
||||||
_target: *Element,
|
_target: *Element,
|
||||||
@@ -319,10 +336,25 @@ pub const IntersectionObserverEntry = struct {
|
|||||||
_intersection_ratio: f64,
|
_intersection_ratio: f64,
|
||||||
_is_intersecting: bool,
|
_is_intersecting: bool,
|
||||||
|
|
||||||
pub fn deinit(self: *IntersectionObserverEntry, _: bool, session: *Session) void {
|
pub fn deinit(self: *IntersectionObserverEntry, session: *Session) void {
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn deinitIfUnused(self: *IntersectionObserverEntry, session: *Session) void {
|
||||||
|
if (self._rc._refs == 0) {
|
||||||
|
// hasn't been handed to JS yet.
|
||||||
|
self.deinit(session);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *IntersectionObserverEntry, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *IntersectionObserverEntry) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn getTarget(self: *const IntersectionObserverEntry) *Element {
|
pub fn getTarget(self: *const IntersectionObserverEntry) *Element {
|
||||||
return self._target;
|
return self._target;
|
||||||
}
|
}
|
||||||
@@ -358,8 +390,6 @@ pub const IntersectionObserverEntry = struct {
|
|||||||
pub const name = "IntersectionObserverEntry";
|
pub const name = "IntersectionObserverEntry";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(IntersectionObserverEntry.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const target = bridge.accessor(IntersectionObserverEntry.getTarget, null, .{});
|
pub const target = bridge.accessor(IntersectionObserverEntry.getTarget, null, .{});
|
||||||
@@ -379,8 +409,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "IntersectionObserver";
|
pub const name = "IntersectionObserver";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(IntersectionObserver.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(init, .{});
|
pub const constructor = bridge.constructor(init, .{});
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
const String = @import("../../string.zig").String;
|
const String = @import("../../string.zig").String;
|
||||||
|
|
||||||
const js = @import("../js/js.zig");
|
const js = @import("../js/js.zig");
|
||||||
@@ -39,6 +40,7 @@ pub fn registerTypes() []const type {
|
|||||||
|
|
||||||
const MutationObserver = @This();
|
const MutationObserver = @This();
|
||||||
|
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
_callback: js.Function.Temp,
|
_callback: js.Function.Temp,
|
||||||
_observing: std.ArrayList(Observing) = .{},
|
_observing: std.ArrayList(Observing) = .{},
|
||||||
@@ -85,15 +87,20 @@ pub fn init(callback: js.Function.Temp, page: *Page) !*MutationObserver {
|
|||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *MutationObserver, shutdown: bool, session: *Session) void {
|
/// Force cleanup on Session shutdown.
|
||||||
|
pub fn deinit(self: *MutationObserver, session: *Session) void {
|
||||||
self._callback.release();
|
self._callback.release();
|
||||||
if ((comptime IS_DEBUG) and !shutdown) {
|
|
||||||
std.debug.assert(self._observing.items.len == 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *MutationObserver, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *MutationObserver) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn observe(self: *MutationObserver, target: *Node, options: ObserveOptions, page: *Page) !void {
|
pub fn observe(self: *MutationObserver, target: *Node, options: ObserveOptions, page: *Page) !void {
|
||||||
const arena = self._arena;
|
const arena = self._arena;
|
||||||
|
|
||||||
@@ -158,7 +165,7 @@ pub fn observe(self: *MutationObserver, target: *Node, options: ObserveOptions,
|
|||||||
|
|
||||||
// Register with page if this is our first observation
|
// Register with page if this is our first observation
|
||||||
if (self._observing.items.len == 0) {
|
if (self._observing.items.len == 0) {
|
||||||
page.js.strongRef(self);
|
self._rc._refs += 1;
|
||||||
try page.registerMutationObserver(self);
|
try page.registerMutationObserver(self);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,13 +176,17 @@ pub fn observe(self: *MutationObserver, target: *Node, options: ObserveOptions,
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn disconnect(self: *MutationObserver, page: *Page) void {
|
pub fn disconnect(self: *MutationObserver, page: *Page) void {
|
||||||
page.unregisterMutationObserver(self);
|
|
||||||
self._observing.clearRetainingCapacity();
|
|
||||||
for (self._pending_records.items) |record| {
|
for (self._pending_records.items) |record| {
|
||||||
record.deinit(false, page._session);
|
_ = record.releaseRef(page._session);
|
||||||
}
|
}
|
||||||
self._pending_records.clearRetainingCapacity();
|
self._pending_records.clearRetainingCapacity();
|
||||||
page.js.safeWeakRef(self);
|
const observing_count = self._observing.items.len;
|
||||||
|
self._observing.clearRetainingCapacity();
|
||||||
|
|
||||||
|
if (observing_count > 0) {
|
||||||
|
_ = self.releaseRef(page._session);
|
||||||
|
}
|
||||||
|
page.unregisterMutationObserver(self);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn takeRecords(self: *MutationObserver, page: *Page) ![]*MutationRecord {
|
pub fn takeRecords(self: *MutationObserver, page: *Page) ![]*MutationRecord {
|
||||||
@@ -348,6 +359,7 @@ pub fn deliverRecords(self: *MutationObserver, page: *Page) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub const MutationRecord = struct {
|
pub const MutationRecord = struct {
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_type: Type,
|
_type: Type,
|
||||||
_target: *Node,
|
_target: *Node,
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
@@ -364,10 +376,18 @@ pub const MutationRecord = struct {
|
|||||||
characterData,
|
characterData,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn deinit(self: *MutationRecord, _: bool, session: *Session) void {
|
pub fn deinit(self: *MutationRecord, session: *Session) void {
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *MutationRecord, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *MutationRecord) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn getType(self: *const MutationRecord) []const u8 {
|
pub fn getType(self: *const MutationRecord) []const u8 {
|
||||||
return switch (self._type) {
|
return switch (self._type) {
|
||||||
.attributes => "attributes",
|
.attributes => "attributes",
|
||||||
@@ -418,8 +438,6 @@ pub const MutationRecord = struct {
|
|||||||
pub const name = "MutationRecord";
|
pub const name = "MutationRecord";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(MutationRecord.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const @"type" = bridge.accessor(MutationRecord.getType, null, .{});
|
pub const @"type" = bridge.accessor(MutationRecord.getType, null, .{});
|
||||||
@@ -441,8 +459,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "MutationObserver";
|
pub const name = "MutationObserver";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(MutationObserver.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(MutationObserver.init, .{});
|
pub const constructor = bridge.constructor(MutationObserver.init, .{});
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
const js = @import("../js/js.zig");
|
const js = @import("../js/js.zig");
|
||||||
const Page = @import("../Page.zig");
|
const Page = @import("../Page.zig");
|
||||||
const Session = @import("../Session.zig");
|
const Session = @import("../Session.zig");
|
||||||
@@ -50,14 +51,23 @@ pub fn query(_: *const Permissions, qd: QueryDescriptor, page: *Page) !js.Promis
|
|||||||
}
|
}
|
||||||
|
|
||||||
const PermissionStatus = struct {
|
const PermissionStatus = struct {
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
_name: []const u8,
|
_name: []const u8,
|
||||||
_state: []const u8,
|
_state: []const u8,
|
||||||
|
|
||||||
pub fn deinit(self: *PermissionStatus, _: bool, session: *Session) void {
|
pub fn deinit(self: *PermissionStatus, session: *Session) void {
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *PermissionStatus, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *PermissionStatus) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
fn getName(self: *const PermissionStatus) []const u8 {
|
fn getName(self: *const PermissionStatus) []const u8 {
|
||||||
return self._name;
|
return self._name;
|
||||||
}
|
}
|
||||||
@@ -72,8 +82,6 @@ const PermissionStatus = struct {
|
|||||||
pub const name = "PermissionStatus";
|
pub const name = "PermissionStatus";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(PermissionStatus.deinit);
|
|
||||||
};
|
};
|
||||||
pub const name = bridge.accessor(getName, null, .{});
|
pub const name = bridge.accessor(getName, null, .{});
|
||||||
pub const state = bridge.accessor(getState, null, .{});
|
pub const state = bridge.accessor(getState, null, .{});
|
||||||
|
|||||||
@@ -38,10 +38,6 @@ pub fn init(page: *Page) !*Range {
|
|||||||
return page._factory.abstractRange(arena, Range{ ._proto = undefined }, page);
|
return page._factory.abstractRange(arena, Range{ ._proto = undefined }, page);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *Range, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asAbstractRange(self: *Range) *AbstractRange {
|
pub fn asAbstractRange(self: *Range) *AbstractRange {
|
||||||
return self._proto;
|
return self._proto;
|
||||||
}
|
}
|
||||||
@@ -697,8 +693,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "Range";
|
pub const name = "Range";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(Range.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Constants for compareBoundaryPoints
|
// Constants for compareBoundaryPoints
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
|
|
||||||
const js = @import("../js/js.zig");
|
const js = @import("../js/js.zig");
|
||||||
const Page = @import("../Page.zig");
|
const Page = @import("../Page.zig");
|
||||||
@@ -32,18 +33,27 @@ const Selection = @This();
|
|||||||
|
|
||||||
pub const SelectionDirection = enum { backward, forward, none };
|
pub const SelectionDirection = enum { backward, forward, none };
|
||||||
|
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_range: ?*Range = null,
|
_range: ?*Range = null,
|
||||||
_direction: SelectionDirection = .none,
|
_direction: SelectionDirection = .none,
|
||||||
|
|
||||||
pub const init: Selection = .{};
|
pub const init: Selection = .{};
|
||||||
|
|
||||||
pub fn deinit(self: *Selection, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *Selection, session: *Session) void {
|
||||||
if (self._range) |r| {
|
if (self._range) |r| {
|
||||||
r.deinit(shutdown, session);
|
r.asAbstractRange().releaseRef(session);
|
||||||
self._range = null;
|
self._range = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *Selection, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *Selection) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
fn dispatchSelectionChangeEvent(page: *Page) !void {
|
fn dispatchSelectionChangeEvent(page: *Page) !void {
|
||||||
const event = try Event.init("selectionchange", .{}, page);
|
const event = try Event.init("selectionchange", .{}, page);
|
||||||
try page._event_manager.dispatch(page.document.asEventTarget(), event);
|
try page._event_manager.dispatch(page.document.asEventTarget(), event);
|
||||||
@@ -693,7 +703,7 @@ pub fn toString(self: *const Selection, page: *Page) ![]const u8 {
|
|||||||
|
|
||||||
fn setRange(self: *Selection, new_range: ?*Range, page: *Page) void {
|
fn setRange(self: *Selection, new_range: ?*Range, page: *Page) void {
|
||||||
if (self._range) |existing| {
|
if (self._range) |existing| {
|
||||||
existing.deinit(false, page._session);
|
_ = existing.asAbstractRange().releaseRef(page._session);
|
||||||
}
|
}
|
||||||
if (new_range) |nr| {
|
if (new_range) |nr| {
|
||||||
nr.asAbstractRange().acquireRef();
|
nr.asAbstractRange().acquireRef();
|
||||||
@@ -708,7 +718,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "Selection";
|
pub const name = "Selection";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const finalizer = bridge.finalizer(Selection.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const anchorNode = bridge.accessor(Selection.getAnchorNode, null, .{});
|
pub const anchorNode = bridge.accessor(Selection.getAnchorNode, null, .{});
|
||||||
|
|||||||
@@ -256,8 +256,7 @@ pub fn createObjectURL(blob: *Blob, page: *Page) ![]const u8 {
|
|||||||
.{ page.origin orelse "null", uuid_buf },
|
.{ page.origin orelse "null", uuid_buf },
|
||||||
);
|
);
|
||||||
try page._blob_urls.put(page.arena, blob_url, blob);
|
try page._blob_urls.put(page.arena, blob_url, blob);
|
||||||
// prevent GC from cleaning up the blob while it's in the registry
|
blob.acquireRef();
|
||||||
page.js.strongRef(blob);
|
|
||||||
return blob_url;
|
return blob_url;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -267,9 +266,8 @@ pub fn revokeObjectURL(url: []const u8, page: *Page) void {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove from registry and release strong ref (no-op if not found)
|
|
||||||
if (page._blob_urls.fetchRemove(url)) |entry| {
|
if (page._blob_urls.fetchRemove(url)) |entry| {
|
||||||
page.js.weakRef(entry.value);
|
entry.value.releaseRef(page._session);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
const log = @import("../../../log.zig");
|
const log = @import("../../../log.zig");
|
||||||
const js = @import("../../js/js.zig");
|
const js = @import("../../js/js.zig");
|
||||||
const Page = @import("../../Page.zig");
|
const Page = @import("../../Page.zig");
|
||||||
@@ -33,6 +34,7 @@ const PlayState = enum {
|
|||||||
finished,
|
finished,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
_rc: lp.RC(u32) = .{},
|
||||||
_page: *Page,
|
_page: *Page,
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
|
|
||||||
@@ -62,10 +64,18 @@ pub fn init(page: *Page) !*Animation {
|
|||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *Animation, _: bool, session: *Session) void {
|
pub fn deinit(self: *Animation, session: *Session) void {
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *Animation, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *Animation) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn play(self: *Animation, page: *Page) !void {
|
pub fn play(self: *Animation, page: *Page) !void {
|
||||||
if (self._playState == .running) {
|
if (self._playState == .running) {
|
||||||
return;
|
return;
|
||||||
@@ -75,7 +85,7 @@ pub fn play(self: *Animation, page: *Page) !void {
|
|||||||
self._playState = .running;
|
self._playState = .running;
|
||||||
|
|
||||||
// Schedule the transition from .running => .finished in 10ms.
|
// Schedule the transition from .running => .finished in 10ms.
|
||||||
page.js.strongRef(self);
|
self.acquireRef();
|
||||||
try page.js.scheduler.add(
|
try page.js.scheduler.add(
|
||||||
self,
|
self,
|
||||||
Animation.update,
|
Animation.update,
|
||||||
@@ -201,7 +211,7 @@ fn update(ctx: *anyopaque) !?u32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// No future change scheduled, set the object weak for garbage collection.
|
// No future change scheduled, set the object weak for garbage collection.
|
||||||
self._page.js.weakRef(self);
|
self.releaseRef(self._page._session);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,8 +230,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "Animation";
|
pub const name = "Animation";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(Animation.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const play = bridge.function(Animation.play, .{});
|
pub const play = bridge.function(Animation.play, .{});
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
|
|
||||||
const log = @import("../../../log.zig");
|
const log = @import("../../../log.zig");
|
||||||
const js = @import("../../js/js.zig");
|
const js = @import("../../js/js.zig");
|
||||||
@@ -37,15 +38,9 @@ _data: union(enum) {
|
|||||||
radio_node_list: *RadioNodeList,
|
radio_node_list: *RadioNodeList,
|
||||||
name: NodeLive(.name),
|
name: NodeLive(.name),
|
||||||
},
|
},
|
||||||
_rc: usize = 0,
|
_rc: lp.RC(u32) = .{},
|
||||||
|
|
||||||
pub fn deinit(self: *NodeList, _: bool, session: *Session) void {
|
|
||||||
const rc = self._rc;
|
|
||||||
if (rc > 1) {
|
|
||||||
self._rc = rc - 1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
pub fn deinit(self: *NodeList, session: *Session) void {
|
||||||
switch (self._data) {
|
switch (self._data) {
|
||||||
.selector_list => |list| list.deinit(session),
|
.selector_list => |list| list.deinit(session),
|
||||||
.child_nodes => |cn| cn.deinit(session),
|
.child_nodes => |cn| cn.deinit(session),
|
||||||
@@ -53,8 +48,12 @@ pub fn deinit(self: *NodeList, _: bool, session: *Session) void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *NodeList, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
pub fn acquireRef(self: *NodeList) void {
|
pub fn acquireRef(self: *NodeList) void {
|
||||||
self._rc += 1;
|
self._rc.acquire();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn length(self: *NodeList, page: *Page) !u32 {
|
pub fn length(self: *NodeList, page: *Page) !u32 {
|
||||||
@@ -119,8 +118,12 @@ const Iterator = struct {
|
|||||||
|
|
||||||
const Entry = struct { u32, *Node };
|
const Entry = struct { u32, *Node };
|
||||||
|
|
||||||
pub fn deinit(self: *Iterator, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *Iterator, session: *Session) void {
|
||||||
self.list.deinit(shutdown, session);
|
self.list.deinit(session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *Iterator, session: *Session) void {
|
||||||
|
self.list.releaseRef(session);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn acquireRef(self: *Iterator) void {
|
pub fn acquireRef(self: *Iterator) void {
|
||||||
@@ -143,8 +146,6 @@ pub const JsApi = struct {
|
|||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const enumerable = false;
|
pub const enumerable = false;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(NodeList.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const length = bridge.accessor(NodeList.length, null, .{});
|
pub const length = bridge.accessor(NodeList.length, null, .{});
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
const js = @import("../../js/js.zig");
|
const js = @import("../../js/js.zig");
|
||||||
const Page = @import("../../Page.zig");
|
const Page = @import("../../Page.zig");
|
||||||
const Session = @import("../../Session.zig");
|
const Session = @import("../../Session.zig");
|
||||||
@@ -40,9 +41,15 @@ pub fn Entry(comptime Inner: type, comptime field: ?[]const u8) type {
|
|||||||
return page._factory.create(Self{ .inner = inner });
|
return page._factory.create(Self{ .inner = inner });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *Self, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *Self, session: *Session) void {
|
||||||
if (@hasDecl(Inner, "deinit")) {
|
_ = self;
|
||||||
self.inner.deinit(shutdown, session);
|
_ = session;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *Self, session: *Session) void {
|
||||||
|
// Release the reference to the inner type that we acquired
|
||||||
|
if (@hasDecl(Inner, "releaseRef")) {
|
||||||
|
self.inner.releaseRef(session);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,8 +80,6 @@ pub fn Entry(comptime Inner: type, comptime field: ?[]const u8) type {
|
|||||||
pub const Meta = struct {
|
pub const Meta = struct {
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(Self.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const next = bridge.function(Self.next, .{ .null_as_undefined = true });
|
pub const next = bridge.function(Self.next, .{ .null_as_undefined = true });
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
const js = @import("../../js/js.zig");
|
const js = @import("../../js/js.zig");
|
||||||
const Page = @import("../../Page.zig");
|
const Page = @import("../../Page.zig");
|
||||||
const Session = @import("../../Session.zig");
|
const Session = @import("../../Session.zig");
|
||||||
@@ -25,6 +26,7 @@ const Allocator = std.mem.Allocator;
|
|||||||
|
|
||||||
const FontFace = @This();
|
const FontFace = @This();
|
||||||
|
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
_family: []const u8,
|
_family: []const u8,
|
||||||
|
|
||||||
@@ -42,10 +44,18 @@ pub fn init(family: []const u8, source: []const u8, page: *Page) !*FontFace {
|
|||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *FontFace, _: bool, session: *Session) void {
|
pub fn deinit(self: *FontFace, session: *Session) void {
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *FontFace, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *FontFace) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn getFamily(self: *const FontFace) []const u8 {
|
pub fn getFamily(self: *const FontFace) []const u8 {
|
||||||
return self._family;
|
return self._family;
|
||||||
}
|
}
|
||||||
@@ -67,8 +77,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "FontFace";
|
pub const name = "FontFace";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(FontFace.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(FontFace.init, .{});
|
pub const constructor = bridge.constructor(FontFace.init, .{});
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
const js = @import("../../js/js.zig");
|
const js = @import("../../js/js.zig");
|
||||||
const Page = @import("../../Page.zig");
|
const Page = @import("../../Page.zig");
|
||||||
const Session = @import("../../Session.zig");
|
const Session = @import("../../Session.zig");
|
||||||
@@ -28,6 +29,7 @@ const Allocator = std.mem.Allocator;
|
|||||||
|
|
||||||
const FontFaceSet = @This();
|
const FontFaceSet = @This();
|
||||||
|
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_proto: *EventTarget,
|
_proto: *EventTarget,
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
|
|
||||||
@@ -41,10 +43,18 @@ pub fn init(page: *Page) !*FontFaceSet {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *FontFaceSet, _: bool, session: *Session) void {
|
pub fn deinit(self: *FontFaceSet, session: *Session) void {
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *FontFaceSet, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *FontFaceSet) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn asEventTarget(self: *FontFaceSet) *EventTarget {
|
pub fn asEventTarget(self: *FontFaceSet) *EventTarget {
|
||||||
return self._proto;
|
return self._proto;
|
||||||
}
|
}
|
||||||
@@ -95,8 +105,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "FontFaceSet";
|
pub const name = "FontFaceSet";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(FontFaceSet.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const size = bridge.property(0, .{ .template = false, .readonly = true });
|
pub const size = bridge.property(0, .{ .template = false, .readonly = true });
|
||||||
|
|||||||
@@ -29,6 +29,9 @@ const OffscreenCanvas = @import("../../canvas/OffscreenCanvas.zig");
|
|||||||
|
|
||||||
const Canvas = @This();
|
const Canvas = @This();
|
||||||
_proto: *HtmlElement,
|
_proto: *HtmlElement,
|
||||||
|
_cached: ?DrawingContext = null,
|
||||||
|
|
||||||
|
const ContextType = enum { none, @"2d", webgl };
|
||||||
|
|
||||||
pub fn asElement(self: *Canvas) *Element {
|
pub fn asElement(self: *Canvas) *Element {
|
||||||
return self._proto._proto;
|
return self._proto._proto;
|
||||||
@@ -68,17 +71,28 @@ const DrawingContext = union(enum) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
pub fn getContext(self: *Canvas, context_type: []const u8, page: *Page) !?DrawingContext {
|
pub fn getContext(self: *Canvas, context_type: []const u8, page: *Page) !?DrawingContext {
|
||||||
|
if (self._cached) |cached| {
|
||||||
|
const matches = switch (cached) {
|
||||||
|
.@"2d" => std.mem.eql(u8, context_type, "2d"),
|
||||||
|
.webgl => std.mem.eql(u8, context_type, "webgl") or std.mem.eql(u8, context_type, "experimental-webgl"),
|
||||||
|
};
|
||||||
|
return if (matches) cached else null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const drawing_context: DrawingContext = blk: {
|
||||||
if (std.mem.eql(u8, context_type, "2d")) {
|
if (std.mem.eql(u8, context_type, "2d")) {
|
||||||
const ctx = try page._factory.create(CanvasRenderingContext2D{ ._canvas = self });
|
const ctx = try page._factory.create(CanvasRenderingContext2D{ ._canvas = self });
|
||||||
return .{ .@"2d" = ctx };
|
break :blk .{ .@"2d" = ctx };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (std.mem.eql(u8, context_type, "webgl") or std.mem.eql(u8, context_type, "experimental-webgl")) {
|
if (std.mem.eql(u8, context_type, "webgl") or std.mem.eql(u8, context_type, "experimental-webgl")) {
|
||||||
const ctx = try page._factory.create(WebGLRenderingContext{});
|
const ctx = try page._factory.create(WebGLRenderingContext{});
|
||||||
return .{ .webgl = ctx };
|
break :blk .{ .webgl = ctx };
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
|
};
|
||||||
|
self._cached = drawing_context;
|
||||||
|
return drawing_context;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Transfers control of the canvas to an OffscreenCanvas.
|
/// Transfers control of the canvas to an OffscreenCanvas.
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
const js = @import("../../js/js.zig");
|
const js = @import("../../js/js.zig");
|
||||||
|
|
||||||
const Page = @import("../../Page.zig");
|
const Page = @import("../../Page.zig");
|
||||||
@@ -25,6 +26,7 @@ const Allocator = std.mem.Allocator;
|
|||||||
|
|
||||||
const TextDecoder = @This();
|
const TextDecoder = @This();
|
||||||
|
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_fatal: bool,
|
_fatal: bool,
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
_ignore_bom: bool,
|
_ignore_bom: bool,
|
||||||
@@ -60,10 +62,18 @@ pub fn init(label_: ?[]const u8, opts_: ?InitOpts, page: *Page) !*TextDecoder {
|
|||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *TextDecoder, _: bool, session: *Session) void {
|
pub fn deinit(self: *TextDecoder, session: *Session) void {
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *TextDecoder, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *TextDecoder) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn getIgnoreBOM(self: *const TextDecoder) bool {
|
pub fn getIgnoreBOM(self: *const TextDecoder) bool {
|
||||||
return self._ignore_bom;
|
return self._ignore_bom;
|
||||||
}
|
}
|
||||||
@@ -109,8 +119,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "TextDecoder";
|
pub const name = "TextDecoder";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(TextDecoder.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(TextDecoder.init, .{});
|
pub const constructor = bridge.constructor(TextDecoder.init, .{});
|
||||||
|
|||||||
@@ -53,10 +53,6 @@ pub fn init(typ: []const u8, opts_: ?Options, page: *Page) !*CompositionEvent {
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *CompositionEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *CompositionEvent) *Event {
|
pub fn asEvent(self: *CompositionEvent) *Event {
|
||||||
return self._proto;
|
return self._proto;
|
||||||
}
|
}
|
||||||
@@ -72,8 +68,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "CompositionEvent";
|
pub const name = "CompositionEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(CompositionEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(CompositionEvent.init, .{});
|
pub const constructor = bridge.constructor(CompositionEvent.init, .{});
|
||||||
|
|||||||
@@ -73,11 +73,19 @@ pub fn initCustomEvent(
|
|||||||
self._detail = detail_;
|
self._detail = detail_;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *CustomEvent, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *CustomEvent, session: *Session) void {
|
||||||
if (self._detail) |d| {
|
if (self._detail) |d| {
|
||||||
d.release();
|
d.release();
|
||||||
}
|
}
|
||||||
self._proto.deinit(shutdown, session);
|
self._proto.deinit(session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *CustomEvent) void {
|
||||||
|
self._proto.acquireRef();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *CustomEvent, session: *Session) void {
|
||||||
|
self._proto._rc.release(self, session);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn asEvent(self: *CustomEvent) *Event {
|
pub fn asEvent(self: *CustomEvent) *Event {
|
||||||
@@ -95,8 +103,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "CustomEvent";
|
pub const name = "CustomEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(CustomEvent.deinit);
|
|
||||||
pub const enumerable = false;
|
pub const enumerable = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -80,11 +80,19 @@ fn initWithTrusted(arena: Allocator, typ: String, opts_: ?Options, trusted: bool
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *ErrorEvent, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *ErrorEvent, session: *Session) void {
|
||||||
if (self._error) |e| {
|
if (self._error) |e| {
|
||||||
e.release();
|
e.release();
|
||||||
}
|
}
|
||||||
self._proto.deinit(shutdown, session);
|
self._proto.deinit(session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *ErrorEvent) void {
|
||||||
|
self._proto.acquireRef();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *ErrorEvent, session: *Session) void {
|
||||||
|
self._proto._rc.release(self, session);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn asEvent(self: *ErrorEvent) *Event {
|
pub fn asEvent(self: *ErrorEvent) *Event {
|
||||||
|
|||||||
@@ -70,10 +70,6 @@ fn initWithTrusted(arena: Allocator, typ: String, _opts: ?Options, trusted: bool
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *FocusEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *FocusEvent) *Event {
|
pub fn asEvent(self: *FocusEvent) *Event {
|
||||||
return self._proto.asEvent();
|
return self._proto.asEvent();
|
||||||
}
|
}
|
||||||
@@ -89,8 +85,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "FocusEvent";
|
pub const name = "FocusEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(FocusEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(FocusEvent.init, .{});
|
pub const constructor = bridge.constructor(FocusEvent.init, .{});
|
||||||
|
|||||||
@@ -66,10 +66,6 @@ fn initWithTrusted(arena: Allocator, typ: String, maybe_options: ?Options, trust
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *FormDataEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *FormDataEvent) *Event {
|
pub fn asEvent(self: *FormDataEvent) *Event {
|
||||||
return self._proto;
|
return self._proto;
|
||||||
}
|
}
|
||||||
@@ -85,8 +81,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "FormDataEvent";
|
pub const name = "FormDataEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(FormDataEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(FormDataEvent.init, .{});
|
pub const constructor = bridge.constructor(FormDataEvent.init, .{});
|
||||||
|
|||||||
@@ -83,10 +83,6 @@ fn initWithTrusted(arena: Allocator, typ: String, _opts: ?Options, trusted: bool
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *InputEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *InputEvent) *Event {
|
pub fn asEvent(self: *InputEvent) *Event {
|
||||||
return self._proto.asEvent();
|
return self._proto.asEvent();
|
||||||
}
|
}
|
||||||
@@ -110,8 +106,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "InputEvent";
|
pub const name = "InputEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(InputEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(InputEvent.init, .{});
|
pub const constructor = bridge.constructor(InputEvent.init, .{});
|
||||||
|
|||||||
@@ -229,10 +229,6 @@ fn initWithTrusted(arena: Allocator, typ: String, _opts: ?Options, trusted: bool
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *KeyboardEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *KeyboardEvent) *Event {
|
pub fn asEvent(self: *KeyboardEvent) *Event {
|
||||||
return self._proto.asEvent();
|
return self._proto.asEvent();
|
||||||
}
|
}
|
||||||
@@ -296,8 +292,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "KeyboardEvent";
|
pub const name = "KeyboardEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(KeyboardEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(KeyboardEvent.init, .{});
|
pub const constructor = bridge.constructor(KeyboardEvent.init, .{});
|
||||||
|
|||||||
@@ -73,11 +73,19 @@ fn initWithTrusted(arena: Allocator, typ: String, opts_: ?Options, trusted: bool
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *MessageEvent, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *MessageEvent, session: *Session) void {
|
||||||
if (self._data) |d| {
|
if (self._data) |d| {
|
||||||
d.release();
|
d.release();
|
||||||
}
|
}
|
||||||
self._proto.deinit(shutdown, session);
|
self._proto.deinit(session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *MessageEvent) void {
|
||||||
|
self._proto.acquireRef();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *MessageEvent, session: *Session) void {
|
||||||
|
self._proto._rc.release(self, session);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn asEvent(self: *MessageEvent) *Event {
|
pub fn asEvent(self: *MessageEvent) *Event {
|
||||||
@@ -103,8 +111,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "MessageEvent";
|
pub const name = "MessageEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(MessageEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(MessageEvent.init, .{});
|
pub const constructor = bridge.constructor(MessageEvent.init, .{});
|
||||||
|
|||||||
@@ -121,10 +121,6 @@ fn initWithTrusted(arena: Allocator, typ: String, _opts: ?Options, trusted: bool
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *MouseEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *MouseEvent) *Event {
|
pub fn asEvent(self: *MouseEvent) *Event {
|
||||||
return self._proto.asEvent();
|
return self._proto.asEvent();
|
||||||
}
|
}
|
||||||
@@ -203,8 +199,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "MouseEvent";
|
pub const name = "MouseEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(MouseEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(MouseEvent.init, .{});
|
pub const constructor = bridge.constructor(MouseEvent.init, .{});
|
||||||
|
|||||||
@@ -83,10 +83,6 @@ fn initWithTrusted(
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *NavigationCurrentEntryChangeEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *NavigationCurrentEntryChangeEvent) *Event {
|
pub fn asEvent(self: *NavigationCurrentEntryChangeEvent) *Event {
|
||||||
return self._proto;
|
return self._proto;
|
||||||
}
|
}
|
||||||
@@ -106,8 +102,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "NavigationCurrentEntryChangeEvent";
|
pub const name = "NavigationCurrentEntryChangeEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(NavigationCurrentEntryChangeEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(NavigationCurrentEntryChangeEvent.init, .{});
|
pub const constructor = bridge.constructor(NavigationCurrentEntryChangeEvent.init, .{});
|
||||||
|
|||||||
@@ -66,10 +66,6 @@ fn initWithTrusted(arena: Allocator, typ: String, _opts: ?Options, trusted: bool
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *PageTransitionEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *PageTransitionEvent) *Event {
|
pub fn asEvent(self: *PageTransitionEvent) *Event {
|
||||||
return self._proto;
|
return self._proto;
|
||||||
}
|
}
|
||||||
@@ -85,8 +81,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "PageTransitionEvent";
|
pub const name = "PageTransitionEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(PageTransitionEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(PageTransitionEvent.init, .{});
|
pub const constructor = bridge.constructor(PageTransitionEvent.init, .{});
|
||||||
|
|||||||
@@ -128,10 +128,6 @@ pub fn init(typ: []const u8, _opts: ?Options, page: *Page) !*PointerEvent {
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *PointerEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *PointerEvent) *Event {
|
pub fn asEvent(self: *PointerEvent) *Event {
|
||||||
return self._proto.asEvent();
|
return self._proto.asEvent();
|
||||||
}
|
}
|
||||||
@@ -191,8 +187,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "PointerEvent";
|
pub const name = "PointerEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(PointerEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(PointerEvent.init, .{});
|
pub const constructor = bridge.constructor(PointerEvent.init, .{});
|
||||||
|
|||||||
@@ -67,10 +67,6 @@ fn initWithTrusted(arena: Allocator, typ: String, _opts: ?Options, trusted: bool
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *PopStateEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *PopStateEvent) *Event {
|
pub fn asEvent(self: *PopStateEvent) *Event {
|
||||||
return self._proto;
|
return self._proto;
|
||||||
}
|
}
|
||||||
@@ -92,8 +88,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "PopStateEvent";
|
pub const name = "PopStateEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(PopStateEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(PopStateEvent.init, .{});
|
pub const constructor = bridge.constructor(PopStateEvent.init, .{});
|
||||||
|
|||||||
@@ -68,10 +68,6 @@ fn initWithTrusted(arena: Allocator, typ: String, _opts: ?Options, trusted: bool
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *ProgressEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *ProgressEvent) *Event {
|
pub fn asEvent(self: *ProgressEvent) *Event {
|
||||||
return self._proto;
|
return self._proto;
|
||||||
}
|
}
|
||||||
@@ -96,8 +92,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "ProgressEvent";
|
pub const name = "ProgressEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(ProgressEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(ProgressEvent.init, .{});
|
pub const constructor = bridge.constructor(ProgressEvent.init, .{});
|
||||||
|
|||||||
@@ -56,14 +56,22 @@ pub fn init(typ: []const u8, opts_: ?Options, page: *Page) !*PromiseRejectionEve
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *PromiseRejectionEvent, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *PromiseRejectionEvent, session: *Session) void {
|
||||||
if (self._reason) |r| {
|
if (self._reason) |r| {
|
||||||
r.release();
|
r.release();
|
||||||
}
|
}
|
||||||
if (self._promise) |p| {
|
if (self._promise) |p| {
|
||||||
p.release();
|
p.release();
|
||||||
}
|
}
|
||||||
self._proto.deinit(shutdown, session);
|
self._proto.deinit(session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *PromiseRejectionEvent) void {
|
||||||
|
self._proto.acquireRef();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *PromiseRejectionEvent, session: *Session) void {
|
||||||
|
self._proto._rc.release(self, session);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn asEvent(self: *PromiseRejectionEvent) *Event {
|
pub fn asEvent(self: *PromiseRejectionEvent) *Event {
|
||||||
@@ -85,8 +93,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "PromiseRejectionEvent";
|
pub const name = "PromiseRejectionEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(PromiseRejectionEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(PromiseRejectionEvent.init, .{});
|
pub const constructor = bridge.constructor(PromiseRejectionEvent.init, .{});
|
||||||
|
|||||||
@@ -67,10 +67,6 @@ fn initWithTrusted(arena: Allocator, typ: String, _opts: ?Options, trusted: bool
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *SubmitEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *SubmitEvent) *Event {
|
pub fn asEvent(self: *SubmitEvent) *Event {
|
||||||
return self._proto;
|
return self._proto;
|
||||||
}
|
}
|
||||||
@@ -86,8 +82,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "SubmitEvent";
|
pub const name = "SubmitEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(SubmitEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(SubmitEvent.init, .{});
|
pub const constructor = bridge.constructor(SubmitEvent.init, .{});
|
||||||
|
|||||||
@@ -59,10 +59,6 @@ pub fn init(typ: []const u8, _opts: ?Options, page: *Page) !*TextEvent {
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *TextEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *TextEvent) *Event {
|
pub fn asEvent(self: *TextEvent) *Event {
|
||||||
return self._proto.asEvent();
|
return self._proto.asEvent();
|
||||||
}
|
}
|
||||||
@@ -101,8 +97,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "TextEvent";
|
pub const name = "TextEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(TextEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// No constructor - TextEvent is created via document.createEvent('TextEvent')
|
// No constructor - TextEvent is created via document.createEvent('TextEvent')
|
||||||
|
|||||||
@@ -71,10 +71,6 @@ pub fn init(typ: []const u8, _opts: ?Options, page: *Page) !*UIEvent {
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *UIEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as(self: *UIEvent, comptime T: type) *T {
|
pub fn as(self: *UIEvent, comptime T: type) *T {
|
||||||
return self.is(T).?;
|
return self.is(T).?;
|
||||||
}
|
}
|
||||||
@@ -122,8 +118,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "UIEvent";
|
pub const name = "UIEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(UIEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(UIEvent.init, .{});
|
pub const constructor = bridge.constructor(UIEvent.init, .{});
|
||||||
|
|||||||
@@ -87,10 +87,6 @@ pub fn init(typ: []const u8, _opts: ?Options, page: *Page) !*WheelEvent {
|
|||||||
return event;
|
return event;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *WheelEvent, shutdown: bool, session: *Session) void {
|
|
||||||
self._proto.deinit(shutdown, session);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asEvent(self: *WheelEvent) *Event {
|
pub fn asEvent(self: *WheelEvent) *Event {
|
||||||
return self._proto.asEvent();
|
return self._proto.asEvent();
|
||||||
}
|
}
|
||||||
@@ -118,8 +114,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "WheelEvent";
|
pub const name = "WheelEvent";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(WheelEvent.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(WheelEvent.init, .{});
|
pub const constructor = bridge.constructor(WheelEvent.init, .{});
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ pub fn init(input: Input, options: ?InitOpts, page: *Page) !js.Promise {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const response = try Response.init(null, .{ .status = 0 }, page);
|
const response = try Response.init(null, .{ .status = 0 }, page);
|
||||||
errdefer response.deinit(true, page._session);
|
errdefer response.deinit(page._session);
|
||||||
|
|
||||||
const fetch = try response._arena.create(Fetch);
|
const fetch = try response._arena.create(Fetch);
|
||||||
fetch.* = .{
|
fetch.* = .{
|
||||||
@@ -127,16 +127,16 @@ fn handleBlobUrl(url: []const u8, resolver: js.PromiseResolver, page: *Page) !js
|
|||||||
return resolver.promise();
|
return resolver.promise();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn httpStartCallback(transfer: *HttpClient.Transfer) !void {
|
fn httpStartCallback(response: HttpClient.Response) !void {
|
||||||
const self: *Fetch = @ptrCast(@alignCast(transfer.ctx));
|
const self: *Fetch = @ptrCast(@alignCast(response.ctx));
|
||||||
if (comptime IS_DEBUG) {
|
if (comptime IS_DEBUG) {
|
||||||
log.debug(.http, "request start", .{ .url = self._url, .source = "fetch" });
|
log.debug(.http, "request start", .{ .url = self._url, .source = "fetch" });
|
||||||
}
|
}
|
||||||
self._response._transfer = transfer;
|
self._response._http_response = response;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn httpHeaderDoneCallback(transfer: *HttpClient.Transfer) !bool {
|
fn httpHeaderDoneCallback(response: HttpClient.Response) !bool {
|
||||||
const self: *Fetch = @ptrCast(@alignCast(transfer.ctx));
|
const self: *Fetch = @ptrCast(@alignCast(response.ctx));
|
||||||
|
|
||||||
if (self._signal) |signal| {
|
if (self._signal) |signal| {
|
||||||
if (signal._aborted) {
|
if (signal._aborted) {
|
||||||
@@ -145,25 +145,24 @@ fn httpHeaderDoneCallback(transfer: *HttpClient.Transfer) !bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const arena = self._response._arena;
|
const arena = self._response._arena;
|
||||||
if (transfer.getContentLength()) |cl| {
|
if (response.contentLength()) |cl| {
|
||||||
try self._buf.ensureTotalCapacity(arena, cl);
|
try self._buf.ensureTotalCapacity(arena, cl);
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = self._response;
|
const res = self._response;
|
||||||
const header = transfer.response_header.?;
|
|
||||||
|
|
||||||
if (comptime IS_DEBUG) {
|
if (comptime IS_DEBUG) {
|
||||||
log.debug(.http, "request header", .{
|
log.debug(.http, "request header", .{
|
||||||
.source = "fetch",
|
.source = "fetch",
|
||||||
.url = self._url,
|
.url = self._url,
|
||||||
.status = header.status,
|
.status = response.status(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
res._status = header.status;
|
res._status = response.status().?;
|
||||||
res._status_text = std.http.Status.phrase(@enumFromInt(header.status)) orelse "";
|
res._status_text = std.http.Status.phrase(@enumFromInt(response.status().?)) orelse "";
|
||||||
res._url = try arena.dupeZ(u8, std.mem.span(header.url));
|
res._url = try arena.dupeZ(u8, response.url());
|
||||||
res._is_redirected = header.redirect_count > 0;
|
res._is_redirected = response.redirectCount().? > 0;
|
||||||
|
|
||||||
// Determine response type based on origin comparison
|
// Determine response type based on origin comparison
|
||||||
const page_origin = URL.getOrigin(arena, self._page.url) catch null;
|
const page_origin = URL.getOrigin(arena, self._page.url) catch null;
|
||||||
@@ -183,7 +182,7 @@ fn httpHeaderDoneCallback(transfer: *HttpClient.Transfer) !bool {
|
|||||||
res._type = .basic;
|
res._type = .basic;
|
||||||
}
|
}
|
||||||
|
|
||||||
var it = transfer.responseHeaderIterator();
|
var it = response.headerIterator();
|
||||||
while (it.next()) |hdr| {
|
while (it.next()) |hdr| {
|
||||||
try res._headers.append(hdr.name, hdr.value, self._page);
|
try res._headers.append(hdr.name, hdr.value, self._page);
|
||||||
}
|
}
|
||||||
@@ -191,8 +190,8 @@ fn httpHeaderDoneCallback(transfer: *HttpClient.Transfer) !bool {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn httpDataCallback(transfer: *HttpClient.Transfer, data: []const u8) !void {
|
fn httpDataCallback(response: HttpClient.Response, data: []const u8) !void {
|
||||||
const self: *Fetch = @ptrCast(@alignCast(transfer.ctx));
|
const self: *Fetch = @ptrCast(@alignCast(response.ctx));
|
||||||
|
|
||||||
// Check if aborted
|
// Check if aborted
|
||||||
if (self._signal) |signal| {
|
if (self._signal) |signal| {
|
||||||
@@ -207,7 +206,7 @@ fn httpDataCallback(transfer: *HttpClient.Transfer, data: []const u8) !void {
|
|||||||
fn httpDoneCallback(ctx: *anyopaque) !void {
|
fn httpDoneCallback(ctx: *anyopaque) !void {
|
||||||
const self: *Fetch = @ptrCast(@alignCast(ctx));
|
const self: *Fetch = @ptrCast(@alignCast(ctx));
|
||||||
var response = self._response;
|
var response = self._response;
|
||||||
response._transfer = null;
|
response._http_response = null;
|
||||||
response._body = self._buf.items;
|
response._body = self._buf.items;
|
||||||
|
|
||||||
log.info(.http, "request complete", .{
|
log.info(.http, "request complete", .{
|
||||||
@@ -226,16 +225,16 @@ fn httpDoneCallback(ctx: *anyopaque) !void {
|
|||||||
return ls.toLocal(self._resolver).resolve("fetch done", js_val);
|
return ls.toLocal(self._resolver).resolve("fetch done", js_val);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn httpErrorCallback(ctx: *anyopaque, err: anyerror) void {
|
fn httpErrorCallback(ctx: *anyopaque, _: anyerror) void {
|
||||||
const self: *Fetch = @ptrCast(@alignCast(ctx));
|
const self: *Fetch = @ptrCast(@alignCast(ctx));
|
||||||
|
|
||||||
var response = self._response;
|
var response = self._response;
|
||||||
response._transfer = null;
|
response._http_response = null;
|
||||||
// the response is only passed on v8 on success, if we're here, it's safe to
|
// the response is only passed on v8 on success, if we're here, it's safe to
|
||||||
// clear this. (defer since `self is in the response's arena).
|
// clear this. (defer since `self is in the response's arena).
|
||||||
|
|
||||||
defer if (self._owns_response) {
|
defer if (self._owns_response) {
|
||||||
response.deinit(err == error.Abort, self._page._session);
|
response.deinit(self._page._session);
|
||||||
self._owns_response = false;
|
self._owns_response = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -256,8 +255,8 @@ fn httpShutdownCallback(ctx: *anyopaque) void {
|
|||||||
|
|
||||||
if (self._owns_response) {
|
if (self._owns_response) {
|
||||||
var response = self._response;
|
var response = self._response;
|
||||||
response._transfer = null;
|
response._http_response = null;
|
||||||
response.deinit(true, self._page._session);
|
response.deinit(self._page._session);
|
||||||
// Do not access `self` after this point: the Fetch struct was
|
// Do not access `self` after this point: the Fetch struct was
|
||||||
// allocated from response._arena which has been released.
|
// allocated from response._arena which has been released.
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
const js = @import("../../js/js.zig");
|
const js = @import("../../js/js.zig");
|
||||||
const HttpClient = @import("../../HttpClient.zig");
|
const HttpClient = @import("../../HttpClient.zig");
|
||||||
|
|
||||||
@@ -38,6 +39,7 @@ pub const Type = enum {
|
|||||||
opaqueredirect,
|
opaqueredirect,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_status: u16,
|
_status: u16,
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
_headers: *Headers,
|
_headers: *Headers,
|
||||||
@@ -46,7 +48,7 @@ _type: Type,
|
|||||||
_status_text: []const u8,
|
_status_text: []const u8,
|
||||||
_url: [:0]const u8,
|
_url: [:0]const u8,
|
||||||
_is_redirected: bool,
|
_is_redirected: bool,
|
||||||
_transfer: ?*HttpClient.Transfer = null,
|
_http_response: ?HttpClient.Response = null,
|
||||||
|
|
||||||
const InitOpts = struct {
|
const InitOpts = struct {
|
||||||
status: u16 = 200,
|
status: u16 = 200,
|
||||||
@@ -78,18 +80,22 @@ pub fn init(body_: ?[]const u8, opts_: ?InitOpts, page: *Page) !*Response {
|
|||||||
return self;
|
return self;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *Response, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *Response, session: *Session) void {
|
||||||
if (self._transfer) |transfer| {
|
if (self._http_response) |resp| {
|
||||||
if (shutdown) {
|
resp.abort(error.Abort);
|
||||||
transfer.terminate();
|
self._http_response = null;
|
||||||
} else {
|
|
||||||
transfer.abort(error.Abort);
|
|
||||||
}
|
|
||||||
self._transfer = null;
|
|
||||||
}
|
}
|
||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *Response, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *Response) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn getStatus(self: *const Response) u16 {
|
pub fn getStatus(self: *const Response) u16 {
|
||||||
return self._status;
|
return self._status;
|
||||||
}
|
}
|
||||||
@@ -185,7 +191,7 @@ pub fn clone(self: *const Response, page: *Page) !*Response {
|
|||||||
._type = self._type,
|
._type = self._type,
|
||||||
._is_redirected = self._is_redirected,
|
._is_redirected = self._is_redirected,
|
||||||
._headers = try Headers.init(.{ .obj = self._headers }, page),
|
._headers = try Headers.init(.{ .obj = self._headers }, page),
|
||||||
._transfer = null,
|
._http_response = null,
|
||||||
};
|
};
|
||||||
return cloned;
|
return cloned;
|
||||||
}
|
}
|
||||||
@@ -197,8 +203,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "Response";
|
pub const name = "Response";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(Response.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(Response.init, .{});
|
pub const constructor = bridge.constructor(Response.init, .{});
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const lp = @import("lightpanda");
|
||||||
const js = @import("../../js/js.zig");
|
const js = @import("../../js/js.zig");
|
||||||
|
|
||||||
const log = @import("../../../log.zig");
|
const log = @import("../../../log.zig");
|
||||||
@@ -38,10 +39,11 @@ const Allocator = std.mem.Allocator;
|
|||||||
const IS_DEBUG = @import("builtin").mode == .Debug;
|
const IS_DEBUG = @import("builtin").mode == .Debug;
|
||||||
|
|
||||||
const XMLHttpRequest = @This();
|
const XMLHttpRequest = @This();
|
||||||
|
_rc: lp.RC(u8) = .{},
|
||||||
_page: *Page,
|
_page: *Page,
|
||||||
_proto: *XMLHttpRequestEventTarget,
|
_proto: *XMLHttpRequestEventTarget,
|
||||||
_arena: Allocator,
|
_arena: Allocator,
|
||||||
_transfer: ?*HttpClient.Transfer = null,
|
_http_response: ?HttpClient.Response = null,
|
||||||
|
|
||||||
_url: [:0]const u8 = "",
|
_url: [:0]const u8 = "",
|
||||||
_method: net_http.Method = .GET,
|
_method: net_http.Method = .GET,
|
||||||
@@ -87,22 +89,19 @@ const ResponseType = enum {
|
|||||||
pub fn init(page: *Page) !*XMLHttpRequest {
|
pub fn init(page: *Page) !*XMLHttpRequest {
|
||||||
const arena = try page.getArena(.{ .debug = "XMLHttpRequest" });
|
const arena = try page.getArena(.{ .debug = "XMLHttpRequest" });
|
||||||
errdefer page.releaseArena(arena);
|
errdefer page.releaseArena(arena);
|
||||||
return page._factory.xhrEventTarget(arena, XMLHttpRequest{
|
const xhr = try page._factory.xhrEventTarget(arena, XMLHttpRequest{
|
||||||
._page = page,
|
._page = page,
|
||||||
._arena = arena,
|
._arena = arena,
|
||||||
._proto = undefined,
|
._proto = undefined,
|
||||||
._request_headers = try Headers.init(null, page),
|
._request_headers = try Headers.init(null, page),
|
||||||
});
|
});
|
||||||
|
return xhr;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *XMLHttpRequest, shutdown: bool, session: *Session) void {
|
pub fn deinit(self: *XMLHttpRequest, session: *Session) void {
|
||||||
if (self._transfer) |transfer| {
|
if (self._http_response) |resp| {
|
||||||
if (shutdown) {
|
resp.abort(error.Abort);
|
||||||
transfer.terminate();
|
self._http_response = null;
|
||||||
} else {
|
|
||||||
transfer.abort(error.Abort);
|
|
||||||
}
|
|
||||||
self._transfer = null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (self._on_ready_state_change) |func| {
|
if (self._on_ready_state_change) |func| {
|
||||||
@@ -137,6 +136,14 @@ pub fn deinit(self: *XMLHttpRequest, shutdown: bool, session: *Session) void {
|
|||||||
session.releaseArena(self._arena);
|
session.releaseArena(self._arena);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn releaseRef(self: *XMLHttpRequest, session: *Session) void {
|
||||||
|
self._rc.release(self, session);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquireRef(self: *XMLHttpRequest) void {
|
||||||
|
self._rc.acquire();
|
||||||
|
}
|
||||||
|
|
||||||
fn asEventTarget(self: *XMLHttpRequest) *EventTarget {
|
fn asEventTarget(self: *XMLHttpRequest) *EventTarget {
|
||||||
return self._proto._proto;
|
return self._proto._proto;
|
||||||
}
|
}
|
||||||
@@ -168,9 +175,9 @@ pub fn setWithCredentials(self: *XMLHttpRequest, value: bool) !void {
|
|||||||
// TODO: url should be a union, as it can be multiple things
|
// TODO: url should be a union, as it can be multiple things
|
||||||
pub fn open(self: *XMLHttpRequest, method_: []const u8, url: [:0]const u8) !void {
|
pub fn open(self: *XMLHttpRequest, method_: []const u8, url: [:0]const u8) !void {
|
||||||
// Abort any in-progress request
|
// Abort any in-progress request
|
||||||
if (self._transfer) |transfer| {
|
if (self._http_response) |transfer| {
|
||||||
transfer.abort(error.Abort);
|
transfer.abort(error.Abort);
|
||||||
self._transfer = null;
|
self._http_response = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset internal state
|
// Reset internal state
|
||||||
@@ -245,8 +252,6 @@ pub fn send(self: *XMLHttpRequest, body_: ?[]const u8) !void {
|
|||||||
.error_callback = httpErrorCallback,
|
.error_callback = httpErrorCallback,
|
||||||
.shutdown_callback = httpShutdownCallback,
|
.shutdown_callback = httpShutdownCallback,
|
||||||
});
|
});
|
||||||
|
|
||||||
page.js.strongRef(self);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handleBlobUrl(self: *XMLHttpRequest, page: *Page) !void {
|
fn handleBlobUrl(self: *XMLHttpRequest, page: *Page) !void {
|
||||||
@@ -382,34 +387,33 @@ pub fn getResponseXML(self: *XMLHttpRequest, page: *Page) !?*Node.Document {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
fn httpStartCallback(transfer: *HttpClient.Transfer) !void {
|
fn httpStartCallback(response: HttpClient.Response) !void {
|
||||||
const self: *XMLHttpRequest = @ptrCast(@alignCast(transfer.ctx));
|
const self: *XMLHttpRequest = @ptrCast(@alignCast(response.ctx));
|
||||||
if (comptime IS_DEBUG) {
|
if (comptime IS_DEBUG) {
|
||||||
log.debug(.http, "request start", .{ .method = self._method, .url = self._url, .source = "xhr" });
|
log.debug(.http, "request start", .{ .method = self._method, .url = self._url, .source = "xhr" });
|
||||||
}
|
}
|
||||||
self._transfer = transfer;
|
self._http_response = response;
|
||||||
|
self.acquireRef();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn httpHeaderCallback(transfer: *HttpClient.Transfer, header: net_http.Header) !void {
|
fn httpHeaderCallback(response: HttpClient.Response, header: net_http.Header) !void {
|
||||||
const self: *XMLHttpRequest = @ptrCast(@alignCast(transfer.ctx));
|
const self: *XMLHttpRequest = @ptrCast(@alignCast(response.ctx));
|
||||||
const joined = try std.fmt.allocPrint(self._arena, "{s}: {s}", .{ header.name, header.value });
|
const joined = try std.fmt.allocPrint(self._arena, "{s}: {s}", .{ header.name, header.value });
|
||||||
try self._response_headers.append(self._arena, joined);
|
try self._response_headers.append(self._arena, joined);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn httpHeaderDoneCallback(transfer: *HttpClient.Transfer) !bool {
|
fn httpHeaderDoneCallback(response: HttpClient.Response) !bool {
|
||||||
const self: *XMLHttpRequest = @ptrCast(@alignCast(transfer.ctx));
|
const self: *XMLHttpRequest = @ptrCast(@alignCast(response.ctx));
|
||||||
|
|
||||||
const header = &transfer.response_header.?;
|
|
||||||
|
|
||||||
if (comptime IS_DEBUG) {
|
if (comptime IS_DEBUG) {
|
||||||
log.debug(.http, "request header", .{
|
log.debug(.http, "request header", .{
|
||||||
.source = "xhr",
|
.source = "xhr",
|
||||||
.url = self._url,
|
.url = self._url,
|
||||||
.status = header.status,
|
.status = response.status(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (header.contentType()) |ct| {
|
if (response.contentType()) |ct| {
|
||||||
self._response_mime = Mime.parse(ct) catch |e| {
|
self._response_mime = Mime.parse(ct) catch |e| {
|
||||||
log.info(.http, "invalid content type", .{
|
log.info(.http, "invalid content type", .{
|
||||||
.content_Type = ct,
|
.content_Type = ct,
|
||||||
@@ -420,18 +424,18 @@ fn httpHeaderDoneCallback(transfer: *HttpClient.Transfer) !bool {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
var it = transfer.responseHeaderIterator();
|
var it = response.headerIterator();
|
||||||
while (it.next()) |hdr| {
|
while (it.next()) |hdr| {
|
||||||
const joined = try std.fmt.allocPrint(self._arena, "{s}: {s}", .{ hdr.name, hdr.value });
|
const joined = try std.fmt.allocPrint(self._arena, "{s}: {s}", .{ hdr.name, hdr.value });
|
||||||
try self._response_headers.append(self._arena, joined);
|
try self._response_headers.append(self._arena, joined);
|
||||||
}
|
}
|
||||||
|
|
||||||
self._response_status = header.status;
|
self._response_status = response.status().?;
|
||||||
if (transfer.getContentLength()) |cl| {
|
if (response.contentLength()) |cl| {
|
||||||
self._response_len = cl;
|
self._response_len = cl;
|
||||||
try self._response_data.ensureTotalCapacity(self._arena, cl);
|
try self._response_data.ensureTotalCapacity(self._arena, cl);
|
||||||
}
|
}
|
||||||
self._response_url = try self._arena.dupeZ(u8, std.mem.span(header.url));
|
self._response_url = try self._arena.dupeZ(u8, response.url());
|
||||||
|
|
||||||
const page = self._page;
|
const page = self._page;
|
||||||
|
|
||||||
@@ -446,8 +450,8 @@ fn httpHeaderDoneCallback(transfer: *HttpClient.Transfer) !bool {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn httpDataCallback(transfer: *HttpClient.Transfer, data: []const u8) !void {
|
fn httpDataCallback(response: HttpClient.Response, data: []const u8) !void {
|
||||||
const self: *XMLHttpRequest = @ptrCast(@alignCast(transfer.ctx));
|
const self: *XMLHttpRequest = @ptrCast(@alignCast(response.ctx));
|
||||||
try self._response_data.appendSlice(self._arena, data);
|
try self._response_data.appendSlice(self._arena, data);
|
||||||
|
|
||||||
const page = self._page;
|
const page = self._page;
|
||||||
@@ -470,7 +474,7 @@ fn httpDoneCallback(ctx: *anyopaque) !void {
|
|||||||
|
|
||||||
// Not that the request is done, the http/client will free the transfer
|
// Not that the request is done, the http/client will free the transfer
|
||||||
// object. It isn't safe to keep it around.
|
// object. It isn't safe to keep it around.
|
||||||
self._transfer = null;
|
self._http_response = null;
|
||||||
|
|
||||||
const page = self._page;
|
const page = self._page;
|
||||||
|
|
||||||
@@ -486,29 +490,31 @@ fn httpDoneCallback(ctx: *anyopaque) !void {
|
|||||||
.loaded = loaded,
|
.loaded = loaded,
|
||||||
}, page);
|
}, page);
|
||||||
|
|
||||||
page.js.weakRef(self);
|
self.releaseRef(page._session);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn httpErrorCallback(ctx: *anyopaque, err: anyerror) void {
|
fn httpErrorCallback(ctx: *anyopaque, err: anyerror) void {
|
||||||
const self: *XMLHttpRequest = @ptrCast(@alignCast(ctx));
|
const self: *XMLHttpRequest = @ptrCast(@alignCast(ctx));
|
||||||
// http client will close it after an error, it isn't safe to keep around
|
// http client will close it after an error, it isn't safe to keep around
|
||||||
self._transfer = null;
|
|
||||||
self.handleError(err);
|
self.handleError(err);
|
||||||
self._page.js.weakRef(self);
|
if (self._http_response != null) {
|
||||||
|
self._http_response = null;
|
||||||
|
self.releaseRef(self._page._session);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn httpShutdownCallback(ctx: *anyopaque) void {
|
fn httpShutdownCallback(ctx: *anyopaque) void {
|
||||||
const self: *XMLHttpRequest = @ptrCast(@alignCast(ctx));
|
const self: *XMLHttpRequest = @ptrCast(@alignCast(ctx));
|
||||||
self._transfer = null;
|
self._http_response = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn abort(self: *XMLHttpRequest) void {
|
pub fn abort(self: *XMLHttpRequest) void {
|
||||||
self.handleError(error.Abort);
|
self.handleError(error.Abort);
|
||||||
if (self._transfer) |transfer| {
|
if (self._http_response) |resp| {
|
||||||
transfer.abort(error.Abort);
|
resp.abort(error.Abort);
|
||||||
self._transfer = null;
|
self._http_response = null;
|
||||||
|
self.releaseRef(self._page._session);
|
||||||
}
|
}
|
||||||
self._page.js.weakRef(self);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handleError(self: *XMLHttpRequest, err: anyerror) void {
|
fn handleError(self: *XMLHttpRequest, err: anyerror) void {
|
||||||
@@ -582,8 +588,6 @@ pub const JsApi = struct {
|
|||||||
pub const name = "XMLHttpRequest";
|
pub const name = "XMLHttpRequest";
|
||||||
pub const prototype_chain = bridge.prototypeChain();
|
pub const prototype_chain = bridge.prototypeChain();
|
||||||
pub var class_id: bridge.ClassId = undefined;
|
pub var class_id: bridge.ClassId = undefined;
|
||||||
pub const weak = true;
|
|
||||||
pub const finalizer = bridge.finalizer(XMLHttpRequest.deinit);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const constructor = bridge.constructor(XMLHttpRequest.init, .{});
|
pub const constructor = bridge.constructor(XMLHttpRequest.init, .{});
|
||||||
|
|||||||
127
src/cdp/CDP.zig
127
src/cdp/CDP.zig
@@ -63,7 +63,7 @@ target_id_gen: TargetIdGen = .{},
|
|||||||
session_id_gen: SessionIdGen = .{},
|
session_id_gen: SessionIdGen = .{},
|
||||||
browser_context_id_gen: BrowserContextIdGen = .{},
|
browser_context_id_gen: BrowserContextIdGen = .{},
|
||||||
|
|
||||||
browser_context: ?BrowserContext,
|
browser_context: ?BrowserContext(CDP),
|
||||||
|
|
||||||
// Re-used arena for processing a message. We're assuming that we're getting
|
// Re-used arena for processing a message. We're assuming that we're getting
|
||||||
// 1 message at a time.
|
// 1 message at a time.
|
||||||
@@ -120,7 +120,7 @@ pub fn handleMessage(self: *CDP, msg: []const u8) bool {
|
|||||||
pub fn processMessage(self: *CDP, msg: []const u8) !void {
|
pub fn processMessage(self: *CDP, msg: []const u8) !void {
|
||||||
const arena = &self.message_arena;
|
const arena = &self.message_arena;
|
||||||
defer _ = arena.reset(.{ .retain_with_limit = 1024 * 16 });
|
defer _ = arena.reset(.{ .retain_with_limit = 1024 * 16 });
|
||||||
return self.dispatch(arena.allocator(), .{ .cdp = self }, msg);
|
return self.dispatch(arena.allocator(), self, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
// @newhttp
|
// @newhttp
|
||||||
@@ -136,12 +136,12 @@ pub fn pageWait(self: *CDP, ms: u32) !Session.Runner.CDPWaitResult {
|
|||||||
// Called from above, in processMessage which handles client messages
|
// Called from above, in processMessage which handles client messages
|
||||||
// but can also be called internally. For example, Target.sendMessageToTarget
|
// but can also be called internally. For example, Target.sendMessageToTarget
|
||||||
// calls back into dispatch to capture the response.
|
// calls back into dispatch to capture the response.
|
||||||
pub fn dispatch(self: *CDP, arena: Allocator, sender: Command.Sender, str: []const u8) !void {
|
pub fn dispatch(self: *CDP, arena: Allocator, sender: anytype, str: []const u8) !void {
|
||||||
const input = json.parseFromSliceLeaky(InputMessage, arena, str, .{
|
const input = json.parseFromSliceLeaky(InputMessage, arena, str, .{
|
||||||
.ignore_unknown_fields = true,
|
.ignore_unknown_fields = true,
|
||||||
}) catch return error.InvalidJSON;
|
}) catch return error.InvalidJSON;
|
||||||
|
|
||||||
var command = Command{
|
var command = Command(CDP, @TypeOf(sender)){
|
||||||
.input = .{
|
.input = .{
|
||||||
.json = str,
|
.json = str,
|
||||||
.id = input.id,
|
.id = input.id,
|
||||||
@@ -186,7 +186,7 @@ pub fn dispatch(self: *CDP, arena: Allocator, sender: Command.Sender, str: []con
|
|||||||
// "special" handling - the bare minimum we need to do until the driver
|
// "special" handling - the bare minimum we need to do until the driver
|
||||||
// switches to a real BrowserContext.
|
// switches to a real BrowserContext.
|
||||||
// (I can imagine this logic will become driver-specific)
|
// (I can imagine this logic will become driver-specific)
|
||||||
fn dispatchStartupCommand(command: *Command, method: []const u8) !void {
|
fn dispatchStartupCommand(command: anytype, method: []const u8) !void {
|
||||||
// Stagehand parses the response and error if we don't return a
|
// Stagehand parses the response and error if we don't return a
|
||||||
// correct one for Page.getFrameTree on startup call.
|
// correct one for Page.getFrameTree on startup call.
|
||||||
if (std.mem.eql(u8, method, "Page.getFrameTree")) {
|
if (std.mem.eql(u8, method, "Page.getFrameTree")) {
|
||||||
@@ -197,7 +197,7 @@ fn dispatchStartupCommand(command: *Command, method: []const u8) !void {
|
|||||||
return command.sendResult(null, .{});
|
return command.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dispatchCommand(command: *Command, method: []const u8) !void {
|
fn dispatchCommand(command: anytype, method: []const u8) !void {
|
||||||
const domain = blk: {
|
const domain = blk: {
|
||||||
const i = std.mem.indexOfScalarPos(u8, method, 0, '.') orelse {
|
const i = std.mem.indexOfScalarPos(u8, method, 0, '.') orelse {
|
||||||
return error.InvalidMethod;
|
return error.InvalidMethod;
|
||||||
@@ -273,10 +273,10 @@ pub fn createBrowserContext(self: *CDP) ![]const u8 {
|
|||||||
}
|
}
|
||||||
const id = self.browser_context_id_gen.next();
|
const id = self.browser_context_id_gen.next();
|
||||||
|
|
||||||
self.browser_context = @as(BrowserContext, undefined);
|
self.browser_context = @as(BrowserContext(CDP), undefined);
|
||||||
const browser_context = &self.browser_context.?;
|
const browser_context = &self.browser_context.?;
|
||||||
|
|
||||||
try BrowserContext.init(browser_context, id, self);
|
try BrowserContext(CDP).init(browser_context, id, self);
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -308,7 +308,7 @@ pub fn sendJSON(self: *CDP, message: anytype) !void {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const BrowserContext = struct {
|
pub fn BrowserContext(comptime CDP_T: type) type {
|
||||||
const Node = @import("Node.zig");
|
const Node = @import("Node.zig");
|
||||||
const AXNode = @import("AXNode.zig");
|
const AXNode = @import("AXNode.zig");
|
||||||
|
|
||||||
@@ -317,8 +317,9 @@ pub const BrowserContext = struct {
|
|||||||
data: std.ArrayList(u8),
|
data: std.ArrayList(u8),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
return struct {
|
||||||
id: []const u8,
|
id: []const u8,
|
||||||
cdp: *CDP,
|
cdp: *CDP_T,
|
||||||
|
|
||||||
// Represents the browser session. There is no equivalent in CDP. For
|
// Represents the browser session. There is no equivalent in CDP. For
|
||||||
// all intents and purpose, from CDP's point of view our Browser and
|
// all intents and purpose, from CDP's point of view our Browser and
|
||||||
@@ -385,7 +386,9 @@ pub const BrowserContext = struct {
|
|||||||
|
|
||||||
notification: *Notification,
|
notification: *Notification,
|
||||||
|
|
||||||
fn init(self: *BrowserContext, id: []const u8, cdp: *CDP) !void {
|
const Self = @This();
|
||||||
|
|
||||||
|
fn init(self: *Self, id: []const u8, cdp: *CDP_T) !void {
|
||||||
const allocator = cdp.allocator;
|
const allocator = cdp.allocator;
|
||||||
|
|
||||||
// Create notification for this BrowserContext
|
// Create notification for this BrowserContext
|
||||||
@@ -431,7 +434,7 @@ pub const BrowserContext = struct {
|
|||||||
try notification.register(.page_frame_created, self, onPageFrameCreated);
|
try notification.register(.page_frame_created, self, onPageFrameCreated);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn deinit(self: *BrowserContext) void {
|
pub fn deinit(self: *Self) void {
|
||||||
const browser = &self.cdp.browser;
|
const browser = &self.cdp.browser;
|
||||||
const env = &browser.env;
|
const env = &browser.env;
|
||||||
|
|
||||||
@@ -477,12 +480,12 @@ pub const BrowserContext = struct {
|
|||||||
self.intercept_state.deinit();
|
self.intercept_state.deinit();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn reset(self: *BrowserContext) void {
|
pub fn reset(self: *Self) void {
|
||||||
self.node_registry.reset();
|
self.node_registry.reset();
|
||||||
self.node_search_list.reset();
|
self.node_search_list.reset();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn createIsolatedWorld(self: *BrowserContext, world_name: []const u8, grant_universal_access: bool) !*IsolatedWorld {
|
pub fn createIsolatedWorld(self: *Self, world_name: []const u8, grant_universal_access: bool) !*IsolatedWorld {
|
||||||
const browser = &self.cdp.browser;
|
const browser = &self.cdp.browser;
|
||||||
const arena = try browser.arena_pool.acquire(.{ .debug = "IsolatedWorld" });
|
const arena = try browser.arena_pool.acquire(.{ .debug = "IsolatedWorld" });
|
||||||
errdefer browser.arena_pool.release(arena);
|
errdefer browser.arena_pool.release(arena);
|
||||||
@@ -505,7 +508,7 @@ pub const BrowserContext = struct {
|
|||||||
return world;
|
return world;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn nodeWriter(self: *BrowserContext, root: *const Node, opts: Node.Writer.Opts) Node.Writer {
|
pub fn nodeWriter(self: *Self, root: *const Node, opts: Node.Writer.Opts) Node.Writer {
|
||||||
return .{
|
return .{
|
||||||
.root = root,
|
.root = root,
|
||||||
.depth = opts.depth,
|
.depth = opts.depth,
|
||||||
@@ -514,7 +517,7 @@ pub const BrowserContext = struct {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn axnodeWriter(self: *BrowserContext, root: *const Node, opts: AXNode.Writer.Opts) !AXNode.Writer {
|
pub fn axnodeWriter(self: *Self, root: *const Node, opts: AXNode.Writer.Opts) !AXNode.Writer {
|
||||||
const page = self.session.currentPage() orelse return error.PageNotLoaded;
|
const page = self.session.currentPage() orelse return error.PageNotLoaded;
|
||||||
_ = opts;
|
_ = opts;
|
||||||
return .{
|
return .{
|
||||||
@@ -524,13 +527,13 @@ pub const BrowserContext = struct {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn getURL(self: *const BrowserContext) ?[:0]const u8 {
|
pub fn getURL(self: *const Self) ?[:0]const u8 {
|
||||||
const page = self.session.currentPage() orelse return null;
|
const page = self.session.currentPage() orelse return null;
|
||||||
const url = page.url;
|
const url = page.url;
|
||||||
return if (url.len == 0) null else url;
|
return if (url.len == 0) null else url;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn getTitle(self: *const BrowserContext) ?[]const u8 {
|
pub fn getTitle(self: *const Self) ?[]const u8 {
|
||||||
const page = self.session.currentPage() orelse return null;
|
const page = self.session.currentPage() orelse return null;
|
||||||
return page.getTitle() catch |err| {
|
return page.getTitle() catch |err| {
|
||||||
log.err(.cdp, "page title", .{ .err = err });
|
log.err(.cdp, "page title", .{ .err = err });
|
||||||
@@ -538,7 +541,7 @@ pub const BrowserContext = struct {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn networkEnable(self: *BrowserContext) !void {
|
pub fn networkEnable(self: *Self) !void {
|
||||||
try self.notification.register(.http_request_fail, self, onHttpRequestFail);
|
try self.notification.register(.http_request_fail, self, onHttpRequestFail);
|
||||||
try self.notification.register(.http_request_start, self, onHttpRequestStart);
|
try self.notification.register(.http_request_start, self, onHttpRequestStart);
|
||||||
try self.notification.register(.http_request_done, self, onHttpRequestDone);
|
try self.notification.register(.http_request_done, self, onHttpRequestDone);
|
||||||
@@ -546,7 +549,7 @@ pub const BrowserContext = struct {
|
|||||||
try self.notification.register(.http_response_header_done, self, onHttpResponseHeadersDone);
|
try self.notification.register(.http_response_header_done, self, onHttpResponseHeadersDone);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn networkDisable(self: *BrowserContext) void {
|
pub fn networkDisable(self: *Self) void {
|
||||||
self.notification.unregister(.http_request_fail, self);
|
self.notification.unregister(.http_request_fail, self);
|
||||||
self.notification.unregister(.http_request_start, self);
|
self.notification.unregister(.http_request_start, self);
|
||||||
self.notification.unregister(.http_request_done, self);
|
self.notification.unregister(.http_request_done, self);
|
||||||
@@ -554,83 +557,83 @@ pub const BrowserContext = struct {
|
|||||||
self.notification.unregister(.http_response_header_done, self);
|
self.notification.unregister(.http_response_header_done, self);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetchEnable(self: *BrowserContext, authRequests: bool) !void {
|
pub fn fetchEnable(self: *Self, authRequests: bool) !void {
|
||||||
try self.notification.register(.http_request_intercept, self, onHttpRequestIntercept);
|
try self.notification.register(.http_request_intercept, self, onHttpRequestIntercept);
|
||||||
if (authRequests) {
|
if (authRequests) {
|
||||||
try self.notification.register(.http_request_auth_required, self, onHttpRequestAuthRequired);
|
try self.notification.register(.http_request_auth_required, self, onHttpRequestAuthRequired);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn fetchDisable(self: *BrowserContext) void {
|
pub fn fetchDisable(self: *Self) void {
|
||||||
self.notification.unregister(.http_request_intercept, self);
|
self.notification.unregister(.http_request_intercept, self);
|
||||||
self.notification.unregister(.http_request_auth_required, self);
|
self.notification.unregister(.http_request_auth_required, self);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn lifecycleEventsEnable(self: *BrowserContext) !void {
|
pub fn lifecycleEventsEnable(self: *Self) !void {
|
||||||
self.page_life_cycle_events = true;
|
self.page_life_cycle_events = true;
|
||||||
try self.notification.register(.page_network_idle, self, onPageNetworkIdle);
|
try self.notification.register(.page_network_idle, self, onPageNetworkIdle);
|
||||||
try self.notification.register(.page_network_almost_idle, self, onPageNetworkAlmostIdle);
|
try self.notification.register(.page_network_almost_idle, self, onPageNetworkAlmostIdle);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn lifecycleEventsDisable(self: *BrowserContext) void {
|
pub fn lifecycleEventsDisable(self: *Self) void {
|
||||||
self.page_life_cycle_events = false;
|
self.page_life_cycle_events = false;
|
||||||
self.notification.unregister(.page_network_idle, self);
|
self.notification.unregister(.page_network_idle, self);
|
||||||
self.notification.unregister(.page_network_almost_idle, self);
|
self.notification.unregister(.page_network_almost_idle, self);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onPageRemove(ctx: *anyopaque, _: Notification.PageRemove) !void {
|
pub fn onPageRemove(ctx: *anyopaque, _: Notification.PageRemove) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
try @import("domains/page.zig").pageRemove(self);
|
try @import("domains/page.zig").pageRemove(self);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onPageCreated(ctx: *anyopaque, page: *Page) !void {
|
pub fn onPageCreated(ctx: *anyopaque, page: *Page) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
return @import("domains/page.zig").pageCreated(self, page);
|
return @import("domains/page.zig").pageCreated(self, page);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onPageNavigate(ctx: *anyopaque, msg: *const Notification.PageNavigate) !void {
|
pub fn onPageNavigate(ctx: *anyopaque, msg: *const Notification.PageNavigate) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
return @import("domains/page.zig").pageNavigate(self, msg);
|
return @import("domains/page.zig").pageNavigate(self, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onPageNavigated(ctx: *anyopaque, msg: *const Notification.PageNavigated) !void {
|
pub fn onPageNavigated(ctx: *anyopaque, msg: *const Notification.PageNavigated) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
defer self.resetNotificationArena();
|
defer self.resetNotificationArena();
|
||||||
return @import("domains/page.zig").pageNavigated(self.notification_arena, self, msg);
|
return @import("domains/page.zig").pageNavigated(self.notification_arena, self, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onPageFrameCreated(ctx: *anyopaque, msg: *const Notification.PageFrameCreated) !void {
|
pub fn onPageFrameCreated(ctx: *anyopaque, msg: *const Notification.PageFrameCreated) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
return @import("domains/page.zig").pageFrameCreated(self, msg);
|
return @import("domains/page.zig").pageFrameCreated(self, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onPageNetworkIdle(ctx: *anyopaque, msg: *const Notification.PageNetworkIdle) !void {
|
pub fn onPageNetworkIdle(ctx: *anyopaque, msg: *const Notification.PageNetworkIdle) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
return @import("domains/page.zig").pageNetworkIdle(self, msg);
|
return @import("domains/page.zig").pageNetworkIdle(self, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onPageNetworkAlmostIdle(ctx: *anyopaque, msg: *const Notification.PageNetworkAlmostIdle) !void {
|
pub fn onPageNetworkAlmostIdle(ctx: *anyopaque, msg: *const Notification.PageNetworkAlmostIdle) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
return @import("domains/page.zig").pageNetworkAlmostIdle(self, msg);
|
return @import("domains/page.zig").pageNetworkAlmostIdle(self, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onHttpRequestStart(ctx: *anyopaque, msg: *const Notification.RequestStart) !void {
|
pub fn onHttpRequestStart(ctx: *anyopaque, msg: *const Notification.RequestStart) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
try @import("domains/network.zig").httpRequestStart(self, msg);
|
try @import("domains/network.zig").httpRequestStart(self, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onHttpRequestIntercept(ctx: *anyopaque, msg: *const Notification.RequestIntercept) !void {
|
pub fn onHttpRequestIntercept(ctx: *anyopaque, msg: *const Notification.RequestIntercept) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
try @import("domains/fetch.zig").requestIntercept(self, msg);
|
try @import("domains/fetch.zig").requestIntercept(self, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onHttpRequestFail(ctx: *anyopaque, msg: *const Notification.RequestFail) !void {
|
pub fn onHttpRequestFail(ctx: *anyopaque, msg: *const Notification.RequestFail) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
return @import("domains/network.zig").httpRequestFail(self, msg);
|
return @import("domains/network.zig").httpRequestFail(self, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onHttpResponseHeadersDone(ctx: *anyopaque, msg: *const Notification.ResponseHeaderDone) !void {
|
pub fn onHttpResponseHeadersDone(ctx: *anyopaque, msg: *const Notification.ResponseHeaderDone) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
defer self.resetNotificationArena();
|
defer self.resetNotificationArena();
|
||||||
|
|
||||||
const arena = self.page_arena;
|
const arena = self.page_arena;
|
||||||
@@ -665,12 +668,12 @@ pub const BrowserContext = struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn onHttpRequestDone(ctx: *anyopaque, msg: *const Notification.RequestDone) !void {
|
pub fn onHttpRequestDone(ctx: *anyopaque, msg: *const Notification.RequestDone) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
return @import("domains/network.zig").httpRequestDone(self, msg);
|
return @import("domains/network.zig").httpRequestDone(self, msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn onHttpResponseData(ctx: *anyopaque, msg: *const Notification.ResponseData) !void {
|
pub fn onHttpResponseData(ctx: *anyopaque, msg: *const Notification.ResponseData) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
const arena = self.page_arena;
|
const arena = self.page_arena;
|
||||||
|
|
||||||
const id = msg.transfer.id;
|
const id = msg.transfer.id;
|
||||||
@@ -680,16 +683,16 @@ pub const BrowserContext = struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn onHttpRequestAuthRequired(ctx: *anyopaque, data: *const Notification.RequestAuthRequired) !void {
|
pub fn onHttpRequestAuthRequired(ctx: *anyopaque, data: *const Notification.RequestAuthRequired) !void {
|
||||||
const self: *BrowserContext = @ptrCast(@alignCast(ctx));
|
const self: *Self = @ptrCast(@alignCast(ctx));
|
||||||
defer self.resetNotificationArena();
|
defer self.resetNotificationArena();
|
||||||
try @import("domains/fetch.zig").requestAuthRequired(self, data);
|
try @import("domains/fetch.zig").requestAuthRequired(self, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resetNotificationArena(self: *BrowserContext) void {
|
fn resetNotificationArena(self: *Self) void {
|
||||||
defer _ = self.cdp.notification_arena.reset(.{ .retain_with_limit = 1024 * 64 });
|
defer _ = self.cdp.notification_arena.reset(.{ .retain_with_limit = 1024 * 64 });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn callInspector(self: *const BrowserContext, msg: []const u8) void {
|
pub fn callInspector(self: *const Self, msg: []const u8) void {
|
||||||
self.inspector_session.send(msg);
|
self.inspector_session.send(msg);
|
||||||
self.session.browser.env.runMicrotasks();
|
self.session.browser.env.runMicrotasks();
|
||||||
}
|
}
|
||||||
@@ -720,7 +723,7 @@ pub const BrowserContext = struct {
|
|||||||
// This is hacky x 2. First, we create the JSON payload by gluing our
|
// This is hacky x 2. First, we create the JSON payload by gluing our
|
||||||
// session_id onto it. Second, we're much more client/websocket aware than
|
// session_id onto it. Second, we're much more client/websocket aware than
|
||||||
// we should be.
|
// we should be.
|
||||||
fn sendInspectorMessage(self: *BrowserContext, msg: []const u8) !void {
|
fn sendInspectorMessage(self: *Self, msg: []const u8) !void {
|
||||||
const session_id = self.session_id orelse {
|
const session_id = self.session_id orelse {
|
||||||
// We no longer have an active session. What should we do
|
// We no longer have an active session. What should we do
|
||||||
// in this case?
|
// in this case?
|
||||||
@@ -756,7 +759,8 @@ pub const BrowserContext = struct {
|
|||||||
|
|
||||||
try cdp.client.sendJSONRaw(buf);
|
try cdp.client.sendJSONRaw(buf);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/// see: https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/renderer/bindings/core/v8/V8BindingDesign.md#world
|
/// see: https://chromium.googlesource.com/chromium/src/+/master/third_party/blink/renderer/bindings/core/v8/V8BindingDesign.md#world
|
||||||
/// The current understanding. An isolated world lives in the same isolate, but a separated context.
|
/// The current understanding. An isolated world lives in the same isolate, but a separated context.
|
||||||
@@ -828,16 +832,17 @@ const IsolatedWorld = struct {
|
|||||||
// behaviors. Normally, we're sending the result to the client. But in some cases
|
// behaviors. Normally, we're sending the result to the client. But in some cases
|
||||||
// we want to capture the result. So we want the command.sendResult to be
|
// we want to capture the result. So we want the command.sendResult to be
|
||||||
// generic.
|
// generic.
|
||||||
pub const Command = struct {
|
pub fn Command(comptime CDP_T: type, comptime Sender: type) type {
|
||||||
|
return struct {
|
||||||
// A misc arena that can be used for any allocation for processing
|
// A misc arena that can be used for any allocation for processing
|
||||||
// the message
|
// the message
|
||||||
arena: Allocator,
|
arena: Allocator,
|
||||||
|
|
||||||
// reference to our CDP instance
|
// reference to our CDP instance
|
||||||
cdp: *CDP,
|
cdp: *CDP_T,
|
||||||
|
|
||||||
// The browser context this command targets
|
// The browser context this command targets
|
||||||
browser_context: ?*BrowserContext,
|
browser_context: ?*BrowserContext(CDP_T),
|
||||||
|
|
||||||
// The command input (the id, optional session_id, params, ...)
|
// The command input (the id, optional session_id, params, ...)
|
||||||
input: Input,
|
input: Input,
|
||||||
@@ -848,23 +853,9 @@ pub const Command = struct {
|
|||||||
// be code to capture the data that we were "sending".
|
// be code to capture the data that we were "sending".
|
||||||
sender: Sender,
|
sender: Sender,
|
||||||
|
|
||||||
const Sender = union(enum) {
|
const Self = @This();
|
||||||
cdp: *CDP,
|
|
||||||
capture: *std.Io.Writer,
|
|
||||||
|
|
||||||
pub fn sendJSON(self: Sender, message: anytype) !void {
|
pub fn params(self: *const Self, comptime T: type) !?T {
|
||||||
switch (self) {
|
|
||||||
.cdp => |cdp| return cdp.sendJSON(message),
|
|
||||||
.capture => |writer| {
|
|
||||||
return std.json.Stringify.value(message, .{
|
|
||||||
.emit_null_optional_fields = false,
|
|
||||||
}, writer);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
pub fn params(self: *const Command, comptime T: type) !?T {
|
|
||||||
if (self.input.params) |p| {
|
if (self.input.params) |p| {
|
||||||
return try json.parseFromSliceLeaky(
|
return try json.parseFromSliceLeaky(
|
||||||
T,
|
T,
|
||||||
@@ -876,7 +867,7 @@ pub const Command = struct {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn createBrowserContext(self: *Command) !*BrowserContext {
|
pub fn createBrowserContext(self: *Self) !*BrowserContext(CDP_T) {
|
||||||
_ = try self.cdp.createBrowserContext();
|
_ = try self.cdp.createBrowserContext();
|
||||||
self.browser_context = &(self.cdp.browser_context.?);
|
self.browser_context = &(self.cdp.browser_context.?);
|
||||||
return self.browser_context.?;
|
return self.browser_context.?;
|
||||||
@@ -885,7 +876,7 @@ pub const Command = struct {
|
|||||||
const SendResultOpts = struct {
|
const SendResultOpts = struct {
|
||||||
include_session_id: bool = true,
|
include_session_id: bool = true,
|
||||||
};
|
};
|
||||||
pub fn sendResult(self: *Command, result: anytype, opts: SendResultOpts) !void {
|
pub fn sendResult(self: *Self, result: anytype, opts: SendResultOpts) !void {
|
||||||
return self.sender.sendJSON(.{
|
return self.sender.sendJSON(.{
|
||||||
.id = self.input.id,
|
.id = self.input.id,
|
||||||
.result = if (comptime @typeInfo(@TypeOf(result)) == .null) struct {}{} else result,
|
.result = if (comptime @typeInfo(@TypeOf(result)) == .null) struct {}{} else result,
|
||||||
@@ -893,7 +884,10 @@ pub const Command = struct {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sendEvent(self: *Command, method: []const u8, p: anytype, opts: SendEventOpts) !void {
|
const SendEventOpts = struct {
|
||||||
|
session_id: ?[]const u8 = null,
|
||||||
|
};
|
||||||
|
pub fn sendEvent(self: *Self, method: []const u8, p: anytype, opts: CDP_T.SendEventOpts) !void {
|
||||||
// Events ALWAYS go to the client. self.sender should not be used
|
// Events ALWAYS go to the client. self.sender should not be used
|
||||||
return self.cdp.sendEvent(method, p, opts);
|
return self.cdp.sendEvent(method, p, opts);
|
||||||
}
|
}
|
||||||
@@ -901,7 +895,7 @@ pub const Command = struct {
|
|||||||
const SendErrorOpts = struct {
|
const SendErrorOpts = struct {
|
||||||
include_session_id: bool = true,
|
include_session_id: bool = true,
|
||||||
};
|
};
|
||||||
pub fn sendError(self: *Command, code: i32, message: []const u8, opts: SendErrorOpts) !void {
|
pub fn sendError(self: *Self, code: i32, message: []const u8, opts: SendErrorOpts) !void {
|
||||||
return self.sender.sendJSON(.{
|
return self.sender.sendJSON(.{
|
||||||
.id = self.input.id,
|
.id = self.input.id,
|
||||||
.@"error" = .{ .code = code, .message = message },
|
.@"error" = .{ .code = code, .message = message },
|
||||||
@@ -926,7 +920,8 @@ pub const Command = struct {
|
|||||||
// The full raw json input
|
// The full raw json input
|
||||||
json: []const u8,
|
json: []const u8,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// When we parse a JSON message from the client, this is the structure
|
// When we parse a JSON message from the client, this is the structure
|
||||||
// we always expect
|
// we always expect
|
||||||
|
|||||||
@@ -18,9 +18,8 @@
|
|||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const id = @import("../id.zig");
|
const id = @import("../id.zig");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
enable,
|
enable,
|
||||||
disable,
|
disable,
|
||||||
@@ -33,15 +32,15 @@ pub fn processMessage(cmd: *CDP.Command) !void {
|
|||||||
.getFullAXTree => return getFullAXTree(cmd),
|
.getFullAXTree => return getFullAXTree(cmd),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn enable(cmd: *CDP.Command) !void {
|
fn enable(cmd: anytype) !void {
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn disable(cmd: *CDP.Command) !void {
|
fn disable(cmd: anytype) !void {
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getFullAXTree(cmd: *CDP.Command) !void {
|
fn getFullAXTree(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
depth: ?i32 = null,
|
depth: ?i32 = null,
|
||||||
frameId: ?[]const u8 = null,
|
frameId: ?[]const u8 = null,
|
||||||
|
|||||||
@@ -17,7 +17,6 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
// TODO: hard coded data
|
// TODO: hard coded data
|
||||||
const PROTOCOL_VERSION = "1.3";
|
const PROTOCOL_VERSION = "1.3";
|
||||||
@@ -36,7 +35,7 @@ const PRODUCT = "Chrome/124.0.6367.29";
|
|||||||
const JS_VERSION = "12.4.254.8";
|
const JS_VERSION = "12.4.254.8";
|
||||||
const DEV_TOOLS_WINDOW_ID = 1923710101;
|
const DEV_TOOLS_WINDOW_ID = 1923710101;
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
getVersion,
|
getVersion,
|
||||||
setPermission,
|
setPermission,
|
||||||
@@ -58,7 +57,7 @@ pub fn processMessage(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getVersion(cmd: *CDP.Command) !void {
|
fn getVersion(cmd: anytype) !void {
|
||||||
// TODO: pre-serialize?
|
// TODO: pre-serialize?
|
||||||
return cmd.sendResult(.{
|
return cmd.sendResult(.{
|
||||||
.protocolVersion = PROTOCOL_VERSION,
|
.protocolVersion = PROTOCOL_VERSION,
|
||||||
@@ -70,7 +69,7 @@ fn getVersion(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: noop method
|
// TODO: noop method
|
||||||
fn setDownloadBehavior(cmd: *CDP.Command) !void {
|
fn setDownloadBehavior(cmd: anytype) !void {
|
||||||
// const params = (try cmd.params(struct {
|
// const params = (try cmd.params(struct {
|
||||||
// behavior: []const u8,
|
// behavior: []const u8,
|
||||||
// browserContextId: ?[]const u8 = null,
|
// browserContextId: ?[]const u8 = null,
|
||||||
@@ -81,7 +80,7 @@ fn setDownloadBehavior(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(null, .{ .include_session_id = false });
|
return cmd.sendResult(null, .{ .include_session_id = false });
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getWindowForTarget(cmd: *CDP.Command) !void {
|
fn getWindowForTarget(cmd: anytype) !void {
|
||||||
// const params = (try cmd.params(struct {
|
// const params = (try cmd.params(struct {
|
||||||
// targetId: ?[]const u8 = null,
|
// targetId: ?[]const u8 = null,
|
||||||
// })) orelse return error.InvalidParams;
|
// })) orelse return error.InvalidParams;
|
||||||
@@ -92,22 +91,22 @@ fn getWindowForTarget(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: noop method
|
// TODO: noop method
|
||||||
fn setWindowBounds(cmd: *CDP.Command) !void {
|
fn setWindowBounds(cmd: anytype) !void {
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: noop method
|
// TODO: noop method
|
||||||
fn grantPermissions(cmd: *CDP.Command) !void {
|
fn grantPermissions(cmd: anytype) !void {
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: noop method
|
// TODO: noop method
|
||||||
fn setPermission(cmd: *CDP.Command) !void {
|
fn setPermission(cmd: anytype) !void {
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: noop method
|
// TODO: noop method
|
||||||
fn resetPermissions(cmd: *CDP.Command) !void {
|
fn resetPermissions(cmd: anytype) !void {
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,9 +17,8 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
enable,
|
enable,
|
||||||
}, cmd.input.action) orelse return error.UnknownMethod;
|
}, cmd.input.action) orelse return error.UnknownMethod;
|
||||||
|
|||||||
@@ -18,18 +18,17 @@
|
|||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const id = @import("../id.zig");
|
const id = @import("../id.zig");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
const Node = @import("../Node.zig");
|
|
||||||
|
|
||||||
const log = @import("../../log.zig");
|
const log = @import("../../log.zig");
|
||||||
const dump = @import("../../browser/dump.zig");
|
const Node = @import("../Node.zig");
|
||||||
const js = @import("../../browser/js/js.zig");
|
|
||||||
const DOMNode = @import("../../browser/webapi/Node.zig");
|
const DOMNode = @import("../../browser/webapi/Node.zig");
|
||||||
const Selector = @import("../../browser/webapi/selector/Selector.zig");
|
const Selector = @import("../../browser/webapi/selector/Selector.zig");
|
||||||
|
|
||||||
|
const dump = @import("../../browser/dump.zig");
|
||||||
|
const js = @import("../../browser/js/js.zig");
|
||||||
|
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
enable,
|
enable,
|
||||||
getDocument,
|
getDocument,
|
||||||
@@ -70,7 +69,7 @@ pub fn processMessage(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-getDocument
|
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-getDocument
|
||||||
fn getDocument(cmd: *CDP.Command) !void {
|
fn getDocument(cmd: anytype) !void {
|
||||||
const Params = struct {
|
const Params = struct {
|
||||||
// CDP documentation implies that 0 isn't valid, but it _does_ work in Chrome
|
// CDP documentation implies that 0 isn't valid, but it _does_ work in Chrome
|
||||||
depth: i32 = 3,
|
depth: i32 = 3,
|
||||||
@@ -90,7 +89,7 @@ fn getDocument(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-performSearch
|
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-performSearch
|
||||||
fn performSearch(cmd: *CDP.Command) !void {
|
fn performSearch(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
query: []const u8,
|
query: []const u8,
|
||||||
includeUserAgentShadowDOM: ?bool = null,
|
includeUserAgentShadowDOM: ?bool = null,
|
||||||
@@ -117,7 +116,7 @@ fn performSearch(cmd: *CDP.Command) !void {
|
|||||||
// hierarchy of each nodes.
|
// hierarchy of each nodes.
|
||||||
// We dispatch event in the reverse order: from the top level to the direct parents.
|
// We dispatch event in the reverse order: from the top level to the direct parents.
|
||||||
// We should dispatch a node only if it has never been sent.
|
// We should dispatch a node only if it has never been sent.
|
||||||
fn dispatchSetChildNodes(cmd: *CDP.Command, dom_nodes: []const *DOMNode) !void {
|
fn dispatchSetChildNodes(cmd: anytype, dom_nodes: []const *DOMNode) !void {
|
||||||
const arena = cmd.arena;
|
const arena = cmd.arena;
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
const session_id = bc.session_id orelse return error.SessionIdNotLoaded;
|
const session_id = bc.session_id orelse return error.SessionIdNotLoaded;
|
||||||
@@ -173,7 +172,7 @@ fn dispatchSetChildNodes(cmd: *CDP.Command, dom_nodes: []const *DOMNode) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-discardSearchResults
|
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-discardSearchResults
|
||||||
fn discardSearchResults(cmd: *CDP.Command) !void {
|
fn discardSearchResults(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
searchId: []const u8,
|
searchId: []const u8,
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
@@ -185,7 +184,7 @@ fn discardSearchResults(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-getSearchResults
|
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-getSearchResults
|
||||||
fn getSearchResults(cmd: *CDP.Command) !void {
|
fn getSearchResults(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
searchId: []const u8,
|
searchId: []const u8,
|
||||||
fromIndex: u32,
|
fromIndex: u32,
|
||||||
@@ -210,7 +209,7 @@ fn getSearchResults(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(.{ .nodeIds = node_ids[params.fromIndex..params.toIndex] }, .{});
|
return cmd.sendResult(.{ .nodeIds = node_ids[params.fromIndex..params.toIndex] }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn querySelector(cmd: *CDP.Command) !void {
|
fn querySelector(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
nodeId: Node.Id,
|
nodeId: Node.Id,
|
||||||
selector: []const u8,
|
selector: []const u8,
|
||||||
@@ -236,7 +235,7 @@ fn querySelector(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn querySelectorAll(cmd: *CDP.Command) !void {
|
fn querySelectorAll(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
nodeId: Node.Id,
|
nodeId: Node.Id,
|
||||||
selector: []const u8,
|
selector: []const u8,
|
||||||
@@ -267,7 +266,7 @@ fn querySelectorAll(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolveNode(cmd: *CDP.Command) !void {
|
fn resolveNode(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
nodeId: ?Node.Id = null,
|
nodeId: ?Node.Id = null,
|
||||||
backendNodeId: ?u32 = null,
|
backendNodeId: ?u32 = null,
|
||||||
@@ -328,7 +327,7 @@ fn resolveNode(cmd: *CDP.Command) !void {
|
|||||||
} }, .{});
|
} }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn describeNode(cmd: *CDP.Command) !void {
|
fn describeNode(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
nodeId: ?Node.Id = null,
|
nodeId: ?Node.Id = null,
|
||||||
backendNodeId: ?Node.Id = null,
|
backendNodeId: ?Node.Id = null,
|
||||||
@@ -375,7 +374,7 @@ fn rectToQuad(rect: DOMNode.Element.DOMRect) Quad {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
fn scrollIntoViewIfNeeded(cmd: *CDP.Command) !void {
|
fn scrollIntoViewIfNeeded(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
nodeId: ?Node.Id = null,
|
nodeId: ?Node.Id = null,
|
||||||
backendNodeId: ?u32 = null,
|
backendNodeId: ?u32 = null,
|
||||||
@@ -398,7 +397,7 @@ fn scrollIntoViewIfNeeded(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getNode(arena: Allocator, bc: *CDP.BrowserContext, node_id: ?Node.Id, backend_node_id: ?Node.Id, object_id: ?[]const u8) !*Node {
|
fn getNode(arena: Allocator, bc: anytype, node_id: ?Node.Id, backend_node_id: ?Node.Id, object_id: ?[]const u8) !*Node {
|
||||||
const input_node_id = node_id orelse backend_node_id;
|
const input_node_id = node_id orelse backend_node_id;
|
||||||
if (input_node_id) |input_node_id_| {
|
if (input_node_id) |input_node_id_| {
|
||||||
return bc.node_registry.lookup_by_id.get(input_node_id_) orelse return error.NodeNotFound;
|
return bc.node_registry.lookup_by_id.get(input_node_id_) orelse return error.NodeNotFound;
|
||||||
@@ -418,7 +417,7 @@ fn getNode(arena: Allocator, bc: *CDP.BrowserContext, node_id: ?Node.Id, backend
|
|||||||
|
|
||||||
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-getContentQuads
|
// https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-getContentQuads
|
||||||
// Related to: https://drafts.csswg.org/cssom-view/#the-geometryutils-interface
|
// Related to: https://drafts.csswg.org/cssom-view/#the-geometryutils-interface
|
||||||
fn getContentQuads(cmd: *CDP.Command) !void {
|
fn getContentQuads(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
nodeId: ?Node.Id = null,
|
nodeId: ?Node.Id = null,
|
||||||
backendNodeId: ?Node.Id = null,
|
backendNodeId: ?Node.Id = null,
|
||||||
@@ -444,7 +443,7 @@ fn getContentQuads(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(.{ .quads = &.{quad} }, .{});
|
return cmd.sendResult(.{ .quads = &.{quad} }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getBoxModel(cmd: *CDP.Command) !void {
|
fn getBoxModel(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
nodeId: ?Node.Id = null,
|
nodeId: ?Node.Id = null,
|
||||||
backendNodeId: ?u32 = null,
|
backendNodeId: ?u32 = null,
|
||||||
@@ -473,7 +472,7 @@ fn getBoxModel(cmd: *CDP.Command) !void {
|
|||||||
} }, .{});
|
} }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn requestChildNodes(cmd: *CDP.Command) !void {
|
fn requestChildNodes(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
nodeId: Node.Id,
|
nodeId: Node.Id,
|
||||||
depth: i32 = 1,
|
depth: i32 = 1,
|
||||||
@@ -497,7 +496,7 @@ fn requestChildNodes(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getFrameOwner(cmd: *CDP.Command) !void {
|
fn getFrameOwner(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
frameId: []const u8,
|
frameId: []const u8,
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
@@ -513,7 +512,7 @@ fn getFrameOwner(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(.{ .nodeId = node.id, .backendNodeId = node.id }, .{});
|
return cmd.sendResult(.{ .nodeId = node.id, .backendNodeId = node.id }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getOuterHTML(cmd: *CDP.Command) !void {
|
fn getOuterHTML(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
nodeId: ?Node.Id = null,
|
nodeId: ?Node.Id = null,
|
||||||
backendNodeId: ?Node.Id = null,
|
backendNodeId: ?Node.Id = null,
|
||||||
@@ -535,7 +534,7 @@ fn getOuterHTML(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(.{ .outerHTML = aw.written() }, .{});
|
return cmd.sendResult(.{ .outerHTML = aw.written() }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn requestNode(cmd: *CDP.Command) !void {
|
fn requestNode(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
objectId: []const u8,
|
objectId: []const u8,
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
|
|||||||
@@ -17,10 +17,9 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
const log = @import("../../log.zig");
|
const log = @import("../../log.zig");
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
setEmulatedMedia,
|
setEmulatedMedia,
|
||||||
setFocusEmulationEnabled,
|
setFocusEmulationEnabled,
|
||||||
@@ -39,7 +38,7 @@ pub fn processMessage(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: noop method
|
// TODO: noop method
|
||||||
fn setEmulatedMedia(cmd: *CDP.Command) !void {
|
fn setEmulatedMedia(cmd: anytype) !void {
|
||||||
// const input = (try const incoming.params(struct {
|
// const input = (try const incoming.params(struct {
|
||||||
// media: ?[]const u8 = null,
|
// media: ?[]const u8 = null,
|
||||||
// features: ?[]struct{
|
// features: ?[]struct{
|
||||||
@@ -52,7 +51,7 @@ fn setEmulatedMedia(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: noop method
|
// TODO: noop method
|
||||||
fn setFocusEmulationEnabled(cmd: *CDP.Command) !void {
|
fn setFocusEmulationEnabled(cmd: anytype) !void {
|
||||||
// const input = (try const incoming.params(struct {
|
// const input = (try const incoming.params(struct {
|
||||||
// enabled: bool,
|
// enabled: bool,
|
||||||
// })) orelse return error.InvalidParams;
|
// })) orelse return error.InvalidParams;
|
||||||
@@ -60,16 +59,16 @@ fn setFocusEmulationEnabled(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: noop method
|
// TODO: noop method
|
||||||
fn setDeviceMetricsOverride(cmd: *CDP.Command) !void {
|
fn setDeviceMetricsOverride(cmd: anytype) !void {
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: noop method
|
// TODO: noop method
|
||||||
fn setTouchEmulationEnabled(cmd: *CDP.Command) !void {
|
fn setTouchEmulationEnabled(cmd: anytype) !void {
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setUserAgentOverride(cmd: *CDP.Command) !void {
|
fn setUserAgentOverride(cmd: anytype) !void {
|
||||||
log.info(.app, "setUserAgentOverride ignored", .{});
|
log.info(.app, "setUserAgentOverride ignored", .{});
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,19 +17,17 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
const Allocator = std.mem.Allocator;
|
||||||
|
|
||||||
const id = @import("../id.zig");
|
const id = @import("../id.zig");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
const log = @import("../../log.zig");
|
const log = @import("../../log.zig");
|
||||||
|
const network = @import("network.zig");
|
||||||
|
|
||||||
const HttpClient = @import("../../browser/HttpClient.zig");
|
const HttpClient = @import("../../browser/HttpClient.zig");
|
||||||
const net_http = @import("../../network/http.zig");
|
const net_http = @import("../../network/http.zig");
|
||||||
const Notification = @import("../../Notification.zig");
|
const Notification = @import("../../Notification.zig");
|
||||||
|
|
||||||
const network = @import("network.zig");
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const Allocator = std.mem.Allocator;
|
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
disable,
|
disable,
|
||||||
enable,
|
enable,
|
||||||
@@ -137,13 +135,13 @@ const ErrorReason = enum {
|
|||||||
BlockedByResponse,
|
BlockedByResponse,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn disable(cmd: *CDP.Command) !void {
|
fn disable(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
bc.fetchDisable();
|
bc.fetchDisable();
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn enable(cmd: *CDP.Command) !void {
|
fn enable(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(EnableParam)) orelse EnableParam{};
|
const params = (try cmd.params(EnableParam)) orelse EnableParam{};
|
||||||
if (!arePatternsSupported(params.patterns)) {
|
if (!arePatternsSupported(params.patterns)) {
|
||||||
log.warn(.not_implemented, "Fetch.enable", .{ .params = "pattern" });
|
log.warn(.not_implemented, "Fetch.enable", .{ .params = "pattern" });
|
||||||
@@ -182,7 +180,7 @@ fn arePatternsSupported(patterns: []RequestPattern) bool {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn requestIntercept(bc: *CDP.BrowserContext, intercept: *const Notification.RequestIntercept) !void {
|
pub fn requestIntercept(bc: anytype, intercept: *const Notification.RequestIntercept) !void {
|
||||||
// detachTarget could be called, in which case, we still have a page doing
|
// detachTarget could be called, in which case, we still have a page doing
|
||||||
// things, but no session.
|
// things, but no session.
|
||||||
const session_id = bc.session_id orelse return;
|
const session_id = bc.session_id orelse return;
|
||||||
@@ -217,7 +215,7 @@ pub fn requestIntercept(bc: *CDP.BrowserContext, intercept: *const Notification.
|
|||||||
intercept.wait_for_interception.* = true;
|
intercept.wait_for_interception.* = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn continueRequest(cmd: *CDP.Command) !void {
|
fn continueRequest(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
requestId: []const u8, // INT-{d}"
|
requestId: []const u8, // INT-{d}"
|
||||||
@@ -277,7 +275,7 @@ const AuthChallengeResponse = enum {
|
|||||||
ProvideCredentials,
|
ProvideCredentials,
|
||||||
};
|
};
|
||||||
|
|
||||||
fn continueWithAuth(cmd: *CDP.Command) !void {
|
fn continueWithAuth(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
requestId: []const u8, // "INT-{d}"
|
requestId: []const u8, // "INT-{d}"
|
||||||
@@ -320,7 +318,7 @@ fn continueWithAuth(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn fulfillRequest(cmd: *CDP.Command) !void {
|
fn fulfillRequest(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
|
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
@@ -362,7 +360,7 @@ fn fulfillRequest(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn failRequest(cmd: *CDP.Command) !void {
|
fn failRequest(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
requestId: []const u8, // "INT-{d}"
|
requestId: []const u8, // "INT-{d}"
|
||||||
@@ -384,7 +382,7 @@ fn failRequest(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn requestAuthRequired(bc: *CDP.BrowserContext, intercept: *const Notification.RequestAuthRequired) !void {
|
pub fn requestAuthRequired(bc: anytype, intercept: *const Notification.RequestAuthRequired) !void {
|
||||||
// detachTarget could be called, in which case, we still have a page doing
|
// detachTarget could be called, in which case, we still have a page doing
|
||||||
// things, but no session.
|
// things, but no session.
|
||||||
const session_id = bc.session_id orelse return;
|
const session_id = bc.session_id orelse return;
|
||||||
|
|||||||
@@ -17,9 +17,8 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
dispatchKeyEvent,
|
dispatchKeyEvent,
|
||||||
dispatchMouseEvent,
|
dispatchMouseEvent,
|
||||||
@@ -34,7 +33,7 @@ pub fn processMessage(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchKeyEvent
|
// https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchKeyEvent
|
||||||
fn dispatchKeyEvent(cmd: *CDP.Command) !void {
|
fn dispatchKeyEvent(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
type: Type,
|
type: Type,
|
||||||
key: []const u8 = "",
|
key: []const u8 = "",
|
||||||
@@ -75,7 +74,7 @@ fn dispatchKeyEvent(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchMouseEvent
|
// https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-dispatchMouseEvent
|
||||||
fn dispatchMouseEvent(cmd: *CDP.Command) !void {
|
fn dispatchMouseEvent(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
x: f64,
|
x: f64,
|
||||||
y: f64,
|
y: f64,
|
||||||
@@ -105,7 +104,7 @@ fn dispatchMouseEvent(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-insertText
|
// https://chromedevtools.github.io/devtools-protocol/tot/Input/#method-insertText
|
||||||
fn insertText(cmd: *CDP.Command) !void {
|
fn insertText(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
text: []const u8, // The text to insert
|
text: []const u8, // The text to insert
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
|
|||||||
@@ -17,9 +17,8 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
enable,
|
enable,
|
||||||
disable,
|
disable,
|
||||||
|
|||||||
@@ -17,9 +17,8 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
enable,
|
enable,
|
||||||
disable,
|
disable,
|
||||||
|
|||||||
@@ -18,18 +18,14 @@
|
|||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const lp = @import("lightpanda");
|
const lp = @import("lightpanda");
|
||||||
|
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
const Node = @import("../Node.zig");
|
|
||||||
|
|
||||||
const DOMNode = @import("../../browser/webapi/Node.zig");
|
|
||||||
|
|
||||||
const markdown = lp.markdown;
|
const markdown = lp.markdown;
|
||||||
const SemanticTree = lp.SemanticTree;
|
const SemanticTree = lp.SemanticTree;
|
||||||
const interactive = lp.interactive;
|
const interactive = lp.interactive;
|
||||||
const structured_data = lp.structured_data;
|
const structured_data = lp.structured_data;
|
||||||
|
const Node = @import("../Node.zig");
|
||||||
|
const DOMNode = @import("../../browser/webapi/Node.zig");
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
getMarkdown,
|
getMarkdown,
|
||||||
getSemanticTree,
|
getSemanticTree,
|
||||||
@@ -55,7 +51,7 @@ pub fn processMessage(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getSemanticTree(cmd: *CDP.Command) !void {
|
fn getSemanticTree(cmd: anytype) !void {
|
||||||
const Params = struct {
|
const Params = struct {
|
||||||
format: ?enum { text } = null,
|
format: ?enum { text } = null,
|
||||||
prune: ?bool = null,
|
prune: ?bool = null,
|
||||||
@@ -100,7 +96,7 @@ fn getSemanticTree(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getMarkdown(cmd: *CDP.Command) !void {
|
fn getMarkdown(cmd: anytype) !void {
|
||||||
const Params = struct {
|
const Params = struct {
|
||||||
nodeId: ?Node.Id = null,
|
nodeId: ?Node.Id = null,
|
||||||
};
|
};
|
||||||
@@ -123,7 +119,7 @@ fn getMarkdown(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getInteractiveElements(cmd: *CDP.Command) !void {
|
fn getInteractiveElements(cmd: anytype) !void {
|
||||||
const Params = struct {
|
const Params = struct {
|
||||||
nodeId: ?Node.Id = null,
|
nodeId: ?Node.Id = null,
|
||||||
};
|
};
|
||||||
@@ -145,7 +141,7 @@ fn getInteractiveElements(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getStructuredData(cmd: *CDP.Command) !void {
|
fn getStructuredData(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.NoBrowserContext;
|
const bc = cmd.browser_context orelse return error.NoBrowserContext;
|
||||||
const page = bc.session.currentPage() orelse return error.PageNotLoaded;
|
const page = bc.session.currentPage() orelse return error.PageNotLoaded;
|
||||||
|
|
||||||
@@ -160,7 +156,7 @@ fn getStructuredData(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn detectForms(cmd: *CDP.Command) !void {
|
fn detectForms(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.NoBrowserContext;
|
const bc = cmd.browser_context orelse return error.NoBrowserContext;
|
||||||
const page = bc.session.currentPage() orelse return error.PageNotLoaded;
|
const page = bc.session.currentPage() orelse return error.PageNotLoaded;
|
||||||
|
|
||||||
@@ -177,7 +173,7 @@ fn detectForms(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn clickNode(cmd: *CDP.Command) !void {
|
fn clickNode(cmd: anytype) !void {
|
||||||
const Params = struct {
|
const Params = struct {
|
||||||
nodeId: ?Node.Id = null,
|
nodeId: ?Node.Id = null,
|
||||||
backendNodeId: ?Node.Id = null,
|
backendNodeId: ?Node.Id = null,
|
||||||
@@ -198,7 +194,7 @@ fn clickNode(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(.{}, .{});
|
return cmd.sendResult(.{}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn fillNode(cmd: *CDP.Command) !void {
|
fn fillNode(cmd: anytype) !void {
|
||||||
const Params = struct {
|
const Params = struct {
|
||||||
nodeId: ?Node.Id = null,
|
nodeId: ?Node.Id = null,
|
||||||
backendNodeId: ?Node.Id = null,
|
backendNodeId: ?Node.Id = null,
|
||||||
@@ -220,7 +216,7 @@ fn fillNode(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(.{}, .{});
|
return cmd.sendResult(.{}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn scrollNode(cmd: *CDP.Command) !void {
|
fn scrollNode(cmd: anytype) !void {
|
||||||
const Params = struct {
|
const Params = struct {
|
||||||
nodeId: ?Node.Id = null,
|
nodeId: ?Node.Id = null,
|
||||||
backendNodeId: ?Node.Id = null,
|
backendNodeId: ?Node.Id = null,
|
||||||
@@ -248,7 +244,7 @@ fn scrollNode(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(.{}, .{});
|
return cmd.sendResult(.{}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn waitForSelector(cmd: *CDP.Command) !void {
|
fn waitForSelector(cmd: anytype) !void {
|
||||||
const Params = struct {
|
const Params = struct {
|
||||||
selector: []const u8,
|
selector: []const u8,
|
||||||
timeout: ?u32 = null,
|
timeout: ?u32 = null,
|
||||||
|
|||||||
@@ -18,21 +18,18 @@
|
|||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const lp = @import("lightpanda");
|
const lp = @import("lightpanda");
|
||||||
|
const Allocator = std.mem.Allocator;
|
||||||
const log = @import("../../log.zig");
|
const log = @import("../../log.zig");
|
||||||
|
|
||||||
const id = @import("../id.zig");
|
const CdpStorage = @import("storage.zig");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
|
const id = @import("../id.zig");
|
||||||
const URL = @import("../../browser/URL.zig");
|
const URL = @import("../../browser/URL.zig");
|
||||||
const Transfer = @import("../../browser/HttpClient.zig").Transfer;
|
const Transfer = @import("../../browser/HttpClient.zig").Transfer;
|
||||||
const Notification = @import("../../Notification.zig");
|
const Notification = @import("../../Notification.zig");
|
||||||
const Mime = @import("../../browser/Mime.zig");
|
const Mime = @import("../../browser/Mime.zig");
|
||||||
|
|
||||||
const CdpStorage = @import("storage.zig");
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const Allocator = std.mem.Allocator;
|
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
enable,
|
enable,
|
||||||
disable,
|
disable,
|
||||||
@@ -62,19 +59,19 @@ pub fn processMessage(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn enable(cmd: *CDP.Command) !void {
|
fn enable(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
try bc.networkEnable();
|
try bc.networkEnable();
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn disable(cmd: *CDP.Command) !void {
|
fn disable(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
bc.networkDisable();
|
bc.networkDisable();
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setExtraHTTPHeaders(cmd: *CDP.Command) !void {
|
fn setExtraHTTPHeaders(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
headers: std.json.ArrayHashMap([]const u8),
|
headers: std.json.ArrayHashMap([]const u8),
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
@@ -113,7 +110,7 @@ fn cookieMatches(cookie: *const Cookie, name: []const u8, domain: ?[]const u8, p
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn deleteCookies(cmd: *CDP.Command) !void {
|
fn deleteCookies(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
name: []const u8,
|
name: []const u8,
|
||||||
url: ?[:0]const u8 = null,
|
url: ?[:0]const u8 = null,
|
||||||
@@ -147,14 +144,14 @@ fn deleteCookies(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn clearBrowserCookies(cmd: *CDP.Command) !void {
|
fn clearBrowserCookies(cmd: anytype) !void {
|
||||||
if (try cmd.params(struct {}) != null) return error.InvalidParams;
|
if (try cmd.params(struct {}) != null) return error.InvalidParams;
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
bc.session.cookie_jar.clearRetainingCapacity();
|
bc.session.cookie_jar.clearRetainingCapacity();
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setCookie(cmd: *CDP.Command) !void {
|
fn setCookie(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(
|
const params = (try cmd.params(
|
||||||
CdpStorage.CdpCookie,
|
CdpStorage.CdpCookie,
|
||||||
)) orelse return error.InvalidParams;
|
)) orelse return error.InvalidParams;
|
||||||
@@ -165,7 +162,7 @@ fn setCookie(cmd: *CDP.Command) !void {
|
|||||||
try cmd.sendResult(.{ .success = true }, .{});
|
try cmd.sendResult(.{ .success = true }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setCookies(cmd: *CDP.Command) !void {
|
fn setCookies(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
cookies: []const CdpStorage.CdpCookie,
|
cookies: []const CdpStorage.CdpCookie,
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
@@ -181,7 +178,7 @@ fn setCookies(cmd: *CDP.Command) !void {
|
|||||||
const GetCookiesParam = struct {
|
const GetCookiesParam = struct {
|
||||||
urls: ?[]const [:0]const u8 = null,
|
urls: ?[]const [:0]const u8 = null,
|
||||||
};
|
};
|
||||||
fn getCookies(cmd: *CDP.Command) !void {
|
fn getCookies(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
const params = (try cmd.params(GetCookiesParam)) orelse GetCookiesParam{};
|
const params = (try cmd.params(GetCookiesParam)) orelse GetCookiesParam{};
|
||||||
|
|
||||||
@@ -204,7 +201,7 @@ fn getCookies(cmd: *CDP.Command) !void {
|
|||||||
try cmd.sendResult(.{ .cookies = writer }, .{});
|
try cmd.sendResult(.{ .cookies = writer }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getResponseBody(cmd: *CDP.Command) !void {
|
fn getResponseBody(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
requestId: []const u8, // "REQ-{d}"
|
requestId: []const u8, // "REQ-{d}"
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
@@ -230,7 +227,7 @@ fn getResponseBody(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn httpRequestFail(bc: *CDP.BrowserContext, msg: *const Notification.RequestFail) !void {
|
pub fn httpRequestFail(bc: anytype, msg: *const Notification.RequestFail) !void {
|
||||||
// It's possible that the request failed because we aborted when the client
|
// It's possible that the request failed because we aborted when the client
|
||||||
// sent Target.closeTarget. In that case, bc.session_id will be cleared
|
// sent Target.closeTarget. In that case, bc.session_id will be cleared
|
||||||
// already, and we can skip sending these messages to the client.
|
// already, and we can skip sending these messages to the client.
|
||||||
@@ -250,7 +247,7 @@ pub fn httpRequestFail(bc: *CDP.BrowserContext, msg: *const Notification.Request
|
|||||||
}, .{ .session_id = session_id });
|
}, .{ .session_id = session_id });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn httpRequestStart(bc: *CDP.BrowserContext, msg: *const Notification.RequestStart) !void {
|
pub fn httpRequestStart(bc: anytype, msg: *const Notification.RequestStart) !void {
|
||||||
// detachTarget could be called, in which case, we still have a page doing
|
// detachTarget could be called, in which case, we still have a page doing
|
||||||
// things, but no session.
|
// things, but no session.
|
||||||
const session_id = bc.session_id orelse return;
|
const session_id = bc.session_id orelse return;
|
||||||
@@ -279,7 +276,7 @@ pub fn httpRequestStart(bc: *CDP.BrowserContext, msg: *const Notification.Reques
|
|||||||
}, .{ .session_id = session_id });
|
}, .{ .session_id = session_id });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn httpResponseHeaderDone(arena: Allocator, bc: *CDP.BrowserContext, msg: *const Notification.ResponseHeaderDone) !void {
|
pub fn httpResponseHeaderDone(arena: Allocator, bc: anytype, msg: *const Notification.ResponseHeaderDone) !void {
|
||||||
// detachTarget could be called, in which case, we still have a page doing
|
// detachTarget could be called, in which case, we still have a page doing
|
||||||
// things, but no session.
|
// things, but no session.
|
||||||
const session_id = bc.session_id orelse return;
|
const session_id = bc.session_id orelse return;
|
||||||
@@ -296,7 +293,7 @@ pub fn httpResponseHeaderDone(arena: Allocator, bc: *CDP.BrowserContext, msg: *c
|
|||||||
}, .{ .session_id = session_id });
|
}, .{ .session_id = session_id });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn httpRequestDone(bc: *CDP.BrowserContext, msg: *const Notification.RequestDone) !void {
|
pub fn httpRequestDone(bc: anytype, msg: *const Notification.RequestDone) !void {
|
||||||
// detachTarget could be called, in which case, we still have a page doing
|
// detachTarget could be called, in which case, we still have a page doing
|
||||||
// things, but no session.
|
// things, but no session.
|
||||||
const session_id = bc.session_id orelse return;
|
const session_id = bc.session_id orelse return;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)
|
||||||
|
|
||||||
//
|
//
|
||||||
// Francis Bouvier <francis@lightpanda.io>
|
// Francis Bouvier <francis@lightpanda.io>
|
||||||
// Pierre Tachoire <pierre@lightpanda.io>
|
// Pierre Tachoire <pierre@lightpanda.io>
|
||||||
@@ -23,8 +22,6 @@ const lp = @import("lightpanda");
|
|||||||
const screenshot_png = @embedFile("screenshot.png");
|
const screenshot_png = @embedFile("screenshot.png");
|
||||||
|
|
||||||
const id = @import("../id.zig");
|
const id = @import("../id.zig");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
const log = @import("../../log.zig");
|
const log = @import("../../log.zig");
|
||||||
const js = @import("../../browser/js/js.zig");
|
const js = @import("../../browser/js/js.zig");
|
||||||
const URL = @import("../../browser/URL.zig");
|
const URL = @import("../../browser/URL.zig");
|
||||||
@@ -34,7 +31,7 @@ const Notification = @import("../../Notification.zig");
|
|||||||
|
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
enable,
|
enable,
|
||||||
getFrameTree,
|
getFrameTree,
|
||||||
@@ -81,7 +78,7 @@ const Frame = struct {
|
|||||||
gatedAPIFeatures: [][]const u8 = &[0][]const u8{},
|
gatedAPIFeatures: [][]const u8 = &[0][]const u8{},
|
||||||
};
|
};
|
||||||
|
|
||||||
fn getFrameTree(cmd: *CDP.Command) !void {
|
fn getFrameTree(cmd: anytype) !void {
|
||||||
// Stagehand parses the response and error if we don't return a
|
// Stagehand parses the response and error if we don't return a
|
||||||
// correct one for this call when browser context or target id are missing.
|
// correct one for this call when browser context or target id are missing.
|
||||||
const startup = .{
|
const startup = .{
|
||||||
@@ -111,7 +108,7 @@ fn getFrameTree(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setLifecycleEventsEnabled(cmd: *CDP.Command) !void {
|
fn setLifecycleEventsEnabled(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
enabled: bool,
|
enabled: bool,
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
@@ -152,7 +149,7 @@ fn setLifecycleEventsEnabled(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn addScriptToEvaluateOnNewDocument(cmd: *CDP.Command) !void {
|
fn addScriptToEvaluateOnNewDocument(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
source: []const u8,
|
source: []const u8,
|
||||||
worldName: ?[]const u8 = null,
|
worldName: ?[]const u8 = null,
|
||||||
@@ -182,7 +179,7 @@ fn addScriptToEvaluateOnNewDocument(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn removeScriptToEvaluateOnNewDocument(cmd: *CDP.Command) !void {
|
fn removeScriptToEvaluateOnNewDocument(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
identifier: []const u8,
|
identifier: []const u8,
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
@@ -201,7 +198,7 @@ fn removeScriptToEvaluateOnNewDocument(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn close(cmd: *CDP.Command) !void {
|
fn close(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
|
|
||||||
const target_id = bc.target_id orelse return error.TargetNotLoaded;
|
const target_id = bc.target_id orelse return error.TargetNotLoaded;
|
||||||
@@ -238,7 +235,7 @@ fn close(cmd: *CDP.Command) !void {
|
|||||||
bc.target_id = null;
|
bc.target_id = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn createIsolatedWorld(cmd: *CDP.Command) !void {
|
fn createIsolatedWorld(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
frameId: []const u8,
|
frameId: []const u8,
|
||||||
worldName: []const u8,
|
worldName: []const u8,
|
||||||
@@ -258,7 +255,7 @@ fn createIsolatedWorld(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(.{ .executionContextId = js_context.id }, .{});
|
return cmd.sendResult(.{ .executionContextId = js_context.id }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn navigate(cmd: *CDP.Command) !void {
|
fn navigate(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
url: [:0]const u8,
|
url: [:0]const u8,
|
||||||
// referrer: ?[]const u8 = null,
|
// referrer: ?[]const u8 = null,
|
||||||
@@ -292,7 +289,7 @@ fn navigate(cmd: *CDP.Command) !void {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn doReload(cmd: *CDP.Command) !void {
|
fn doReload(cmd: anytype) !void {
|
||||||
const params = try cmd.params(struct {
|
const params = try cmd.params(struct {
|
||||||
ignoreCache: ?bool = null,
|
ignoreCache: ?bool = null,
|
||||||
scriptToEvaluateOnLoad: ?[]const u8 = null,
|
scriptToEvaluateOnLoad: ?[]const u8 = null,
|
||||||
@@ -322,7 +319,7 @@ fn doReload(cmd: *CDP.Command) !void {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn pageNavigate(bc: *CDP.BrowserContext, event: *const Notification.PageNavigate) !void {
|
pub fn pageNavigate(bc: anytype, event: *const Notification.PageNavigate) !void {
|
||||||
// detachTarget could be called, in which case, we still have a page doing
|
// detachTarget could be called, in which case, we still have a page doing
|
||||||
// things, but no session.
|
// things, but no session.
|
||||||
const session_id = bc.session_id orelse return;
|
const session_id = bc.session_id orelse return;
|
||||||
@@ -374,7 +371,7 @@ pub fn pageNavigate(bc: *CDP.BrowserContext, event: *const Notification.PageNavi
|
|||||||
}, .{ .session_id = session_id });
|
}, .{ .session_id = session_id });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn pageRemove(bc: *CDP.BrowserContext) !void {
|
pub fn pageRemove(bc: anytype) !void {
|
||||||
// Clear all remote object mappings to prevent stale objectIds from being used
|
// Clear all remote object mappings to prevent stale objectIds from being used
|
||||||
// after the context is destroy
|
// after the context is destroy
|
||||||
bc.inspector_session.inspector.resetContextGroup();
|
bc.inspector_session.inspector.resetContextGroup();
|
||||||
@@ -385,7 +382,7 @@ pub fn pageRemove(bc: *CDP.BrowserContext) !void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn pageCreated(bc: *CDP.BrowserContext, page: *Page) !void {
|
pub fn pageCreated(bc: anytype, page: *Page) !void {
|
||||||
_ = bc.cdp.page_arena.reset(.{ .retain_with_limit = 1024 * 512 });
|
_ = bc.cdp.page_arena.reset(.{ .retain_with_limit = 1024 * 512 });
|
||||||
|
|
||||||
for (bc.isolated_worlds.items) |isolated_world| {
|
for (bc.isolated_worlds.items) |isolated_world| {
|
||||||
@@ -397,7 +394,7 @@ pub fn pageCreated(bc: *CDP.BrowserContext, page: *Page) !void {
|
|||||||
bc.captured_responses = .empty;
|
bc.captured_responses = .empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn pageFrameCreated(bc: *CDP.BrowserContext, event: *const Notification.PageFrameCreated) !void {
|
pub fn pageFrameCreated(bc: anytype, event: *const Notification.PageFrameCreated) !void {
|
||||||
const session_id = bc.session_id orelse return;
|
const session_id = bc.session_id orelse return;
|
||||||
|
|
||||||
const cdp = bc.cdp;
|
const cdp = bc.cdp;
|
||||||
@@ -418,7 +415,7 @@ pub fn pageFrameCreated(bc: *CDP.BrowserContext, event: *const Notification.Page
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn pageNavigated(arena: Allocator, bc: *CDP.BrowserContext, event: *const Notification.PageNavigated) !void {
|
pub fn pageNavigated(arena: Allocator, bc: anytype, event: *const Notification.PageNavigated) !void {
|
||||||
// detachTarget could be called, in which case, we still have a page doing
|
// detachTarget could be called, in which case, we still have a page doing
|
||||||
// things, but no session.
|
// things, but no session.
|
||||||
const session_id = bc.session_id orelse return;
|
const session_id = bc.session_id orelse return;
|
||||||
@@ -600,15 +597,15 @@ pub fn pageNavigated(arena: Allocator, bc: *CDP.BrowserContext, event: *const No
|
|||||||
}, .{ .session_id = session_id });
|
}, .{ .session_id = session_id });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn pageNetworkIdle(bc: *CDP.BrowserContext, event: *const Notification.PageNetworkIdle) !void {
|
pub fn pageNetworkIdle(bc: anytype, event: *const Notification.PageNetworkIdle) !void {
|
||||||
return sendPageLifecycle(bc, "networkIdle", event.timestamp, &id.toFrameId(event.frame_id), &id.toLoaderId(event.req_id));
|
return sendPageLifecycle(bc, "networkIdle", event.timestamp, &id.toFrameId(event.frame_id), &id.toLoaderId(event.req_id));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn pageNetworkAlmostIdle(bc: *CDP.BrowserContext, event: *const Notification.PageNetworkAlmostIdle) !void {
|
pub fn pageNetworkAlmostIdle(bc: anytype, event: *const Notification.PageNetworkAlmostIdle) !void {
|
||||||
return sendPageLifecycle(bc, "networkAlmostIdle", event.timestamp, &id.toFrameId(event.frame_id), &id.toLoaderId(event.req_id));
|
return sendPageLifecycle(bc, "networkAlmostIdle", event.timestamp, &id.toFrameId(event.frame_id), &id.toLoaderId(event.req_id));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sendPageLifecycle(bc: *CDP.BrowserContext, name: []const u8, timestamp: u64, frame_id: []const u8, loader_id: []const u8) !void {
|
fn sendPageLifecycle(bc: anytype, name: []const u8, timestamp: u64, frame_id: []const u8, loader_id: []const u8) !void {
|
||||||
// detachTarget could be called, in which case, we still have a page doing
|
// detachTarget could be called, in which case, we still have a page doing
|
||||||
// things, but no session.
|
// things, but no session.
|
||||||
const session_id = bc.session_id orelse return;
|
const session_id = bc.session_id orelse return;
|
||||||
@@ -643,7 +640,7 @@ fn base64Encode(comptime input: []const u8) [std.base64.standard.Encoder.calcSiz
|
|||||||
return buf;
|
return buf;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn captureScreenshot(cmd: *CDP.Command) !void {
|
fn captureScreenshot(cmd: anytype) !void {
|
||||||
const Params = struct {
|
const Params = struct {
|
||||||
format: ?[]const u8 = "png",
|
format: ?[]const u8 = "png",
|
||||||
quality: ?u8 = null,
|
quality: ?u8 = null,
|
||||||
@@ -679,7 +676,7 @@ fn captureScreenshot(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getLayoutMetrics(cmd: *CDP.Command) !void {
|
fn getLayoutMetrics(cmd: anytype) !void {
|
||||||
const width = 1920;
|
const width = 1920;
|
||||||
const height = 1080;
|
const height = 1080;
|
||||||
|
|
||||||
|
|||||||
@@ -17,9 +17,8 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
enable,
|
enable,
|
||||||
disable,
|
disable,
|
||||||
|
|||||||
@@ -19,9 +19,7 @@
|
|||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const builtin = @import("builtin");
|
const builtin = @import("builtin");
|
||||||
|
|
||||||
const CDP = @import("../CDP.zig");
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
enable,
|
enable,
|
||||||
runIfWaitingForDebugger,
|
runIfWaitingForDebugger,
|
||||||
@@ -38,7 +36,7 @@ pub fn processMessage(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sendInspector(cmd: *CDP.Command, action: anytype) !void {
|
fn sendInspector(cmd: anytype, action: anytype) !void {
|
||||||
// save script in file at debug mode
|
// save script in file at debug mode
|
||||||
if (builtin.mode == .Debug) {
|
if (builtin.mode == .Debug) {
|
||||||
try logInspector(cmd, action);
|
try logInspector(cmd, action);
|
||||||
@@ -50,7 +48,7 @@ fn sendInspector(cmd: *CDP.Command, action: anytype) !void {
|
|||||||
bc.callInspector(cmd.input.json);
|
bc.callInspector(cmd.input.json);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn logInspector(cmd: *CDP.Command, action: anytype) !void {
|
fn logInspector(cmd: anytype, action: anytype) !void {
|
||||||
const script = switch (action) {
|
const script = switch (action) {
|
||||||
.evaluate => blk: {
|
.evaluate => blk: {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
|
|||||||
@@ -17,9 +17,8 @@
|
|||||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
enable,
|
enable,
|
||||||
disable,
|
disable,
|
||||||
@@ -33,7 +32,7 @@ pub fn processMessage(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setIgnoreCertificateErrors(cmd: *CDP.Command) !void {
|
fn setIgnoreCertificateErrors(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
ignore: bool,
|
ignore: bool,
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
|
|||||||
@@ -18,16 +18,13 @@
|
|||||||
|
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
const log = @import("../../log.zig");
|
const log = @import("../../log.zig");
|
||||||
const URL = @import("../../browser/URL.zig");
|
const URL = @import("../../browser/URL.zig");
|
||||||
const Cookie = @import("../../browser/webapi/storage/storage.zig").Cookie;
|
const Cookie = @import("../../browser/webapi/storage/storage.zig").Cookie;
|
||||||
|
|
||||||
const CookieJar = Cookie.Jar;
|
const CookieJar = Cookie.Jar;
|
||||||
pub const PreparedUri = Cookie.PreparedUri;
|
pub const PreparedUri = Cookie.PreparedUri;
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
clearCookies,
|
clearCookies,
|
||||||
setCookies,
|
setCookies,
|
||||||
@@ -43,7 +40,7 @@ pub fn processMessage(cmd: *CDP.Command) !void {
|
|||||||
|
|
||||||
const BrowserContextParam = struct { browserContextId: ?[]const u8 = null };
|
const BrowserContextParam = struct { browserContextId: ?[]const u8 = null };
|
||||||
|
|
||||||
fn clearCookies(cmd: *CDP.Command) !void {
|
fn clearCookies(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
const params = (try cmd.params(BrowserContextParam)) orelse BrowserContextParam{};
|
const params = (try cmd.params(BrowserContextParam)) orelse BrowserContextParam{};
|
||||||
|
|
||||||
@@ -58,7 +55,7 @@ fn clearCookies(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getCookies(cmd: *CDP.Command) !void {
|
fn getCookies(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
const params = (try cmd.params(BrowserContextParam)) orelse BrowserContextParam{};
|
const params = (try cmd.params(BrowserContextParam)) orelse BrowserContextParam{};
|
||||||
|
|
||||||
@@ -72,7 +69,7 @@ fn getCookies(cmd: *CDP.Command) !void {
|
|||||||
try cmd.sendResult(.{ .cookies = writer }, .{});
|
try cmd.sendResult(.{ .cookies = writer }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setCookies(cmd: *CDP.Command) !void {
|
fn setCookies(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
cookies: []const CdpCookie,
|
cookies: []const CdpCookie,
|
||||||
|
|||||||
@@ -20,13 +20,11 @@ const std = @import("std");
|
|||||||
const lp = @import("lightpanda");
|
const lp = @import("lightpanda");
|
||||||
|
|
||||||
const id = @import("../id.zig");
|
const id = @import("../id.zig");
|
||||||
const CDP = @import("../CDP.zig");
|
|
||||||
|
|
||||||
const log = @import("../../log.zig");
|
const log = @import("../../log.zig");
|
||||||
const URL = @import("../../browser/URL.zig");
|
const URL = @import("../../browser/URL.zig");
|
||||||
const js = @import("../../browser/js/js.zig");
|
const js = @import("../../browser/js/js.zig");
|
||||||
|
|
||||||
pub fn processMessage(cmd: *CDP.Command) !void {
|
pub fn processMessage(cmd: anytype) !void {
|
||||||
const action = std.meta.stringToEnum(enum {
|
const action = std.meta.stringToEnum(enum {
|
||||||
getTargets,
|
getTargets,
|
||||||
attachToTarget,
|
attachToTarget,
|
||||||
@@ -62,7 +60,7 @@ pub fn processMessage(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getTargets(cmd: *CDP.Command) !void {
|
fn getTargets(cmd: anytype) !void {
|
||||||
// If no context available, return an empty array.
|
// If no context available, return an empty array.
|
||||||
const bc = cmd.browser_context orelse {
|
const bc = cmd.browser_context orelse {
|
||||||
return cmd.sendResult(.{
|
return cmd.sendResult(.{
|
||||||
@@ -88,7 +86,7 @@ fn getTargets(cmd: *CDP.Command) !void {
|
|||||||
}, .{ .include_session_id = false });
|
}, .{ .include_session_id = false });
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getBrowserContexts(cmd: *CDP.Command) !void {
|
fn getBrowserContexts(cmd: anytype) !void {
|
||||||
var browser_context_ids: []const []const u8 = undefined;
|
var browser_context_ids: []const []const u8 = undefined;
|
||||||
if (cmd.browser_context) |bc| {
|
if (cmd.browser_context) |bc| {
|
||||||
browser_context_ids = &.{bc.id};
|
browser_context_ids = &.{bc.id};
|
||||||
@@ -101,7 +99,7 @@ fn getBrowserContexts(cmd: *CDP.Command) !void {
|
|||||||
}, .{ .include_session_id = false });
|
}, .{ .include_session_id = false });
|
||||||
}
|
}
|
||||||
|
|
||||||
fn createBrowserContext(cmd: *CDP.Command) !void {
|
fn createBrowserContext(cmd: anytype) !void {
|
||||||
const params = try cmd.params(struct {
|
const params = try cmd.params(struct {
|
||||||
disposeOnDetach: bool = false,
|
disposeOnDetach: bool = false,
|
||||||
proxyServer: ?[:0]const u8 = null,
|
proxyServer: ?[:0]const u8 = null,
|
||||||
@@ -132,7 +130,7 @@ fn createBrowserContext(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn disposeBrowserContext(cmd: *CDP.Command) !void {
|
fn disposeBrowserContext(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
browserContextId: []const u8,
|
browserContextId: []const u8,
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
@@ -143,7 +141,7 @@ fn disposeBrowserContext(cmd: *CDP.Command) !void {
|
|||||||
try cmd.sendResult(null, .{});
|
try cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn createTarget(cmd: *CDP.Command) !void {
|
fn createTarget(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
url: [:0]const u8 = "about:blank",
|
url: [:0]const u8 = "about:blank",
|
||||||
// width: ?u64 = null,
|
// width: ?u64 = null,
|
||||||
@@ -232,7 +230,7 @@ fn createTarget(cmd: *CDP.Command) !void {
|
|||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn attachToTarget(cmd: *CDP.Command) !void {
|
fn attachToTarget(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
targetId: []const u8,
|
targetId: []const u8,
|
||||||
flatten: bool = true,
|
flatten: bool = true,
|
||||||
@@ -249,7 +247,7 @@ fn attachToTarget(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(.{ .sessionId = bc.session_id }, .{});
|
return cmd.sendResult(.{ .sessionId = bc.session_id }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn attachToBrowserTarget(cmd: *CDP.Command) !void {
|
fn attachToBrowserTarget(cmd: anytype) !void {
|
||||||
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
const bc = cmd.browser_context orelse return error.BrowserContextNotLoaded;
|
||||||
|
|
||||||
const session_id = bc.session_id orelse cmd.cdp.session_id_gen.next();
|
const session_id = bc.session_id orelse cmd.cdp.session_id_gen.next();
|
||||||
@@ -271,7 +269,7 @@ fn attachToBrowserTarget(cmd: *CDP.Command) !void {
|
|||||||
return cmd.sendResult(.{ .sessionId = bc.session_id }, .{});
|
return cmd.sendResult(.{ .sessionId = bc.session_id }, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn closeTarget(cmd: *CDP.Command) !void {
|
fn closeTarget(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
targetId: []const u8,
|
targetId: []const u8,
|
||||||
})) orelse return error.InvalidParams;
|
})) orelse return error.InvalidParams;
|
||||||
@@ -312,7 +310,7 @@ fn closeTarget(cmd: *CDP.Command) !void {
|
|||||||
bc.target_id = null;
|
bc.target_id = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn getTargetInfo(cmd: *CDP.Command) !void {
|
fn getTargetInfo(cmd: anytype) !void {
|
||||||
const Params = struct {
|
const Params = struct {
|
||||||
targetId: ?[]const u8 = null,
|
targetId: ?[]const u8 = null,
|
||||||
};
|
};
|
||||||
@@ -349,7 +347,7 @@ fn getTargetInfo(cmd: *CDP.Command) !void {
|
|||||||
}, .{ .include_session_id = false });
|
}, .{ .include_session_id = false });
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sendMessageToTarget(cmd: *CDP.Command) !void {
|
fn sendMessageToTarget(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
message: []const u8,
|
message: []const u8,
|
||||||
sessionId: []const u8,
|
sessionId: []const u8,
|
||||||
@@ -367,19 +365,32 @@ fn sendMessageToTarget(cmd: *CDP.Command) !void {
|
|||||||
return error.UnknownSessionId;
|
return error.UnknownSessionId;
|
||||||
}
|
}
|
||||||
|
|
||||||
var aw = std.Io.Writer.Allocating.init(cmd.arena);
|
const Capture = struct {
|
||||||
cmd.cdp.dispatch(cmd.arena, .{ .capture = &aw.writer }, params.message) catch |err| {
|
aw: std.Io.Writer.Allocating,
|
||||||
|
|
||||||
|
pub fn sendJSON(self: *@This(), message: anytype) !void {
|
||||||
|
return std.json.Stringify.value(message, .{
|
||||||
|
.emit_null_optional_fields = false,
|
||||||
|
}, &self.aw.writer);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
var capture = Capture{
|
||||||
|
.aw = .init(cmd.arena),
|
||||||
|
};
|
||||||
|
|
||||||
|
cmd.cdp.dispatch(cmd.arena, &capture, params.message) catch |err| {
|
||||||
log.err(.cdp, "internal dispatch error", .{ .err = err, .id = cmd.input.id, .message = params.message });
|
log.err(.cdp, "internal dispatch error", .{ .err = err, .id = cmd.input.id, .message = params.message });
|
||||||
return err;
|
return err;
|
||||||
};
|
};
|
||||||
|
|
||||||
try cmd.sendEvent("Target.receivedMessageFromTarget", .{
|
try cmd.sendEvent("Target.receivedMessageFromTarget", .{
|
||||||
.message = aw.written(),
|
.message = capture.aw.written(),
|
||||||
.sessionId = params.sessionId,
|
.sessionId = params.sessionId,
|
||||||
}, .{});
|
}, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn detachFromTarget(cmd: *CDP.Command) !void {
|
fn detachFromTarget(cmd: anytype) !void {
|
||||||
if (cmd.browser_context) |bc| {
|
if (cmd.browser_context) |bc| {
|
||||||
if (bc.session_id) |session_id| {
|
if (bc.session_id) |session_id| {
|
||||||
try cmd.sendEvent("Target.detachedFromTarget", .{
|
try cmd.sendEvent("Target.detachedFromTarget", .{
|
||||||
@@ -393,11 +404,11 @@ fn detachFromTarget(cmd: *CDP.Command) !void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO: noop method
|
// TODO: noop method
|
||||||
fn setDiscoverTargets(cmd: *CDP.Command) !void {
|
fn setDiscoverTargets(cmd: anytype) !void {
|
||||||
return cmd.sendResult(null, .{});
|
return cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setAutoAttach(cmd: *CDP.Command) !void {
|
fn setAutoAttach(cmd: anytype) !void {
|
||||||
const params = (try cmd.params(struct {
|
const params = (try cmd.params(struct {
|
||||||
autoAttach: bool,
|
autoAttach: bool,
|
||||||
waitForDebuggerOnStart: bool,
|
waitForDebuggerOnStart: bool,
|
||||||
@@ -457,7 +468,7 @@ fn setAutoAttach(cmd: *CDP.Command) !void {
|
|||||||
try cmd.sendResult(null, .{});
|
try cmd.sendResult(null, .{});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn doAttachtoTarget(cmd: *CDP.Command, target_id: []const u8) !void {
|
fn doAttachtoTarget(cmd: anytype, target_id: []const u8) !void {
|
||||||
const bc = cmd.browser_context.?;
|
const bc = cmd.browser_context.?;
|
||||||
const session_id = bc.session_id orelse cmd.cdp.session_id_gen.next();
|
const session_id = bc.session_id orelse cmd.cdp.session_id_gen.next();
|
||||||
|
|
||||||
|
|||||||
@@ -64,7 +64,7 @@ const TestContext = struct {
|
|||||||
session_id: ?[]const u8 = null,
|
session_id: ?[]const u8 = null,
|
||||||
url: ?[:0]const u8 = null,
|
url: ?[:0]const u8 = null,
|
||||||
};
|
};
|
||||||
pub fn loadBrowserContext(self: *TestContext, opts: BrowserContextOpts) !*CDP.BrowserContext {
|
pub fn loadBrowserContext(self: *TestContext, opts: BrowserContextOpts) !*CDP.BrowserContext(CDP) {
|
||||||
var c = self.cdp();
|
var c = self.cdp();
|
||||||
if (c.browser_context) |bc| {
|
if (c.browser_context) |bc| {
|
||||||
_ = c.disposeBrowserContext(bc.id);
|
_ = c.disposeBrowserContext(bc.id);
|
||||||
|
|||||||
@@ -209,6 +209,37 @@ noinline fn assertionFailure(comptime ctx: []const u8, args: anytype) noreturn {
|
|||||||
@import("crash_handler.zig").crash(ctx, args, @returnAddress());
|
@import("crash_handler.zig").crash(ctx, args, @returnAddress());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reference counting helper
|
||||||
|
pub fn RC(comptime T: type) type {
|
||||||
|
return struct {
|
||||||
|
_refs: T = 0,
|
||||||
|
|
||||||
|
pub fn init(refs: T) @This() {
|
||||||
|
return .{ ._refs = refs };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn acquire(self: *@This()) void {
|
||||||
|
self._refs += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn release(self: *@This(), value: anytype, session: *Session) void {
|
||||||
|
if (comptime IS_DEBUG) {
|
||||||
|
std.debug.assert(self._refs > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const refs = self._refs - 1;
|
||||||
|
self._refs = refs;
|
||||||
|
if (refs > 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
value.deinit(session);
|
||||||
|
if (session.finalizer_callbacks.fetchRemove(@intFromPtr(value))) |kv| {
|
||||||
|
session.releaseArena(kv.value.arena);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
test {
|
test {
|
||||||
std.testing.refAllDecls(@This());
|
std.testing.refAllDecls(@This());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
|
||||||
pub const protocol = @import("mcp/protocol.zig");
|
pub const protocol = @import("mcp/protocol.zig");
|
||||||
|
pub const Version = protocol.Version;
|
||||||
pub const router = @import("mcp/router.zig");
|
pub const router = @import("mcp/router.zig");
|
||||||
pub const Server = @import("mcp/Server.zig");
|
pub const Server = @import("mcp/Server.zig");
|
||||||
|
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ test "MCP.Server - Integration: synchronous smoke test" {
|
|||||||
|
|
||||||
try router.processRequests(server, &in_reader);
|
try router.processRequests(server, &in_reader);
|
||||||
|
|
||||||
try testing.expectJson(.{ .jsonrpc = "2.0", .id = 1 }, out_alloc.writer.buffered());
|
try testing.expectJson(.{ .jsonrpc = "2.0", .id = 1, .result = .{ .protocolVersion = "2024-11-05" } }, out_alloc.writer.buffered());
|
||||||
}
|
}
|
||||||
|
|
||||||
test "MCP.Server - Integration: ping request returns an empty result" {
|
test "MCP.Server - Integration: ping request returns an empty result" {
|
||||||
|
|||||||
@@ -1,5 +1,14 @@
|
|||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
|
|
||||||
|
pub const Version = enum {
|
||||||
|
@"2024-11-05",
|
||||||
|
@"2025-03-26",
|
||||||
|
@"2025-06-18",
|
||||||
|
@"2025-11-25",
|
||||||
|
|
||||||
|
pub const default: Version = .@"2024-11-05";
|
||||||
|
};
|
||||||
|
|
||||||
pub const Request = struct {
|
pub const Request = struct {
|
||||||
jsonrpc: []const u8 = "2.0",
|
jsonrpc: []const u8 = "2.0",
|
||||||
id: ?std.json.Value = null,
|
id: ?std.json.Value = null,
|
||||||
|
|||||||
@@ -81,8 +81,12 @@ pub fn handleMessage(server: *Server, arena: std.mem.Allocator, msg: []const u8)
|
|||||||
|
|
||||||
fn handleInitialize(server: *Server, req: protocol.Request) !void {
|
fn handleInitialize(server: *Server, req: protocol.Request) !void {
|
||||||
const id = req.id orelse return;
|
const id = req.id orelse return;
|
||||||
const result = protocol.InitializeResult{
|
const version: protocol.Version = switch (server.app.config.mode) {
|
||||||
.protocolVersion = "2025-11-25",
|
.mcp => |opts| opts.version,
|
||||||
|
else => .default,
|
||||||
|
};
|
||||||
|
const result: protocol.InitializeResult = .{
|
||||||
|
.protocolVersion = @tagName(version),
|
||||||
.capabilities = .{
|
.capabilities = .{
|
||||||
.resources = .{},
|
.resources = .{},
|
||||||
.tools = .{},
|
.tools = .{},
|
||||||
@@ -121,7 +125,7 @@ test "MCP.router - handleMessage - synchronous unit tests" {
|
|||||||
\\{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}
|
\\{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}
|
||||||
);
|
);
|
||||||
try testing.expectJson(
|
try testing.expectJson(
|
||||||
\\{ "jsonrpc": "2.0", "id": 1, "result": { "capabilities": { "tools": {} } } }
|
\\{ "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2024-11-05", "capabilities": { "tools": {} } } }
|
||||||
, out_alloc.writer.buffered());
|
, out_alloc.writer.buffered());
|
||||||
out_alloc.writer.end = 0;
|
out_alloc.writer.end = 0;
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,9 @@ const libcurl = @import("../sys/libcurl.zig");
|
|||||||
const net_http = @import("http.zig");
|
const net_http = @import("http.zig");
|
||||||
const RobotStore = @import("Robots.zig").RobotStore;
|
const RobotStore = @import("Robots.zig").RobotStore;
|
||||||
const WebBotAuth = @import("WebBotAuth.zig");
|
const WebBotAuth = @import("WebBotAuth.zig");
|
||||||
|
const Cache = @import("cache/Cache.zig");
|
||||||
|
|
||||||
|
const App = @import("../App.zig");
|
||||||
const Runtime = @This();
|
const Runtime = @This();
|
||||||
|
|
||||||
const Listener = struct {
|
const Listener = struct {
|
||||||
@@ -45,10 +47,12 @@ const MAX_TICK_CALLBACKS = 16;
|
|||||||
|
|
||||||
allocator: Allocator,
|
allocator: Allocator,
|
||||||
|
|
||||||
|
app: *App,
|
||||||
config: *const Config,
|
config: *const Config,
|
||||||
ca_blob: ?net_http.Blob,
|
ca_blob: ?net_http.Blob,
|
||||||
robot_store: RobotStore,
|
robot_store: RobotStore,
|
||||||
web_bot_auth: ?WebBotAuth,
|
web_bot_auth: ?WebBotAuth,
|
||||||
|
cache: ?Cache,
|
||||||
|
|
||||||
connections: []net_http.Connection,
|
connections: []net_http.Connection,
|
||||||
available: std.DoublyLinkedList = .{},
|
available: std.DoublyLinkedList = .{},
|
||||||
@@ -200,7 +204,7 @@ fn globalDeinit() void {
|
|||||||
libcurl.curl_global_cleanup();
|
libcurl.curl_global_cleanup();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn init(allocator: Allocator, config: *const Config) !Runtime {
|
pub fn init(allocator: Allocator, app: *App, config: *const Config) !Runtime {
|
||||||
globalInit(allocator);
|
globalInit(allocator);
|
||||||
errdefer globalDeinit();
|
errdefer globalDeinit();
|
||||||
|
|
||||||
@@ -233,6 +237,11 @@ pub fn init(allocator: Allocator, config: *const Config) !Runtime {
|
|||||||
else
|
else
|
||||||
null;
|
null;
|
||||||
|
|
||||||
|
const cache = if (config.cacheDir()) |cache_dir_path|
|
||||||
|
Cache{ .kind = .{ .fs = try .init(cache_dir_path) } }
|
||||||
|
else
|
||||||
|
null;
|
||||||
|
|
||||||
return .{
|
return .{
|
||||||
.allocator = allocator,
|
.allocator = allocator,
|
||||||
.config = config,
|
.config = config,
|
||||||
@@ -244,8 +253,10 @@ pub fn init(allocator: Allocator, config: *const Config) !Runtime {
|
|||||||
.available = available,
|
.available = available,
|
||||||
.connections = connections,
|
.connections = connections,
|
||||||
|
|
||||||
|
.app = app,
|
||||||
.robot_store = RobotStore.init(allocator),
|
.robot_store = RobotStore.init(allocator),
|
||||||
.web_bot_auth = web_bot_auth,
|
.web_bot_auth = web_bot_auth,
|
||||||
|
.cache = cache,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
173
src/network/cache/Cache.zig
vendored
Normal file
173
src/network/cache/Cache.zig
vendored
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
|
||||||
|
//
|
||||||
|
// Francis Bouvier <francis@lightpanda.io>
|
||||||
|
// Pierre Tachoire <pierre@lightpanda.io>
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const Http = @import("../http.zig");
|
||||||
|
const FsCache = @import("FsCache.zig");
|
||||||
|
|
||||||
|
/// A browser-wide cache for resources across the network.
|
||||||
|
/// This mostly conforms to RFC9111 with regards to caching behavior.
|
||||||
|
pub const Cache = @This();
|
||||||
|
|
||||||
|
kind: union(enum) {
|
||||||
|
fs: FsCache,
|
||||||
|
},
|
||||||
|
|
||||||
|
pub fn get(self: *Cache, arena: std.mem.Allocator, req: CacheRequest) ?CachedResponse {
|
||||||
|
return switch (self.kind) {
|
||||||
|
inline else => |*c| c.get(arena, req),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn put(self: *Cache, metadata: CachedMetadata, body: []const u8) !void {
|
||||||
|
return switch (self.kind) {
|
||||||
|
inline else => |*c| c.put(metadata, body),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const CacheControl = struct {
|
||||||
|
max_age: u64,
|
||||||
|
must_revalidate: bool = false,
|
||||||
|
immutable: bool = false,
|
||||||
|
|
||||||
|
pub fn parse(value: []const u8) ?CacheControl {
|
||||||
|
var cc: CacheControl = .{ .max_age = undefined };
|
||||||
|
|
||||||
|
var max_age_set = false;
|
||||||
|
var max_s_age_set = false;
|
||||||
|
var is_public = false;
|
||||||
|
|
||||||
|
var iter = std.mem.splitScalar(u8, value, ',');
|
||||||
|
while (iter.next()) |part| {
|
||||||
|
const directive = std.mem.trim(u8, part, &std.ascii.whitespace);
|
||||||
|
if (std.ascii.eqlIgnoreCase(directive, "no-store")) {
|
||||||
|
return null;
|
||||||
|
} else if (std.ascii.eqlIgnoreCase(directive, "no-cache")) {
|
||||||
|
return null;
|
||||||
|
} else if (std.ascii.eqlIgnoreCase(directive, "must-revalidate")) {
|
||||||
|
cc.must_revalidate = true;
|
||||||
|
} else if (std.ascii.eqlIgnoreCase(directive, "immutable")) {
|
||||||
|
cc.immutable = true;
|
||||||
|
} else if (std.ascii.eqlIgnoreCase(directive, "public")) {
|
||||||
|
is_public = true;
|
||||||
|
} else if (std.ascii.startsWithIgnoreCase(directive, "max-age=")) {
|
||||||
|
if (!max_s_age_set) {
|
||||||
|
if (std.fmt.parseInt(u64, directive[8..], 10) catch null) |max_age| {
|
||||||
|
cc.max_age = max_age;
|
||||||
|
max_age_set = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (std.ascii.startsWithIgnoreCase(directive, "s-maxage=")) {
|
||||||
|
if (std.fmt.parseInt(u64, directive[9..], 10) catch null) |max_age| {
|
||||||
|
cc.max_age = max_age;
|
||||||
|
max_age_set = true;
|
||||||
|
max_s_age_set = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!max_age_set) return null;
|
||||||
|
if (!is_public) return null;
|
||||||
|
if (cc.max_age == 0) return null;
|
||||||
|
|
||||||
|
return cc;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const Vary = union(enum) {
|
||||||
|
wildcard: void,
|
||||||
|
value: []const u8,
|
||||||
|
|
||||||
|
pub fn parse(value: []const u8) Vary {
|
||||||
|
if (std.mem.eql(u8, value, "*")) return .wildcard;
|
||||||
|
return .{ .value = value };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn toString(self: Vary) []const u8 {
|
||||||
|
return switch (self) {
|
||||||
|
.wildcard => "*",
|
||||||
|
.value => |v| v,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const CachedMetadata = struct {
|
||||||
|
url: [:0]const u8,
|
||||||
|
content_type: []const u8,
|
||||||
|
|
||||||
|
status: u16,
|
||||||
|
stored_at: i64,
|
||||||
|
age_at_store: u64,
|
||||||
|
|
||||||
|
// for If-None-Match
|
||||||
|
etag: ?[]const u8,
|
||||||
|
// for If-Modified-Since
|
||||||
|
last_modified: ?[]const u8,
|
||||||
|
|
||||||
|
cache_control: CacheControl,
|
||||||
|
vary: ?Vary,
|
||||||
|
headers: []const Http.Header,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const CacheRequest = struct {
|
||||||
|
url: []const u8,
|
||||||
|
timestamp: i64,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const CachedData = union(enum) {
|
||||||
|
buffer: []const u8,
|
||||||
|
file: std.fs.File,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const CachedResponse = struct {
|
||||||
|
metadata: CachedMetadata,
|
||||||
|
data: CachedData,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn tryCache(
|
||||||
|
arena: std.mem.Allocator,
|
||||||
|
timestamp: i64,
|
||||||
|
url: [:0]const u8,
|
||||||
|
status: u16,
|
||||||
|
content_type: ?[]const u8,
|
||||||
|
cache_control: ?[]const u8,
|
||||||
|
vary: ?[]const u8,
|
||||||
|
etag: ?[]const u8,
|
||||||
|
last_modified: ?[]const u8,
|
||||||
|
age: ?[]const u8,
|
||||||
|
has_set_cookie: bool,
|
||||||
|
has_authorization: bool,
|
||||||
|
) !?CachedMetadata {
|
||||||
|
if (status != 200) return null;
|
||||||
|
if (has_set_cookie) return null;
|
||||||
|
if (has_authorization) return null;
|
||||||
|
const cc = CacheControl.parse(cache_control orelse return null) orelse return null;
|
||||||
|
|
||||||
|
return .{
|
||||||
|
.url = url,
|
||||||
|
.content_type = if (content_type) |ct| try arena.dupe(u8, ct) else "application/octet-stream",
|
||||||
|
.status = status,
|
||||||
|
.stored_at = timestamp,
|
||||||
|
.age_at_store = if (age) |a| std.fmt.parseInt(u64, a, 10) catch 0 else 0,
|
||||||
|
.cache_control = cc,
|
||||||
|
.vary = if (vary) |v| Vary.parse(v) else null,
|
||||||
|
.etag = if (etag) |e| try arena.dupe(u8, e) else null,
|
||||||
|
.last_modified = if (last_modified) |lm| try arena.dupe(u8, lm) else null,
|
||||||
|
.headers = &.{},
|
||||||
|
};
|
||||||
|
}
|
||||||
293
src/network/cache/FsCache.zig
vendored
Normal file
293
src/network/cache/FsCache.zig
vendored
Normal file
@@ -0,0 +1,293 @@
|
|||||||
|
// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
|
||||||
|
//
|
||||||
|
// Francis Bouvier <francis@lightpanda.io>
|
||||||
|
// Pierre Tachoire <pierre@lightpanda.io>
|
||||||
|
//
|
||||||
|
// 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/>.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
const Cache = @import("Cache.zig");
|
||||||
|
const Http = @import("../http.zig");
|
||||||
|
const CacheRequest = Cache.CacheRequest;
|
||||||
|
const CachedMetadata = Cache.CachedMetadata;
|
||||||
|
const CachedResponse = Cache.CachedResponse;
|
||||||
|
|
||||||
|
const CACHE_VERSION: usize = 1;
|
||||||
|
const LOCK_STRIPES = 16;
|
||||||
|
|
||||||
|
pub const FsCache = @This();
|
||||||
|
|
||||||
|
dir: std.fs.Dir,
|
||||||
|
locks: [LOCK_STRIPES]std.Thread.Mutex = .{std.Thread.Mutex{}} ** LOCK_STRIPES,
|
||||||
|
|
||||||
|
const CacheMetadataFile = struct {
|
||||||
|
version: usize,
|
||||||
|
metadata: CachedMetadata,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn getLockPtr(self: *FsCache, key: *const [HASHED_KEY_LEN]u8) *std.Thread.Mutex {
|
||||||
|
const lock_idx: usize = @truncate(std.hash.Wyhash.hash(0, key) % LOCK_STRIPES);
|
||||||
|
return &self.locks[lock_idx];
|
||||||
|
}
|
||||||
|
|
||||||
|
const HASHED_KEY_LEN = 64;
|
||||||
|
const HASHED_PATH_LEN = HASHED_KEY_LEN + 5;
|
||||||
|
const HASHED_TMP_PATH_LEN = HASHED_PATH_LEN + 4;
|
||||||
|
|
||||||
|
fn hashKey(key: []const u8) [HASHED_KEY_LEN]u8 {
|
||||||
|
var digest: [std.crypto.hash.sha2.Sha256.digest_length]u8 = undefined;
|
||||||
|
std.crypto.hash.sha2.Sha256.hash(key, &digest, .{});
|
||||||
|
var hex: [HASHED_KEY_LEN]u8 = undefined;
|
||||||
|
_ = std.fmt.bufPrint(&hex, "{s}", .{std.fmt.bytesToHex(&digest, .lower)}) catch unreachable;
|
||||||
|
return hex;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn metaPath(hashed_key: *const [HASHED_KEY_LEN]u8) [HASHED_PATH_LEN]u8 {
|
||||||
|
var path: [HASHED_PATH_LEN]u8 = undefined;
|
||||||
|
_ = std.fmt.bufPrint(&path, "{s}.meta", .{hashed_key}) catch unreachable;
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bodyPath(hashed_key: *const [HASHED_KEY_LEN]u8) [HASHED_PATH_LEN]u8 {
|
||||||
|
var path: [HASHED_PATH_LEN]u8 = undefined;
|
||||||
|
_ = std.fmt.bufPrint(&path, "{s}.body", .{hashed_key}) catch unreachable;
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn metaTmpPath(hashed_key: *const [HASHED_KEY_LEN]u8) [HASHED_TMP_PATH_LEN]u8 {
|
||||||
|
var path: [HASHED_TMP_PATH_LEN]u8 = undefined;
|
||||||
|
_ = std.fmt.bufPrint(&path, "{s}.meta.tmp", .{hashed_key}) catch unreachable;
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bodyTmpPath(hashed_key: *const [HASHED_KEY_LEN]u8) [HASHED_TMP_PATH_LEN]u8 {
|
||||||
|
var path: [HASHED_TMP_PATH_LEN]u8 = undefined;
|
||||||
|
_ = std.fmt.bufPrint(&path, "{s}.body.tmp", .{hashed_key}) catch unreachable;
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn init(path: []const u8) !FsCache {
|
||||||
|
const cwd = std.fs.cwd();
|
||||||
|
|
||||||
|
cwd.makeDir(path) catch |err| switch (err) {
|
||||||
|
error.PathAlreadyExists => {},
|
||||||
|
else => return err,
|
||||||
|
};
|
||||||
|
|
||||||
|
const dir = try cwd.openDir(path, .{ .iterate = true });
|
||||||
|
return .{ .dir = dir };
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn deinit(self: *FsCache) void {
|
||||||
|
self.dir.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(self: *FsCache, arena: std.mem.Allocator, req: CacheRequest) ?Cache.CachedResponse {
|
||||||
|
const hashed_key = hashKey(req.url);
|
||||||
|
const meta_p = metaPath(&hashed_key);
|
||||||
|
const body_p = bodyPath(&hashed_key);
|
||||||
|
|
||||||
|
const lock = self.getLockPtr(&hashed_key);
|
||||||
|
lock.lock();
|
||||||
|
defer lock.unlock();
|
||||||
|
|
||||||
|
const meta_file = self.dir.openFile(&meta_p, .{ .mode = .read_only }) catch return null;
|
||||||
|
defer meta_file.close();
|
||||||
|
|
||||||
|
const contents = meta_file.readToEndAlloc(arena, 1 * 1024 * 1024) catch return null;
|
||||||
|
defer arena.free(contents);
|
||||||
|
|
||||||
|
const cache_file: CacheMetadataFile = std.json.parseFromSliceLeaky(
|
||||||
|
CacheMetadataFile,
|
||||||
|
arena,
|
||||||
|
contents,
|
||||||
|
.{ .allocate = .alloc_always },
|
||||||
|
) catch {
|
||||||
|
self.dir.deleteFile(&meta_p) catch {};
|
||||||
|
self.dir.deleteFile(&body_p) catch {};
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const metadata = cache_file.metadata;
|
||||||
|
|
||||||
|
if (cache_file.version != CACHE_VERSION) {
|
||||||
|
self.dir.deleteFile(&meta_p) catch {};
|
||||||
|
self.dir.deleteFile(&body_p) catch {};
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = req.timestamp;
|
||||||
|
const age = (now - metadata.stored_at) + @as(i64, @intCast(metadata.age_at_store));
|
||||||
|
if (age < 0 or @as(u64, @intCast(age)) >= metadata.cache_control.max_age) {
|
||||||
|
self.dir.deleteFile(&meta_p) catch {};
|
||||||
|
self.dir.deleteFile(&body_p) catch {};
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const body_file = self.dir.openFile(
|
||||||
|
&body_p,
|
||||||
|
.{ .mode = .read_only },
|
||||||
|
) catch return null;
|
||||||
|
|
||||||
|
return .{
|
||||||
|
.metadata = metadata,
|
||||||
|
.data = .{ .file = body_file },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn put(self: *FsCache, meta: CachedMetadata, body: []const u8) !void {
|
||||||
|
const hashed_key = hashKey(meta.url);
|
||||||
|
const meta_p = metaPath(&hashed_key);
|
||||||
|
const meta_tmp_p = metaTmpPath(&hashed_key);
|
||||||
|
const body_p = bodyPath(&hashed_key);
|
||||||
|
const body_tmp_p = bodyTmpPath(&hashed_key);
|
||||||
|
var writer_buf: [512]u8 = undefined;
|
||||||
|
|
||||||
|
const lock = self.getLockPtr(&hashed_key);
|
||||||
|
lock.lock();
|
||||||
|
defer lock.unlock();
|
||||||
|
|
||||||
|
{
|
||||||
|
const meta_file = try self.dir.createFile(&meta_tmp_p, .{});
|
||||||
|
errdefer {
|
||||||
|
meta_file.close();
|
||||||
|
self.dir.deleteFile(&meta_tmp_p) catch {};
|
||||||
|
}
|
||||||
|
|
||||||
|
var meta_file_writer = meta_file.writer(&writer_buf);
|
||||||
|
const meta_file_writer_iface = &meta_file_writer.interface;
|
||||||
|
try std.json.Stringify.value(
|
||||||
|
CacheMetadataFile{ .version = CACHE_VERSION, .metadata = meta },
|
||||||
|
.{ .whitespace = .minified },
|
||||||
|
meta_file_writer_iface,
|
||||||
|
);
|
||||||
|
try meta_file_writer_iface.flush();
|
||||||
|
meta_file.close();
|
||||||
|
}
|
||||||
|
errdefer self.dir.deleteFile(&meta_tmp_p) catch {};
|
||||||
|
try self.dir.rename(&meta_tmp_p, &meta_p);
|
||||||
|
|
||||||
|
{
|
||||||
|
const body_file = try self.dir.createFile(&body_tmp_p, .{});
|
||||||
|
errdefer {
|
||||||
|
body_file.close();
|
||||||
|
self.dir.deleteFile(&body_tmp_p) catch {};
|
||||||
|
}
|
||||||
|
|
||||||
|
var body_file_writer = body_file.writer(&writer_buf);
|
||||||
|
const body_file_writer_iface = &body_file_writer.interface;
|
||||||
|
try body_file_writer_iface.writeAll(body);
|
||||||
|
try body_file_writer_iface.flush();
|
||||||
|
body_file.close();
|
||||||
|
}
|
||||||
|
errdefer self.dir.deleteFile(&body_tmp_p) catch {};
|
||||||
|
|
||||||
|
errdefer self.dir.deleteFile(&meta_p) catch {};
|
||||||
|
try self.dir.rename(&body_tmp_p, &body_p);
|
||||||
|
}
|
||||||
|
|
||||||
|
const testing = std.testing;
|
||||||
|
|
||||||
|
test "FsCache: basic put and get" {
|
||||||
|
var tmp = testing.tmpDir(.{});
|
||||||
|
defer tmp.cleanup();
|
||||||
|
|
||||||
|
const path = try tmp.dir.realpathAlloc(testing.allocator, ".");
|
||||||
|
defer testing.allocator.free(path);
|
||||||
|
|
||||||
|
var fs_cache = try FsCache.init(path);
|
||||||
|
defer fs_cache.deinit();
|
||||||
|
var cache = Cache{ .kind = .{ .fs = fs_cache } };
|
||||||
|
|
||||||
|
var arena = std.heap.ArenaAllocator.init(testing.allocator);
|
||||||
|
defer arena.deinit();
|
||||||
|
|
||||||
|
const now = std.time.timestamp();
|
||||||
|
const meta = CachedMetadata{
|
||||||
|
.url = "https://example.com",
|
||||||
|
.content_type = "text/html",
|
||||||
|
.status = 200,
|
||||||
|
.stored_at = now,
|
||||||
|
.age_at_store = 0,
|
||||||
|
.etag = null,
|
||||||
|
.last_modified = null,
|
||||||
|
.cache_control = .{ .max_age = 600 },
|
||||||
|
.vary = null,
|
||||||
|
.headers = &.{},
|
||||||
|
};
|
||||||
|
|
||||||
|
const body = "hello world";
|
||||||
|
try cache.put(meta, body);
|
||||||
|
|
||||||
|
const result = cache.get(arena.allocator(), .{ .url = "https://example.com", .timestamp = now }) orelse return error.CacheMiss;
|
||||||
|
defer result.data.file.close();
|
||||||
|
|
||||||
|
var buf: [64]u8 = undefined;
|
||||||
|
var file_reader = result.data.file.reader(&buf);
|
||||||
|
|
||||||
|
const read_buf = try file_reader.interface.allocRemaining(testing.allocator, .unlimited);
|
||||||
|
defer testing.allocator.free(read_buf);
|
||||||
|
|
||||||
|
try testing.expectEqualStrings(body, read_buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
test "FsCache: get expiration" {
|
||||||
|
var tmp = testing.tmpDir(.{});
|
||||||
|
defer tmp.cleanup();
|
||||||
|
|
||||||
|
const path = try tmp.dir.realpathAlloc(testing.allocator, ".");
|
||||||
|
defer testing.allocator.free(path);
|
||||||
|
|
||||||
|
var fs_cache = try FsCache.init(path);
|
||||||
|
defer fs_cache.deinit();
|
||||||
|
var cache = Cache{ .kind = .{ .fs = fs_cache } };
|
||||||
|
|
||||||
|
var arena = std.heap.ArenaAllocator.init(testing.allocator);
|
||||||
|
defer arena.deinit();
|
||||||
|
|
||||||
|
const now = 5000;
|
||||||
|
const max_age = 1000;
|
||||||
|
|
||||||
|
const meta = CachedMetadata{
|
||||||
|
.url = "https://example.com",
|
||||||
|
.content_type = "text/html",
|
||||||
|
.status = 200,
|
||||||
|
.stored_at = now,
|
||||||
|
.age_at_store = 900,
|
||||||
|
.etag = null,
|
||||||
|
.last_modified = null,
|
||||||
|
.cache_control = .{ .max_age = max_age },
|
||||||
|
.vary = null,
|
||||||
|
.headers = &.{},
|
||||||
|
};
|
||||||
|
|
||||||
|
const body = "hello world";
|
||||||
|
try cache.put(meta, body);
|
||||||
|
|
||||||
|
const result = cache.get(
|
||||||
|
arena.allocator(),
|
||||||
|
.{ .url = "https://example.com", .timestamp = now + 50 },
|
||||||
|
) orelse return error.CacheMiss;
|
||||||
|
result.data.file.close();
|
||||||
|
|
||||||
|
try testing.expectEqual(null, cache.get(
|
||||||
|
arena.allocator(),
|
||||||
|
.{ .url = "https://example.com", .timestamp = now + 200 },
|
||||||
|
));
|
||||||
|
|
||||||
|
try testing.expectEqual(null, cache.get(
|
||||||
|
arena.allocator(),
|
||||||
|
.{ .url = "https://example.com", .timestamp = now },
|
||||||
|
));
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user