Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: explicit variadic parameter

Karl Seguin01342c02bcfd
diff --git a/src/Notification.zig b/src/Notification.zig
index 1520efd53..47fdb76c6 100644
--- a/src/Notification.zig
+++ b/src/Notification.zig
@@ -381,7 +381,7 @@ pub const ConsoleMessage = struct {
worker,
},
type: ConsoleMessageType,
- values: []js.Value,
+ values: []const js.Value,
// The caller's: the context the message was logged in.
local: *const js.Local,
url: ?[]const u8 = null,
diff --git a/src/browser/js/Caller.zig b/src/browser/js/Caller.zig
index 1e7f27e52..2c108485f 100644
--- a/src/browser/js/Caller.zig
+++ b/src/browser/js/Caller.zig
@@ -1064,10 +1064,27 @@ pub const Function = struct {
//
// For constructors, setters and methods, we can further increase offset + 1
// if the first parameter is an instance of Page/Frame/Execution.
-//
-// Finally, if the JS function is called with _more_ parameters and
-// the last parameter in Zig is an array, we'll try to slurp the additional
-// parameters into the array.
+
+// Only fold errors we don't recognize into InvalidArgument; let
+// domain-meaningful ones (e.g. InvalidCharacterError from a String.OneByte
+// param) propagate so handleError can map them to the right DOMException.
+// Compared by name because the per-type instantiation of jsValueToZig may not
+// include such errors in its inferred error set.
+fn argToZig(comptime T: type, local: *const Local, js_val: js.Value) !T {
+ return local.jsValueToZig(T, js_val) catch |err| {
+ if (err == error.JsException or err == error.ExecutionTerminated) {
+ // an exception thrown by user code (e.g. a toString getter), or
+ // the termination, is pending; propagate it untouched
+ return err;
+ }
+ const DOMException = @import("../webapi/DOMException.zig");
+ if (DOMException.fromError(err) != null) {
+ return err;
+ }
+ return error.InvalidArgument;
+ };
+}
+
fn getArgs(comptime F: type, comptime offset: usize, local: *const Local, info: FunctionCallbackInfo) !ParameterTypes(F) {
var args: ParameterTypes(F) = undefined;
@@ -1098,78 +1115,44 @@ fn getArgs(comptime F: type, comptime offset: usize, local: *const Local, info:
}
const js_parameter_count = info.length();
- const last_js_parameter = params_to_map.len - 1;
- var is_variadic = false;
- {
- // This is going to get complicated. If the last Zig parameter
- // is a slice AND the corresponding javascript parameter is
- // NOT an an array, then we'll treat it as a variadic.
-
- const last_parameter_type = params_to_map[params_to_map.len - 1].?;
- const last_parameter_type_info = @typeInfo(last_parameter_type);
- if (last_parameter_type_info == .pointer and last_parameter_type_info.pointer.size == .slice) {
- const slice_type = last_parameter_type_info.pointer.child;
- const corresponding_js_value = info.getArg(@intCast(last_js_parameter), local);
- if (slice_type == js.Value or (corresponding_js_value.isArray() == false and corresponding_js_value.isTypedArray() == false and slice_type != u8)) {
- is_variadic = true;
- if (js_parameter_count == 0) {
- @field(args, tupleFieldName(params_to_map.len + offset - 1)) = &.{};
- } else if (js_parameter_count >= params_to_map.len) {
- const arr = try local.call_arena.alloc(last_parameter_type_info.pointer.child, js_parameter_count - params_to_map.len + 1);
- for (arr, last_js_parameter..) |*a, i| {
- a.* = try local.jsValueToZig(slice_type, info.getArg(@intCast(i), local));
- }
- @field(args, tupleFieldName(params_to_map.len + offset - 1)) = arr;
- } else {
- @field(args, tupleFieldName(params_to_map.len + offset - 1)) = &.{};
- }
- }
- }
- }
+ // A trailing js.Variadic(T) takes every argument after the fixed ones.
+ const LastJsParam = params_to_map[params_to_map.len - 1].?;
+ const fixed_params = comptime if (isVariadic(LastJsParam)) params_to_map[0 .. params_to_map.len - 1] else params_to_map;
- inline for (params_to_map, 0..) |param_type, i| {
+ inline for (fixed_params, 0..) |param_type, i| {
const field_index = comptime i + offset;
- if (comptime i == params_to_map.len - 1) {
- if (is_variadic) {
- break;
- }
- }
-
if (comptime isFrame(param_type.?)) {
@compileError("Frame must be the last parameter: " ++ @typeName(F));
} else if (comptime isPage(param_type.?)) {
@compileError("Page must be the last parameter: " ++ @typeName(F));
} else if (comptime isExecution(param_type.?)) {
@compileError("Execution must be the last parameter: " ++ @typeName(F));
+ } else if (comptime isVariadic(param_type.?)) {
+ @compileError("Variadic must be the last JS parameter: " ++ @typeName(F));
} else if (i >= js_parameter_count) {
if (@typeInfo(param_type.?) != .optional) {
return error.InvalidArgument;
}
@field(args, tupleFieldName(field_index)) = null;
} else {
- const js_val = info.getArg(@intCast(i), local);
- // Only fold errors we don't recognize into InvalidArgument; let
- // domain-meaningful ones (e.g. InvalidCharacterError from a
- // String.OneByte param) propagate so handleError can map them
- // to the right DOMException. Compared by name because the per-
- // type instantiation of jsValueToZig may not include such errors
- // in its inferred error set.
- @field(args, tupleFieldName(field_index)) = local.jsValueToZig(param_type.?, js_val) catch |err| {
- if (err == error.JsException or err == error.ExecutionTerminated) {
- // an exception thrown by user code (e.g. a toString
- // getter), or the termination, is pending; propagate it
- // untouched
- return err;
- }
- const DOMException = @import("../webapi/DOMException.zig");
- if (DOMException.fromError(err) != null) {
- return err;
- }
- return error.InvalidArgument;
- };
+ @field(args, tupleFieldName(field_index)) = try argToZig(param_type.?, local, info.getArg(@intCast(i), local));
+ }
+ }
+
+ if (comptime isVariadic(LastJsParam)) {
+ const T = LastJsParam.js_variadic;
+ const first = fixed_params.len;
+ const values = try local.call_arena.alloc(T, js_parameter_count -| first);
+ for (values, first..) |*value, i| {
+ value.* = try argToZig(T, local, info.getArg(@intCast(i), local));
}
+ @field(args, tupleFieldName(first + offset)) = .{ .values = values };
}
return args;
}
+
+fn isVariadic(comptime T: type) bool {
+ return @typeInfo(T) == .@"struct" and @hasDecl(T, "js_variadic");
+}
diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zig
index b612438f7..9fbffa9c7 100644
--- a/src/browser/js/bridge.zig
+++ b/src/browser/js/bridge.zig
@@ -208,9 +208,8 @@ pub const Function = struct {
break;
}
- // A slice of js.Value is always bound as variadic (see
- // Caller.getArgs) and variadics contribute 0 to length.
- if (@typeInfo(PT) == .pointer and @typeInfo(PT).pointer.size == .slice and @typeInfo(PT).pointer.child == js.Value) {
+ // a rest parameter contributes 0 to length
+ if (@typeInfo(PT) == .@"struct" and @hasDecl(PT, "js_variadic")) {
break;
}
count += 1;
diff --git a/src/browser/js/js.zig b/src/browser/js/js.zig
index 72b9b195c..52a03fa59 100644
--- a/src/browser/js/js.zig
+++ b/src/browser/js/js.zig
@@ -331,6 +331,18 @@ pub fn Nullable(comptime T: type) type {
};
}
+pub fn Variadic(comptime T: type) type {
+ return struct {
+ values: []const T,
+
+ pub const js_variadic = T;
+
+ pub fn init(values: []const T) @This() {
+ return .{ .values = values };
+ }
+ };
+}
+
// A WebIDL [EnforceRange] integer. NaN, +/i infinity and values outside of T's
// range are a TypeError.
pub fn EnforceRange(comptime T: type) type {
diff --git a/src/browser/tests/crypto.html b/src/browser/tests/crypto.html
index 39e89eb65..27ec81277 100644
--- a/src/browser/tests/crypto.html
+++ b/src/browser/tests/crypto.html
@@ -2909,6 +2909,7 @@
});
</script>
+<<<<<<< HEAD
<script id=export-and-format-order type=module>
const state = await testing.async();
const subtle = crypto.subtle;
@@ -3050,3 +3051,22 @@
}, results);
});
</script>
+
+<script id=key-usages-sequence type=module>
+ // keyUsages is a sequence<KeyUsage>: any iterable, and required
+ const state = await testing.async();
+ const algo = { name: "HMAC", hash: "SHA-256" };
+ const key = await crypto.subtle.generateKey(algo, true, new Set(["sign", "verify"]));
+ let missing;
+ try {
+ await crypto.subtle.generateKey(algo, true);
+ } catch (e) {
+ missing = e.name;
+ }
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(["sign", "verify"], key.usages);
+ testing.expectEqual("TypeError", missing);
+ });
+</script>
diff --git a/src/browser/tests/element/append.html b/src/browser/tests/element/append.html
index 1e6b36ead..5b267dde8 100644
--- a/src/browser/tests/element/append.html
+++ b/src/browser/tests/element/append.html
@@ -27,3 +27,19 @@
container.prepend(p4, 'some text ');
testing.expectEqual('<p>p4</p>some text <p>p3</p>', container.innerHTML, "prepend multiple nodes");
</script>
+
+<script id=rest_params>
+{
+ // `...nodes`: an array isn't spread, it's converted to a string
+ const container = document.createElement('div');
+ const p = document.createElement('p');
+ container.append([p, 'x']);
+ testing.expectEqual('[object HTMLParagraphElement],x', container.innerHTML);
+ testing.expectEqual(null, p.parentNode);
+ testing.expectEqual(0, container.append.length);
+ testing.expectEqual(0, container.prepend.length);
+ testing.expectEqual(0, container.before.length);
+ testing.expectEqual(0, container.replaceWith.length);
+ testing.expectEqual(0, container.replaceChildren.length);
+}
+</script>
diff --git a/src/browser/tests/element/class_list.html b/src/browser/tests/element/class_list.html
index 4ae7258db..ae112d38e 100644
--- a/src/browser/tests/element/class_list.html
+++ b/src/browser/tests/element/class_list.html
@@ -647,3 +647,18 @@
testing.expectEqual(true, result.done);
}
</script>
+
+<script id=rest_params>
+{
+ // add/remove take `...tokens`: an array is one argument, stringified
+ const div = document.createElement('div');
+ div.classList.add(['a', 'b']);
+ testing.expectEqual('a,b', div.className);
+ div.classList.add('c', 'd');
+ testing.expectEqual('a,b c d', div.className);
+ div.classList.remove(['a', 'b'], 'c');
+ testing.expectEqual('d', div.className);
+ testing.expectEqual(0, div.classList.add.length);
+ testing.expectEqual(0, div.classList.remove.length);
+}
+</script>
diff --git a/src/browser/tests/event/abort_controller.html b/src/browser/tests/event/abort_controller.html
index 10f65d3d8..28b9833a9 100644
--- a/src/browser/tests/event/abort_controller.html
+++ b/src/browser/tests/event/abort_controller.html
@@ -370,3 +370,15 @@
});
}
</script>
+
+<script id=any_sequence>
+{
+ // signals is a required sequence<AbortSignal>
+ testing.expectError('TypeError', () => AbortSignal.any());
+ testing.expectError('TypeError', () => AbortSignal.any(new AbortController().signal));
+ const c = new AbortController();
+ const signal = AbortSignal.any(new Set([c.signal]));
+ c.abort();
+ testing.expectEqual(true, signal.aborted);
+}
+</script>
diff --git a/src/browser/tests/net/websocket.html b/src/browser/tests/net/websocket.html
index e5bfb64d7..072af3002 100644
--- a/src/browser/tests/net/websocket.html
+++ b/src/browser/tests/net/websocket.html
@@ -875,3 +875,13 @@
});
}
</script>
+
+<script id=protocols>
+{
+ // `optional (DOMString or sequence<DOMString>) protocols`
+ testing.expectError('SyntaxError', () => new WebSocket('ws://127.0.0.1:9584/', 'a b'));
+ testing.expectError('SyntaxError', () => new WebSocket('ws://127.0.0.1:9584/', ['ok', 'a b']));
+ testing.expectError('SyntaxError', () => new WebSocket('ws://127.0.0.1:9584/', new Set(['a b'])));
+ testing.expectEqual(1, WebSocket.length);
+}
+</script>
diff --git a/src/browser/webapi/AbortSignal.zig b/src/browser/webapi/AbortSignal.zig
index c00ccaeeb..fc6ebaf95 100644
--- a/src/browser/webapi/AbortSignal.zig
+++ b/src/browser/webapi/AbortSignal.zig
@@ -191,12 +191,7 @@ fn createAborted(reason_: ?js.Value, exec: *const Execution) !*AbortSignal {
return signal;
}
-fn createAny(signals_value: js.Value, exec: *const Execution) !*AbortSignal {
- // The parameter isn't optional. If we declared it as a slice directy, the
- // bridge would treat it as a variadic and map it to empty rather than throwing
- // a TypeError as it should.
- const signals = try signals_value.toZig([]const *AbortSignal);
-
+fn createAny(signals: []const *AbortSignal, exec: *const Execution) !*AbortSignal {
const result = try init(exec);
for (signals) |source| {
if (source._aborted) {
diff --git a/src/browser/webapi/CData.zig b/src/browser/webapi/CData.zig
index c9adde5f0..5d4bb8bfc 100644
--- a/src/browser/webapi/CData.zig
+++ b/src/browser/webapi/CData.zig
@@ -439,29 +439,29 @@ pub fn remove(self: *CData, frame: *Frame) !void {
_ = try parent.removeChild(node, frame);
}
-pub fn before(self: *CData, nodes: []const Node.NodeOrText, frame: *Frame) !void {
+pub fn before(self: *CData, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
const node = self.asNode();
const parent = node.parentNode() orelse return;
- for (nodes) |node_or_text| {
+ for (nodes.values) |node_or_text| {
const child = try node_or_text.toNode(node.getDocument(frame));
_ = try parent.insertBefore(child, node, frame);
}
}
-pub fn after(self: *CData, nodes: []const Node.NodeOrText, frame: *Frame) !void {
+pub fn after(self: *CData, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
const node = self.asNode();
const parent = node.parentNode() orelse return;
- const viable_next = Node.NodeOrText.viableNextSibling(node, nodes);
+ const viable_next = Node.NodeOrText.viableNextSibling(node, nodes.values);
- for (nodes) |node_or_text| {
+ for (nodes.values) |node_or_text| {
const child = try node_or_text.toNode(node.getDocument(frame));
_ = try parent.insertBefore(child, viable_next, frame);
}
}
-pub fn replaceWith(self: *CData, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- return self.asNode().replaceWithNodes(nodes, frame);
+pub fn replaceWith(self: *CData, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
+ return self.asNode().replaceWithNodes(nodes.values, frame);
}
pub fn nextElementSibling(self: *CData) ?*Node.Element {
diff --git a/src/browser/webapi/Console.zig b/src/browser/webapi/Console.zig
index 2af45eb63..e68ac1c80 100644
--- a/src/browser/webapi/Console.zig
+++ b/src/browser/webapi/Console.zig
@@ -31,7 +31,7 @@ _counts: std.StringHashMapUnmanaged(u64) = .{},
pub const init: Console = .{};
-fn dispatchConsoleMessage(values: []js.Value, console_type: Notification.ConsoleMessageType, exec: *js.Execution) void {
+fn dispatchConsoleMessage(values: []const js.Value, console_type: Notification.ConsoleMessageType, exec: *js.Execution) void {
const notification = exec.session.notification;
const ts = lp.datetime.timestamp(.boot);
const local = exec.js.local.?;
@@ -53,49 +53,49 @@ fn dispatchConsoleMessage(values: []js.Value, console_type: Notification.Console
});
}
-pub fn trace(values: []js.Value, exec: *js.Execution) !void {
+pub fn trace(args: js.Variadic(js.Value), exec: *js.Execution) !void {
logger.debug(.js, "console.trace", .{
.stack = exec.js.local.?.stackTrace() catch "???",
- .args = ValueWriter{ .values = values },
+ .args = ValueWriter{ .values = args.values },
});
- dispatchConsoleMessage(values, .trace, exec);
+ dispatchConsoleMessage(args.values, .trace, exec);
}
-pub fn debug(values: []js.Value, exec: *js.Execution) void {
- logger.debug(.js, "console.debug", .{ValueWriter{ .values = values }});
- dispatchConsoleMessage(values, .debug, exec);
+pub fn debug(args: js.Variadic(js.Value), exec: *js.Execution) void {
+ logger.debug(.js, "console.debug", .{ValueWriter{ .values = args.values }});
+ dispatchConsoleMessage(args.values, .debug, exec);
}
-pub fn info(values: []js.Value, exec: *js.Execution) void {
- logger.info(.js, "console.info", .{ValueWriter{ .values = values }});
- dispatchConsoleMessage(values, .info, exec);
+pub fn info(args: js.Variadic(js.Value), exec: *js.Execution) void {
+ logger.info(.js, "console.info", .{ValueWriter{ .values = args.values }});
+ dispatchConsoleMessage(args.values, .info, exec);
}
-pub fn log(values: []js.Value, exec: *js.Execution) void {
- logger.info(.js, "console.log", .{ValueWriter{ .values = values }});
- dispatchConsoleMessage(values, .log, exec);
+pub fn log(args: js.Variadic(js.Value), exec: *js.Execution) void {
+ logger.info(.js, "console.log", .{ValueWriter{ .values = args.values }});
+ dispatchConsoleMessage(args.values, .log, exec);
}
-pub fn warn(values: []js.Value, exec: *js.Execution) void {
- logger.warn(.js, "console.warn", .{ValueWriter{ .values = values }});
- dispatchConsoleMessage(values, .warning, exec);
+pub fn warn(args: js.Variadic(js.Value), exec: *js.Execution) void {
+ logger.warn(.js, "console.warn", .{ValueWriter{ .values = args.values }});
+ dispatchConsoleMessage(args.values, .warning, exec);
}
pub fn clear() void {}
-pub fn assert(assertion_: ?js.Value, values: []js.Value, exec: *js.Execution) void {
+pub fn assert(assertion_: ?js.Value, args: js.Variadic(js.Value), exec: *js.Execution) void {
if (assertion_) |assertion| {
if (assertion.toBool()) {
return;
}
}
- logger.warn(.js, "console.assert", .{ValueWriter{ .values = values }});
- dispatchConsoleMessage(values, .warning, exec);
+ logger.warn(.js, "console.assert", .{ValueWriter{ .values = args.values }});
+ dispatchConsoleMessage(args.values, .warning, exec);
}
-pub fn @"error"(values: []js.Value, exec: *js.Execution) void {
- logger.warn(.js, "console.error", .{ValueWriter{ .values = values, .stack = exec.js.local.?.stackTrace() catch |err| @errorName(err) orelse "???" }});
- dispatchConsoleMessage(values, .@"error", exec);
+pub fn @"error"(args: js.Variadic(js.Value), exec: *js.Execution) void {
+ logger.warn(.js, "console.error", .{ValueWriter{ .values = args.values, .stack = exec.js.local.?.stackTrace() catch |err| @errorName(err) orelse "???" }});
+ dispatchConsoleMessage(args.values, .@"error", exec);
}
pub fn table(data: ?js.Value, columns: ?js.Value) void {
@@ -104,7 +104,7 @@ pub fn table(data: ?js.Value, columns: ?js.Value) void {
pub fn dir(item_: ?js.Value, _: ?js.Value, exec: *js.Execution) void {
var buf: [1]js.Value = undefined;
- const values: []js.Value = if (item_) |item| blk: {
+ const values: []const js.Value = if (item_) |item| blk: {
buf[0] = item;
break :blk buf[0..1];
} else buf[0..0];
@@ -112,9 +112,9 @@ pub fn dir(item_: ?js.Value, _: ?js.Value, exec: *js.Execution) void {
dispatchConsoleMessage(values, .dir, exec);
}
-pub fn dirxml(values: []js.Value, exec: *js.Execution) void {
- logger.info(.js, "console.dirxml", .{ValueWriter{ .values = values }});
- dispatchConsoleMessage(values, .dirxml, exec);
+pub fn dirxml(args: js.Variadic(js.Value), exec: *js.Execution) void {
+ logger.info(.js, "console.dirxml", .{ValueWriter{ .values = args.values }});
+ dispatchConsoleMessage(args.values, .dirxml, exec);
}
pub fn count(label_: ?[]const u8, exec: *js.Execution) !void {
@@ -181,17 +181,17 @@ pub fn timeEnd(label_: ?[]const u8, exec: *js.Execution) void {
logger.info(.js, "console.timeEnd", .{ .label = label, .elapsed = elapsed - kv.value });
}
-pub fn group(values: []js.Value) void {
- logger.info(.js, "console.group", .{ValueWriter{ .values = values }});
+pub fn group(args: js.Variadic(js.Value)) void {
+ logger.info(.js, "console.group", .{ValueWriter{ .values = args.values }});
}
-pub fn groupCollapsed(values: []js.Value) void {
- logger.info(.js, "console.groupCollapsed", .{ValueWriter{ .values = values }});
+pub fn groupCollapsed(args: js.Variadic(js.Value)) void {
+ logger.info(.js, "console.groupCollapsed", .{ValueWriter{ .values = args.values }});
}
fn groupEnd() void {}
const ValueWriter = struct {
- values: []js.Value,
+ values: []const js.Value,
stack: ?[]const u8 = null,
pub fn format(self: ValueWriter, writer: *std.Io.Writer) !void {
@@ -219,7 +219,7 @@ const ValueWriter = struct {
return writer.endArray();
}
- fn valuesToLog(self: ValueWriter) []js.Value {
+ fn valuesToLog(self: ValueWriter) []const js.Value {
if (lp.build_config.wpt_extensions) {
// A few WPT tests print HUGE arrays, it's at best, annoying when
// running it locally
diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zig
index f5945cd42..d79e28210 100644
--- a/src/browser/webapi/Document.zig
+++ b/src/browser/webapi/Document.zig
@@ -862,13 +862,13 @@ fn importNode(self: *const Document, node: *Node, deep_: ?bool, frame: *Frame) !
return node.cloneNodeInto(deep_ orelse false, self, frame);
}
-pub fn append(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- try validateDocumentNodes(self, nodes);
+pub fn append(self: *Document, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
+ try validateDocumentNodes(self, nodes.values);
const parent = self.asNode();
frame.domChanged();
- for (nodes) |node_or_text| {
+ for (nodes.values) |node_or_text| {
const child = try node_or_text.toNode(self);
// DocumentFragments are special - append all their children
@@ -886,16 +886,16 @@ pub fn append(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !v
}
}
-pub fn prepend(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- try validateDocumentNodes(self, nodes);
+pub fn prepend(self: *Document, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
+ try validateDocumentNodes(self, nodes.values);
const parent = self.asNode();
frame.domChanged();
- var i = nodes.len;
+ var i = nodes.values.len;
while (i > 0) {
i -= 1;
- const child = try nodes[i].toNode(self);
+ const child = try nodes.values[i].toNode(self);
// DocumentFragments are special - need to insert all their children
if (child.is(Node.DocumentFragment)) |frag| {
@@ -929,8 +929,8 @@ pub fn prepend(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !
}
}
-pub fn replaceChildren(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- return self.asNode().replaceChildren(nodes, frame);
+pub fn replaceChildren(self: *Document, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
+ return self.asNode().replaceChildren(nodes.values, frame);
}
pub fn moveBefore(self: *Document, node: js.Value, child: js.Value, frame: *Frame) !void {
@@ -1077,15 +1077,15 @@ fn looksLikeNewDocument(html: []const u8) bool {
std.ascii.startsWithIgnoreCase(trimmed, "<html");
}
-pub fn write(self: *Document, text: []const []const u8, frame: *Frame) !void {
- return self.writeInternal(text, false, frame);
+pub fn write(self: *Document, text: js.Variadic([]const u8), frame: *Frame) !void {
+ return self.writeInternal(text.values, false, frame);
}
// https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-writeln
// `writeln(...text)` runs the document write steps with `text` followed by a
// U+000A LINE FEED character.
-fn writeln(self: *Document, text: []const []const u8, frame: *Frame) !void {
- return self.writeInternal(text, true, frame);
+fn writeln(self: *Document, text: js.Variadic([]const u8), frame: *Frame) !void {
+ return self.writeInternal(text.values, true, frame);
}
fn writeInternal(self: *Document, text: []const []const u8, append_newline: bool, call_frame: *Frame) !void {
diff --git a/src/browser/webapi/DocumentFragment.zig b/src/browser/webapi/DocumentFragment.zig
index 38698c58b..86f1148d7 100644
--- a/src/browser/webapi/DocumentFragment.zig
+++ b/src/browser/webapi/DocumentFragment.zig
@@ -135,26 +135,26 @@ fn getChildElementCount(self: *DocumentFragment) usize {
return count;
}
-pub fn append(self: *DocumentFragment, nodes: []const Node.NodeOrText, frame: *Frame) !void {
+pub fn append(self: *DocumentFragment, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
const parent = self.asNode();
- for (nodes) |node_or_text| {
+ for (nodes.values) |node_or_text| {
const child = try node_or_text.toNode(parent.getDocument(frame));
_ = try parent.appendChild(child, frame);
}
}
-pub fn prepend(self: *DocumentFragment, nodes: []const Node.NodeOrText, frame: *Frame) !void {
+pub fn prepend(self: *DocumentFragment, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
const parent = self.asNode();
- var i = nodes.len;
+ var i = nodes.values.len;
while (i > 0) {
i -= 1;
- const child = try nodes[i].toNode(parent.getDocument(frame));
+ const child = try nodes.values[i].toNode(parent.getDocument(frame));
_ = try parent.insertBefore(child, parent.firstChild(), frame);
}
}
-pub fn replaceChildren(self: *DocumentFragment, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- return self.asNode().replaceChildren(nodes, frame);
+pub fn replaceChildren(self: *DocumentFragment, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
+ return self.asNode().replaceChildren(nodes.values, frame);
}
pub fn moveBefore(self: *DocumentFragment, node: js.Value, child: js.Value, frame: *Frame) !void {
diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zig
index 1ccf534bb..02a664310 100644
--- a/src/browser/webapi/Element.zig
+++ b/src/browser/webapi/Element.zig
@@ -1186,12 +1186,12 @@ pub fn getDataset(self: *Element, frame: *Frame) !*DOMStringMap {
return gop.value_ptr.*;
}
-pub fn replaceChildren(self: *Element, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- return self.asNode().replaceChildren(nodes, frame);
+pub fn replaceChildren(self: *Element, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
+ return self.asNode().replaceChildren(nodes.values, frame);
}
-pub fn replaceWith(self: *Element, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- return self.asNode().replaceWithNodes(nodes, frame);
+pub fn replaceWith(self: *Element, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
+ return self.asNode().replaceWithNodes(nodes.values, frame);
}
pub fn remove(self: *Element, frame: *Frame) void {
@@ -1395,34 +1395,34 @@ pub fn getChildren(self: *Element, frame: *Frame) !collections.NodeLive(.child_e
return collections.NodeLive(.child_elements).init(self.asNode(), {}, frame);
}
-pub fn append(self: *Element, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- return self.asNode().appendNodes(nodes, frame);
+pub fn append(self: *Element, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
+ return self.asNode().appendNodes(nodes.values, frame);
}
-pub fn prepend(self: *Element, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- return self.asNode().prependNodes(nodes, frame);
+pub fn prepend(self: *Element, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
+ return self.asNode().prependNodes(nodes.values, frame);
}
pub fn moveBefore(self: *Element, node: js.Value, child: js.Value, frame: *Frame) !void {
return self.asNode().moveBefore(node, child, frame);
}
-pub fn before(self: *Element, nodes: []const Node.NodeOrText, frame: *Frame) !void {
+pub fn before(self: *Element, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
const node = self.asNode();
const parent = node.parentNode() orelse return;
- for (nodes) |node_or_text| {
+ for (nodes.values) |node_or_text| {
const child = try node_or_text.toNode(self.getDocument(frame));
_ = try parent.insertBefore(child, node, frame);
}
}
-pub fn after(self: *Element, nodes: []const Node.NodeOrText, frame: *Frame) !void {
+pub fn after(self: *Element, nodes: js.Variadic(Node.NodeOrText), frame: *Frame) !void {
const node = self.asNode();
const parent = node.parentNode() orelse return;
- const viable_next = Node.NodeOrText.viableNextSibling(node, nodes);
+ const viable_next = Node.NodeOrText.viableNextSibling(node, nodes.values);
- for (nodes) |node_or_text| {
+ for (nodes.values) |node_or_text| {
const child = try node_or_text.toNode(self.getDocument(frame));
_ = try parent.insertBefore(child, viable_next, frame);
}
diff --git a/src/browser/webapi/HTMLDocument.zig b/src/browser/webapi/HTMLDocument.zig
index 21cc143ab..589913994 100644
--- a/src/browser/webapi/HTMLDocument.zig
+++ b/src/browser/webapi/HTMLDocument.zig
@@ -154,9 +154,9 @@ fn setTitle(self: *HTMLDocument, title: []const u8, frame: *Frame) !void {
if (node.is(Element.Html.Title)) |title_element| {
// Replace children, but don't create text node for empty string
if (title.len == 0) {
- return title_element.asElement().replaceChildren(&.{}, frame);
+ return title_element.asElement().replaceChildren(.init(&.{}), frame);
} else {
- return title_element.asElement().replaceChildren(&.{.{ .text = title }}, frame);
+ return title_element.asElement().replaceChildren(.init(&.{.{ .text = title }}), frame);
}
}
}
@@ -167,7 +167,7 @@ fn setTitle(self: *HTMLDocument, title: []const u8, frame: *Frame) !void {
// Only add text if non-empty
if (title.len > 0) {
- try title_element.replaceChildren(&.{.{ .text = title }}, frame);
+ try title_element.replaceChildren(.init(&.{.{ .text = title }}), frame);
}
_ = try head.asNode().appendChild(title_node, frame);
diff --git a/src/browser/webapi/Node.zig b/src/browser/webapi/Node.zig
index de235ed51..9bc4674d8 100644
--- a/src/browser/webapi/Node.zig
+++ b/src/browser/webapi/Node.zig
@@ -459,9 +459,9 @@ pub fn setTextContent(self: *Node, data: []const u8, frame: *Frame) !void {
.element => {
const el = self.subtype(Element);
if (data.len == 0) {
- return el.replaceChildren(&.{}, frame);
+ return el.replaceChildren(.init(&.{}), frame);
}
- return el.replaceChildren(&.{.{ .text = data }}, frame);
+ return el.replaceChildren(.init(&.{.{ .text = data }}), frame);
},
// Per spec, setting textContent on CharacterData runs replaceData(0, length, value)
.cdata => {
@@ -473,9 +473,9 @@ pub fn setTextContent(self: *Node, data: []const u8, frame: *Frame) !void {
.document_fragment => {
const frag = self.subtype(DocumentFragment);
if (data.len == 0) {
- return frag.replaceChildren(&.{}, frame);
+ return frag.replaceChildren(.init(&.{}), frame);
}
- return frag.replaceChildren(&.{.{ .text = data }}, frame);
+ return frag.replaceChildren(.init(&.{.{ .text = data }}), frame);
},
.attribute => return self.subtype(Element.Attribute).setValue(.wrap(data), frame),
}
diff --git a/src/browser/webapi/Timers.zig b/src/browser/webapi/Timers.zig
index 409c74556..7d7db64c5 100644
--- a/src/browser/webapi/Timers.zig
+++ b/src/browser/webapi/Timers.zig
@@ -82,7 +82,7 @@ pub const Mode = enum {
const ScheduleOpts = struct {
repeat: bool,
- params: []js.Value.Global,
+ params: []const js.Value.Global,
name: []const u8,
blocks_done: bool = true,
mode: Mode = .normal,
diff --git a/src/browser/webapi/Window.zig b/src/browser/webapi/Window.zig
index 7407d8d24..911e632fb 100644
--- a/src/browser/webapi/Window.zig
+++ b/src/browser/webapi/Window.zig
@@ -425,20 +425,20 @@ pub fn fetch(_: *const Window, input: Fetch.Input, options: ?Fetch.InitOpts, exe
return Fetch.init(input, options, exec);
}
-pub fn setTimeout(self: *Window, handler: Timers.LegacyHandler, delay_ms: ?i32, params: []js.Value.Global, exec: *js.Execution) !u32 {
+pub fn setTimeout(self: *Window, handler: Timers.LegacyHandler, delay_ms: ?i32, params: js.Variadic(js.Value.Global), exec: *js.Execution) !u32 {
const cb = try handler.resolve(exec);
return self._timers.schedule(exec, cb, Timers.delayFromJs(delay_ms), .{
.repeat = false,
- .params = params,
+ .params = params.values,
.name = "window.setTimeout",
});
}
-pub fn setInterval(self: *Window, handler: Timers.LegacyHandler, delay_ms: ?i32, params: []js.Value.Global, exec: *js.Execution) !u32 {
+pub fn setInterval(self: *Window, handler: Timers.LegacyHandler, delay_ms: ?i32, params: js.Variadic(js.Value.Global), exec: *js.Execution) !u32 {
const cb = try handler.resolve(exec);
return self._timers.schedule(exec, cb, Timers.delayFromJs(delay_ms), .{
.repeat = true,
- .params = params,
+ .params = params.values,
.name = "window.setInterval",
});
}
diff --git a/src/browser/webapi/WorkerGlobalScope.zig b/src/browser/webapi/WorkerGlobalScope.zig
index f0633f2c7..c11b97d29 100644
--- a/src/browser/webapi/WorkerGlobalScope.zig
+++ b/src/browser/webapi/WorkerGlobalScope.zig
@@ -356,7 +356,7 @@ pub fn unhandledPromiseRejection(self: *WorkerGlobalScope, no_handler: bool, pro
return event._prevent_default;
}
-fn importScripts(self: *WorkerGlobalScope, urls: []const [:0]const u8) !void {
+fn importScripts(self: *WorkerGlobalScope, urls: JS.Variadic([:0]const u8)) !void {
if (self._is_module) {
// not allowed to be called when the worker type is module (scripts should
// use actual imports).
@@ -368,7 +368,7 @@ fn importScripts(self: *WorkerGlobalScope, urls: []const [:0]const u8) !void {
const arena = try session.getArena(.small, "importScript");
defer arena.release();
- for (urls) |url| {
+ for (urls.values) |url| {
defer arena.resetRetain();
try self.importScript(arena.allocator(), url);
}
@@ -482,11 +482,11 @@ fn queueMicrotask(self: *WorkerGlobalScope, cb: JS.Function) void {
self.js.queueMicrotaskFunc(cb);
}
-pub fn setTimeout(self: *WorkerGlobalScope, handler: Timers.LegacyHandler, delay_ms: ?i32, params: []JS.Value.Global, exec: *JS.Execution) !u32 {
+pub fn setTimeout(self: *WorkerGlobalScope, handler: Timers.LegacyHandler, delay_ms: ?i32, params: JS.Variadic(JS.Value.Global), exec: *JS.Execution) !u32 {
const cb = try handler.resolve(exec);
return self._timers.schedule(exec, cb, Timers.delayFromJs(delay_ms), .{
.repeat = false,
- .params = params,
+ .params = params.values,
.name = "worker.setTimeout",
});
}
@@ -495,11 +495,11 @@ fn clearTimeout(self: *WorkerGlobalScope, id: u32) void {
self._timers.clear(id);
}
-pub fn setInterval(self: *WorkerGlobalScope, handler: Timers.LegacyHandler, delay_ms: ?i32, params: []JS.Value.Global, exec: *JS.Execution) !u32 {
+pub fn setInterval(self: *WorkerGlobalScope, handler: Timers.LegacyHandler, delay_ms: ?i32, params: JS.Variadic(JS.Value.Global), exec: *JS.Execution) !u32 {
const cb = try handler.resolve(exec);
return self._timers.schedule(exec, cb, Timers.delayFromJs(delay_ms), .{
.repeat = true,
- .params = params,
+ .params = params.values,
.name = "worker.setInterval",
});
}
diff --git a/src/browser/webapi/collections/DOMTokenList.zig b/src/browser/webapi/collections/DOMTokenList.zig
index 2b4f162ae..f2b821df6 100644
--- a/src/browser/webapi/collections/DOMTokenList.zig
+++ b/src/browser/webapi/collections/DOMTokenList.zig
@@ -117,29 +117,29 @@ pub fn contains(self: *const DOMTokenList, search: []const u8) !bool {
return false;
}
-pub fn add(self: *DOMTokenList, tokens: []const []const u8, frame: *Frame) !void {
- for (tokens) |token| {
+pub fn add(self: *DOMTokenList, tokens: js.Variadic([]const u8), frame: *Frame) !void {
+ for (tokens.values) |token| {
try validateToken(token);
}
const allocator = frame.local_arena;
var lookup = try self.getTokens(allocator);
- try lookup.ensureUnusedCapacity(allocator, tokens.len);
+ try lookup.ensureUnusedCapacity(allocator, tokens.values.len);
- for (tokens) |token| {
+ for (tokens.values) |token| {
try lookup.put(allocator, token, {});
}
try self.updateAttribute(lookup, frame);
}
-pub fn remove(self: *DOMTokenList, tokens: []const []const u8, frame: *Frame) !void {
- for (tokens) |token| {
+pub fn remove(self: *DOMTokenList, tokens: js.Variadic([]const u8), frame: *Frame) !void {
+ for (tokens.values) |token| {
try validateToken(token);
}
var lookup = try self.getTokens(frame.local_arena);
- for (tokens) |token| {
+ for (tokens.values) |token| {
_ = lookup.orderedRemove(token);
}
try self.updateAttribute(lookup, frame);
@@ -154,24 +154,24 @@ pub fn toggle(self: *DOMTokenList, token: []const u8, force: ?bool, frame: *Fram
if (f) {
if (!has_token) {
const tokens_to_add = [_][]const u8{token};
- try self.add(&tokens_to_add, frame);
+ try self.add(.init(&tokens_to_add), frame);
}
return true;
} else {
if (has_token) {
const tokens_to_remove = [_][]const u8{token};
- try self.remove(&tokens_to_remove, frame);
+ try self.remove(.init(&tokens_to_remove), frame);
}
return false;
}
} else {
if (has_token) {
const tokens_to_remove = [_][]const u8{token};
- try self.remove(tokens_to_remove[0..], frame);
+ try self.remove(.init(&tokens_to_remove), frame);
return false;
} else {
const tokens_to_add = [_][]const u8{token};
- try self.add(tokens_to_add[0..], frame);
+ try self.add(.init(&tokens_to_add), frame);
return true;
}
}
diff --git a/src/browser/webapi/element/Html.zig b/src/browser/webapi/element/Html.zig
index 5a5637800..90efdc4f9 100644
--- a/src/browser/webapi/element/Html.zig
+++ b/src/browser/webapi/element/Html.zig
@@ -360,7 +360,7 @@ pub fn getInnerText(self: *HtmlElement, writer: *std.Io.Writer, frame: *Frame) !
pub fn setInnerText(self: *HtmlElement, text: []const u8, frame: *Frame) !void {
const items = try renderedTextFragment(self.asNode().getDocument(frame), text, frame);
- try self.asElement().replaceChildren(items, frame);
+ try self.asElement().replaceChildren(.init(items), frame);
}
pub fn setOuterText(self: *HtmlElement, text: []const u8, frame: *Frame) !void {
@@ -382,7 +382,7 @@ pub fn setOuterText(self: *HtmlElement, text: []const u8, frame: *Frame) !void {
// node so surrounding text can merge with it.
items = &.{.{ .text = "" }};
}
- try el.replaceWith(items, frame);
+ try el.replaceWith(.init(items), frame);
// Merge with the immediately neighbouring Text nodes (only those two; the
// tree is not fully normalised, per spec).
diff --git a/src/browser/webapi/element/html/Slot.zig b/src/browser/webapi/element/html/Slot.zig
index 0333fdaa5..27becd731 100644
--- a/src/browser/webapi/element/html/Slot.zig
+++ b/src/browser/webapi/element/html/Slot.zig
@@ -126,17 +126,12 @@ fn appendFlattened(comptime elements: bool, coll: CollectionType(elements), node
}
}
-// DOM spec HTMLSlotElement.assign(...nodes). Takes js.Value so the bridge
-// always treats the parameter as variadic: per WebIDL it's a rest parameter
-// of (Element or Text), so passing an array must throw a TypeError.
-pub fn assign(self: *Slot, values: []const js.Value, frame: *Frame) !void {
- const nodes = try frame.call_arena.alloc(*Node, values.len);
- for (values, nodes) |value, *entry| {
- const node = value.toZig(*Node) catch return error.TypeError;
+// DOM spec HTMLSlotElement.assign(...nodes), each an Element or Text.
+pub fn assign(self: *Slot, nodes: js.Variadic(*Node), frame: *Frame) !void {
+ for (nodes.values) |node| {
if (!slotting.isSlottable(node)) {
return error.TypeError;
}
- entry.* = node;
}
const page = frame.page;
@@ -145,7 +140,7 @@ pub fn assign(self: *Slot, values: []const js.Value, frame: *Frame) !void {
}
self._manually_assigned.clearRetainingCapacity();
- for (nodes) |node| {
+ for (nodes.values) |node| {
const gop = try page._manual_slot_assignments.getOrPut(page.arena, node);
if (gop.found_existing) {
const other = gop.value_ptr.*;
diff --git a/src/browser/webapi/net/WebSocket.zig b/src/browser/webapi/net/WebSocket.zig
index 9c7754bd7..37333fb32 100644
--- a/src/browser/webapi/net/WebSocket.zig
+++ b/src/browser/webapi/net/WebSocket.zig
@@ -132,7 +132,22 @@ const BinaryType = enum {
arraybuffer,
};
-pub fn init(url: []const u8, protocols: [][]const u8, exec: *const Execution) !*WebSocket {
+// WebIDL: `optional (DOMString or sequence<DOMString>) protocols = []`
+const Protocols = union(enum) {
+ list: []const []const u8,
+ one: []const u8,
+};
+
+pub fn init(url: []const u8, protocols_: ?Protocols, exec: *const Execution) !*WebSocket {
+ var one: [1][]const u8 = undefined;
+ const protocols: []const []const u8 = if (protocols_) |p| switch (p) {
+ .list => |list| list,
+ .one => |protocol| blk: {
+ one[0] = protocol;
+ break :blk &one;
+ },
+ } else &.{};
+
{
if (std.mem.findScalar(u8, url, '#') != null) {
// Fragments are not allowed in WebSocket URLs.
@@ -209,7 +224,7 @@ pub fn init(url: []const u8, protocols: [][]const u8, exec: *const Execution) !*
return self;
}
-fn connect(self: *WebSocket, protocols: [][]const u8) !void {
+fn connect(self: *WebSocket, protocols: []const []const u8) !void {
const exec = self._exec;
const arena = self._arena;
const resolved_url = self._url;
@@ -980,8 +995,7 @@ test "WebApi: WebSocket send owns its message arena once when the unpause fails"
frame.js.localScope(&ls);
defer ls.deinit();
- var protocols: [0][]const u8 = .{};
- const ws = try WebSocket.init("ws://127.0.0.1:9582/ws", &protocols, &frame.js.execution);
+ const ws = try WebSocket.init("ws://127.0.0.1:9582/ws", null, &frame.js.execution);
try testing.expect(ws._conn != null);
// connect() tracked the easy handle but no tick has performed it, so