Lightpanda: the headless browser designed for AI and automation
webapi: Add static Response.json, Response.error and Response.redirect
Karl Seguinc204623755cb
diff --git a/src/browser/js/Caller.zig b/src/browser/js/Caller.zigindex 7cda1646e..bd8c6dcfa 100644--- a/src/browser/js/Caller.zig+++ b/src/browser/js/Caller.zig@@ -575,6 +575,7 @@ pub const Function = struct {embedded_receiver: bool = false,exposed: Exposed = .both,ce_reactions: bool = false,+ js_name: ?[:0]const u8 = null,pub const Exposed = enum { both, window, worker };diff --git a/src/browser/js/Snapshot.zig b/src/browser/js/Snapshot.zigindex 27338ac1a..1560b3794 100644--- a/src/browser/js/Snapshot.zig+++ b/src/browser/js/Snapshot.zig@@ -776,7 +776,9 @@ fn attachClass(comptime JsApi: type, comptime flatten: bool, isolate: *v8.Isolat.length = value.arity,.signature = func_signature,}).?;- const js_name = v8.v8__String__NewFromUtf8(isolate, name.ptr, v8.kNormal, @intCast(name.len));+ // A member may override its JS-visible name (see Response.json_static)+ const fn_name = value.js_name orelse name;+ const js_name = v8.v8__String__NewFromUtf8(isolate, fn_name.ptr, v8.kNormal, @intCast(fn_name.len));v8.v8__FunctionTemplate__SetClassName(function_template, js_name);if (value.static and !own_properties) {v8.v8__Template__Set(@ptrCast(template), js_name, @ptrCast(function_template), v8.None);diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zigindex 4a3adf1ac..1460ddead 100644--- a/src/browser/js/bridge.zig+++ b/src/browser/js/bridge.zig@@ -156,6 +156,7 @@ pub const Function = struct {arity: usize,noop: bool = false,wpt_only: bool = false,+ js_name: ?[:0]const u8 = null,exposed: Caller.Function.Opts.Exposed = .both,cache: ?Caller.Function.Opts.Caching = null,func: *const fn (?*const v8.FunctionCallbackInfo) callconv(.c) void,@@ -165,6 +166,7 @@ pub const Function = struct {.cache = opts.cache,.static = opts.static,.wpt_only = opts.wpt_only,+ .js_name = opts.js_name,.exposed = opts.exposed,// Non-static methods receive `self` as their first param; static// methods don't, so don't skip the first param for them.diff --git a/src/browser/tests/net/response.html b/src/browser/tests/net/response.htmlindex 0a80ab573..eb7acf4aa 100644--- a/src/browser/tests/net/response.html+++ b/src/browser/tests/net/response.html@@ -251,3 +251,53 @@testing.expectTrue(new Response(new Uint8Array([1, 2, 3])).headers.get('content-type') === null);}</script>++<script id=static_error>+ {+ const r = Response.error();+ testing.expectEqual('error', r.type);+ testing.expectEqual(0, r.status);+ testing.expectEqual('', r.statusText);+ testing.expectEqual(false, r.ok);+ testing.expectEqual(null, r.body);+ }+</script>++<script id=static_redirect>+ {+ const r = Response.redirect('https://example.com/a');+ testing.expectEqual(302, r.status);+ testing.expectEqual('https://example.com/a', r.headers.get('location'));+ testing.expectEqual('default', r.type);+ }+ {+ const r = Response.redirect('https://example.com/a', 301);+ testing.expectEqual(301, r.status);+ }+ {+ let threw = false;+ try { Response.redirect('https://example.com/a', 200); } catch (e) { threw = e instanceof RangeError; }+ testing.expectTrue(threw);+ }+</script>++<script id=static_json type=module>+ {+ const r = Response.json({ a: 1, b: 'two' });+ testing.expectEqual(200, r.status);+ testing.expectEqual('application/json', r.headers.get('content-type'));+ testing.expectEqual('{"a":1,"b":"two"}', await r.text());+ }+ {+ const r = Response.json([1, 2], { status: 201, headers: { 'content-type': 'application/vnd.api+json' } });+ testing.expectEqual(201, r.status);+ // An explicit content-type is not overridden.+ testing.expectEqual('application/vnd.api+json', r.headers.get('content-type'));+ testing.expectEqual('[1,2]', await r.text());+ }+ {+ let threw = false;+ try { Response.json(undefined); } catch (e) { threw = e instanceof TypeError; }+ testing.expectTrue(threw);+ }+</script>diff --git a/src/browser/webapi/net/Response.zig b/src/browser/webapi/net/Response.zigindex b33c42aec..78851e067 100644--- a/src/browser/webapi/net/Response.zig+++ b/src/browser/webapi/net/Response.zig@@ -20,6 +20,7 @@ const std = @import("std");const lp = @import("lightpanda");const js = @import("../../js/js.zig");+const URL = @import("../../URL.zig");const Page = @import("../../Page.zig");const HttpClient = @import("../../HttpClient.zig");@@ -111,6 +112,90 @@ pub fn init(body_: ?BodyInit, opts_: ?InitOpts, exec: *const Execution) !*Responreturn self;}+pub fn createError(exec: *const Execution) !*Response {+ const session = exec.session;+ const arena = try session.getArena(.large, "Response.error");+ errdefer session.releaseArena(arena);++ const self = try arena.create(Response);+ self.* = .{+ ._arena = arena,+ ._status = 0,+ ._status_text = "",+ ._url = "",+ ._body = .empty,+ ._type = .@"error",+ ._is_redirected = false,+ ._headers = try Headers.init(null, exec),+ };+ return self;+}++pub fn createRedirect(url_: []const u8, status_: ?u16, exec: *const Execution) !*Response {+ const status = status_ orelse 302;+ switch (status) {+ 301, 302, 303, 307, 308 => {},+ else => return error.RangeError,+ }++ const session = exec.session;+ const arena = try session.getArena(.large, "Response.redirect");+ errdefer session.releaseArena(arena);++ const location = try URL.resolve(arena, exec.base(), url_, .{ .encoding = exec.charset.* });++ const headers = try Headers.init(null, exec);+ try headers.set("location", location, exec);++ const self = try arena.create(Response);+ self.* = .{+ ._arena = arena,+ ._status = status,+ ._status_text = "",+ ._url = "",+ ._body = .empty,+ ._type = .default,+ ._is_redirected = false,+ ._headers = headers,+ };+ return self;+}++pub fn createJson(data: js.Value, opts_: ?InitOpts, exec: *const Execution) !*Response {+ const session = exec.session;+ const arena = try session.getArena(.medium, "Response.json");+ errdefer session.releaseArena(arena);++ const json = data.toJson(arena) catch |err| switch (err) {+ error.JsException => return error.TryCatchRethrow,+ else => return err,+ };+ if (std.mem.eql(u8, json, "undefined")) {+ return error.TypeError;+ }++ const opts = opts_ orelse InitOpts{};+ const status_text = if (opts.statusText) |st| try arena.dupe(u8, st) else "";++ const headers = try Headers.init(opts.headers, exec);+ if (!headers.has("content-type", exec)) {+ try headers.append("content-type", "application/json", exec);+ }++ const self = try arena.create(Response);+ self.* = .{+ ._arena = arena,+ ._status = opts.status,+ ._status_text = status_text,+ ._url = "",+ ._body = .{ .bytes = json },+ ._type = .default,+ ._is_redirected = false,+ ._headers = headers,+ };+ return self;+}+pub fn deinit(self: *Response, page: *Page) void {if (self._http_response) |resp| {resp.abort(error.Abort);@@ -414,6 +499,12 @@ pub const JsApi = struct {};pub const constructor = bridge.constructor(Response.init, .{});++ pub const @"error" = bridge.function(Response.createError, .{ .static = true });+ pub const redirect = bridge.function(Response.createRedirect, .{ .static = true });+ // Response.json (staticc) conflicts with resposne.json, hence the `js_name` option+ pub const json_static = bridge.function(Response.createJson, .{ .static = true, .js_name = "json" });+pub const ok = bridge.accessor(Response.isOK, null, .{});pub const status = bridge.accessor(Response.getStatus, null, .{});pub const statusText = bridge.accessor(Response.getStatusText, null, .{});