Lightpanda: the headless browser designed for AI and automation
webapi: add the Payment Request API
Adrià Arrufat9a87de9b3610
diff --git a/src/browser/Factory.zig b/src/browser/Factory.zigindex cedcc6eda..7162e6ccc 100644--- a/src/browser/Factory.zig+++ b/src/browser/Factory.zig@@ -114,9 +114,15 @@ pub fn event(_: *const Factory, arena: *lp.Arena, typ: String, child: anytype) !return chain.get(1);}-pub fn uiEvent(_: *const Factory, arena: *lp.Arena, typ: String, child: anytype) !*@TypeOf(child) {+pub fn uiEvent(self: *const Factory, arena: *lp.Arena, typ: String, child: anytype) !*@TypeOf(child) {+ return self.eventWithParent(UIEvent, arena, typ, child);+}++/// An Event subclass whose parent is itself an Event subclass with no fields+/// of its own to fill in.+pub fn eventWithParent(_: *const Factory, comptime Parent: type, arena: *lp.Arena, typ: String, child: anytype) !*@TypeOf(child) {const chain = try PrototypeChain(- &.{ Event, UIEvent, @TypeOf(child) },+ &.{ Event, Parent, @TypeOf(child) },).allocate(arena.allocator());// Special case: Event has a _type_string field, so we need manual setupdiff --git a/src/browser/js/Context.zig b/src/browser/js/Context.zigindex ba8b1339a..96fc955ff 100644--- a/src/browser/js/Context.zig+++ b/src/browser/js/Context.zig@@ -269,10 +269,14 @@ pub fn setOrigin(self: *Context, key: ?[]const u8) !void {const token_local = v8.v8__Global__Get(&origin.security_token, isolate.handle);v8.v8__Context__SetSecurityToken(ls.local.handle, token_local);- // navigator.serviceWorker is [SecureContext]. With the feature- // disabled, Env.createContext has already removed it.- if (self.global == .frame and self.page.session.experimental_features.serviceworker and self.execution.isSecureContext() == false) {- env.hideServiceWorker(true, ls.local.handle, v8.v8__Context__Global(ls.local.handle).?);+ if (self.global == .frame and self.execution.isSecureContext() == false) {+ const global_obj = v8.v8__Context__Global(ls.local.handle).?;+ // navigator.serviceWorker is [SecureContext]. With the feature+ // disabled, Env.createContext has already removed it.+ if (self.page.session.experimental_features.serviceworker) {+ env.hideServiceWorker(true, ls.local.handle, global_obj);+ }+ env.hideSecureContextInterfaces(ls.local.handle, global_obj);}}}diff --git a/src/browser/js/Env.zig b/src/browser/js/Env.zigindex fa7d020dc..4408e288c 100644--- a/src/browser/js/Env.zig+++ b/src/browser/js/Env.zig@@ -97,7 +97,7 @@ inspector: ?*Inspector,// which an be created once per isolate.private_symbols: PrivateSymbols,-// Interned names for `hideServiceWorker`.+// Interned names for `hideServiceWorker` and `hideSecureContextInterfaces`.disabled_api_names: DisabledApiNames,microtask_queues_are_running: bool,@@ -435,10 +435,23 @@ pub fn hideServiceWorker(self: *const Env, comptime is_frame: bool, v8_context:// A [Global] interface's members are on its prototype and mirrored onto the// global itself.self.deletePrototypeMember(v8_context, global_obj, if (comptime is_frame) "window" else "worker_global_scope", "caches");+ self.deleteGlobal(v8_context, global_obj, "caches");+}++// [SecureContext] interfaces that a frame without a potentially trustworthy+// origin must not see. Like serviceWorker, they're baked into the snapshot, so+// they're deleted per context rather than never added.+pub fn hideSecureContextInterfaces(self: *const Env, v8_context: *const v8.Context, global_obj: *const v8.Object) void {+ inline for (.{ "payment_request", "payment_response", "payment_request_update_event", "payment_method_change_event" }) |name| {+ self.deleteGlobal(v8_context, global_obj, name);+ }+}++fn deleteGlobal(self: *const Env, v8_context: *const v8.Context, global_obj: *const v8.Object, comptime name: []const u8) void {var deleted: v8.MaybeBool = undefined;- v8.v8__Object__Delete(global_obj, v8_context, @ptrCast(self.disabled_api_names.get(self.isolate.handle, "caches")), &deleted);+ v8.v8__Object__Delete(global_obj, v8_context, @ptrCast(self.disabled_api_names.get(self.isolate.handle, name)), &deleted);if (deleted.has_value == false or deleted.value == false) {- log.warn(.js, "experimental API not hidden", .{ .interface = "global", .member = "caches" });+ log.warn(.js, "API not hidden", .{ .interface = "global", .member = name });}}@@ -995,6 +1008,10 @@ const DisabledApiNames = struct {prototype: v8.Eternal,service_worker: v8.Eternal,caches: v8.Eternal,+ payment_request: v8.Eternal,+ payment_response: v8.Eternal,+ payment_request_update_event: v8.Eternal,+ payment_method_change_event: v8.Eternal,fn init(isolate: *v8.Isolate) DisabledApiNames {var self: DisabledApiNames = undefined;@@ -1004,6 +1021,10 @@ const DisabledApiNames = struct {intern(isolate, &self.prototype, "prototype");intern(isolate, &self.service_worker, "serviceWorker");intern(isolate, &self.caches, "caches");+ intern(isolate, &self.payment_request, "PaymentRequest");+ intern(isolate, &self.payment_response, "PaymentResponse");+ intern(isolate, &self.payment_request_update_event, "PaymentRequestUpdateEvent");+ intern(isolate, &self.payment_method_change_event, "PaymentMethodChangeEvent");return self;}diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zigindex 33ae9187a..032714dd2 100644--- a/src/browser/js/bridge.zig+++ b/src/browser/js/bridge.zig@@ -1266,6 +1266,10 @@ pub const PageJsApis = flattenTypes(&.{@import("../webapi/geolocation/GeolocationPosition.zig"),@import("../webapi/geolocation/GeolocationCoordinates.zig"),@import("../webapi/geolocation/GeolocationPositionError.zig"),+ @import("../webapi/payment/PaymentRequest.zig"),+ @import("../webapi/payment/PaymentResponse.zig"),+ @import("../webapi/payment/PaymentRequestUpdateEvent.zig"),+ @import("../webapi/payment/PaymentMethodChangeEvent.zig"),@import("../webapi/CustomElementRegistry.zig"),@import("../webapi/ResizeObserver.zig"),@import("../webapi/IdleDeadline.zig"),diff --git a/src/browser/tests/payment_request.html b/src/browser/tests/payment_request.htmlnew file mode 100644index 000000000..07bd2184f--- /dev/null+++ b/src/browser/tests/payment_request.html@@ -0,0 +1,185 @@+<!DOCTYPE html>+<script src="./testing.js"></script>++<script>+ const METHODS = [{ supportedMethods: 'https://example.com/pay' }];+ const DETAILS = { total: { label: 'Total', amount: { currency: 'USD', value: '10.00' } } };+</script>++<script id=shape>+ testing.expectEqual('function', typeof PaymentRequest);+ testing.expectEqual('function', typeof PaymentResponse);+ testing.expectEqual('function', typeof PaymentRequestUpdateEvent);+ testing.expectEqual('function', typeof PaymentMethodChangeEvent);+ testing.expectTrue(PaymentRequest.prototype instanceof EventTarget);+ testing.expectTrue(PaymentResponse.prototype instanceof EventTarget);+ testing.expectTrue(PaymentMethodChangeEvent.prototype instanceof PaymentRequestUpdateEvent);+ testing.expectError('TypeError', () => new PaymentResponse());+</script>++<script id=hidden_outside_secure_context type=module>+ // data: has an opaque origin, so it isn't a secure context+ {+ const state = await testing.async();+ window.addEventListener('message', (e) => state.resolve(e.data));++ const f = document.createElement('iframe');+ f.src = "data:text/html,<script>parent.postMessage({secure: isSecureContext, exposed: ['PaymentRequest', 'PaymentResponse', 'PaymentRequestUpdateEvent', 'PaymentMethodChangeEvent'].filter((n) => n in window)}, '*')<\/script>";+ document.body.appendChild(f);++ await state.done((data) => {+ testing.expectEqual(false, data.secure);+ testing.expectEqual([], data.exposed);+ });+ }+</script>++<script id=constructor>+ {+ const req = new PaymentRequest(METHODS, DETAILS);+ testing.expectTrue(req instanceof PaymentRequest);+ testing.expectTrue(req instanceof EventTarget);+ testing.expectEqual('[object PaymentRequest]', Object.prototype.toString.call(req));+ testing.expectTrue(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(req.id));+ testing.expectEqual(null, req.shippingAddress);+ testing.expectEqual(null, req.shippingOption);+ testing.expectEqual(null, req.shippingType);+ testing.expectEqual(null, req.onpaymentmethodchange);+ }+ {+ const req = new PaymentRequest(+ [{ supportedMethods: 'basic-card' }, { supportedMethods: 'pay2-go' }, { supportedMethods: 'https://example.com/pay' }],+ { id: 'order-1', ...DETAILS, displayItems: [{ label: 'Discount', amount: { currency: 'usd', value: '-1' } }] },+ );+ testing.expectEqual('order-1', req.id);+ }+ new PaymentRequest([{ supportedMethods: 'http://localhost/pay' }, { supportedMethods: 'http://127.0.0.1:9/pay' }], DETAILS);+</script>++<script id=shipping>+ {+ const shippingOptions = [+ { id: 'a', label: 'A', amount: { currency: 'USD', value: '0' } },+ { id: 'b', label: 'B', amount: { currency: 'USD', value: '5' }, selected: true },+ ];+ const req = new PaymentRequest(METHODS, { ...DETAILS, shippingOptions }, { requestShipping: true, shippingType: 'delivery' });+ testing.expectEqual('b', req.shippingOption);+ testing.expectEqual('delivery', req.shippingType);+ }+ {+ // without requestShipping, shipping options are ignored, duplicates included+ const dup = [+ { id: 'a', label: 'A', amount: { currency: 'USD', value: '0' }, selected: true },+ { id: 'a', label: 'A', amount: { currency: 'USD', value: '0' } },+ ];+ const req = new PaymentRequest(METHODS, { ...DETAILS, shippingOptions: dup });+ testing.expectEqual(null, req.shippingOption);+ testing.expectEqual(null, req.shippingType);+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, { ...DETAILS, shippingOptions: dup }, { requestShipping: true }));+ }+</script>++<script id=validation>+ const amount = (value, currency = 'USD') => ({ total: { label: 'Total', amount: { currency, value } } });++ testing.expectError('TypeError', () => new PaymentRequest([], DETAILS));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, {}));++ testing.expectError('RangeError', () => new PaymentRequest([{ supportedMethods: 'Basic-Card' }], DETAILS));+ testing.expectError('RangeError', () => new PaymentRequest([{ supportedMethods: '1pay' }], DETAILS));+ testing.expectError('RangeError', () => new PaymentRequest([{ supportedMethods: 'pay-2go' }], DETAILS));+ testing.expectError('RangeError', () => new PaymentRequest([{ supportedMethods: 'pay--go' }], DETAILS));+ testing.expectError('RangeError', () => new PaymentRequest([{ supportedMethods: 'ftp://example.com/pay' }], DETAILS));+ testing.expectError('RangeError', () => new PaymentRequest([{ supportedMethods: 'http://example.com/pay' }], DETAILS));+ testing.expectError('RangeError', () => new PaymentRequest([{ supportedMethods: 'https://user:[email protected]/pay' }], DETAILS));+ testing.expectError('RangeError', () => new PaymentRequest([...METHODS, ...METHODS], DETAILS));++ testing.expectError('RangeError', () => new PaymentRequest(METHODS, amount('1', 'US')));+ testing.expectError('RangeError', () => new PaymentRequest(METHODS, amount('1', 'U$D')));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, amount('-1')));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, amount('1.')));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, amount('.5')));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, amount('1e3')));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, amount('')));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, {+ ...DETAILS,+ displayItems: [{ label: 'x', amount: { currency: 'USD', value: 'abc' } }],+ }));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, {+ ...DETAILS,+ modifiers: [{ supportedMethods: 'https://example.com/pay', total: { label: 'x', amount: { currency: 'USD', value: '-2' } } }],+ }));+ testing.expectError('RangeError', () => new PaymentRequest(METHODS, {+ ...DETAILS,+ modifiers: [{ supportedMethods: 'not a pmi' }],+ }));+ // a modifier's total is checked before its method identifier+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, {+ ...DETAILS,+ modifiers: [{ supportedMethods: 'not a pmi', total: { label: 'x', amount: { currency: 'USD', value: '-2' } } }],+ }));++ const long = 'x'.repeat(1025);+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, { ...DETAILS, id: long }));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, { total: { label: long, amount: { currency: 'USD', value: '1' } } }));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, amount('1'.repeat(1025))));+ // the length check comes before the currency format+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, amount('1', long)));+ testing.expectError('TypeError', () => new PaymentRequest(METHODS, {+ ...DETAILS,+ displayItems: Array.from({ length: 1025 }, () => DETAILS.total),+ }));+ // an id that's too long fails before the empty method list+ testing.expectError('cannot be longer than 1024', () => new PaymentRequest([], { ...DETAILS, id: long }));+</script>++<script id=can_make_payment type=module>+ {+ const state = await testing.async();+ const result = await new PaymentRequest(METHODS, DETAILS).canMakePayment();+ const enrolled = await new PaymentRequest(METHODS, DETAILS).hasEnrolledInstrument();+ state.resolve();+ await state.done(() => {+ testing.expectEqual(false, result);+ testing.expectEqual(false, enrolled);+ });+ }+</script>++<script id=show type=module>+ {+ const state = await testing.async();+ const req = new PaymentRequest(METHODS, DETAILS);+ const errors = [];+ await req.show().catch((e) => errors.push(e.name));+ await req.show().catch((e) => errors.push(e.name));+ await req.canMakePayment().catch((e) => errors.push(e.name));+ await req.abort().catch((e) => errors.push(e.name));+ state.resolve();+ await state.done(() => {+ testing.expectEqual(['NotSupportedError', 'InvalidStateError', 'InvalidStateError', 'InvalidStateError'], errors);+ });+ }+</script>++<script id=events>+ {+ const e = new PaymentRequestUpdateEvent('shippingaddresschange', { bubbles: true });+ testing.expectTrue(e instanceof Event);+ testing.expectEqual('shippingaddresschange', e.type);+ testing.expectEqual(true, e.bubbles);+ testing.expectError('InvalidStateError', () => e.updateWith(Promise.resolve({})));+ }+ {+ const details = { foo: 1 };+ const e = new PaymentMethodChangeEvent('paymentmethodchange', { methodName: 'https://example.com/pay', methodDetails: details });+ testing.expectTrue(e instanceof PaymentRequestUpdateEvent);+ testing.expectEqual('https://example.com/pay', e.methodName);+ testing.expectEqual(details, e.methodDetails);++ const empty = new PaymentMethodChangeEvent('paymentmethodchange');+ testing.expectEqual('', empty.methodName);+ testing.expectEqual(null, empty.methodDetails);+ }+</script>diff --git a/src/browser/webapi/Event.zig b/src/browser/webapi/Event.zigindex 72d61064e..11e6ba96f 100644--- a/src/browser/webapi/Event.zig+++ b/src/browser/webapi/Event.zig@@ -107,6 +107,7 @@ pub const Type = union(enum) {toggle_event: *@import("event/ToggleEvent.zig"),task_priority_change_event: *@import("event/TaskPriorityChangeEvent.zig"),offline_audio_completion_event: *@import("webaudio/OfflineAudioCompletionEvent.zig"),+ payment_request_update_event: *@import("payment/PaymentRequestUpdateEvent.zig"),};pub const Options = struct {@@ -264,6 +265,12 @@ pub fn is(self: *Event, comptime T: type) ?*T {}return e.is(T);},+ .payment_request_update_event => |e| {+ if (T == @import("payment/PaymentRequestUpdateEvent.zig")) {+ return e;+ }+ return e.is(T);+ },}return null;}diff --git a/src/browser/webapi/EventTarget.zig b/src/browser/webapi/EventTarget.zigindex 0b8b70054..ed6712bc3 100644--- a/src/browser/webapi/EventTarget.zig+++ b/src/browser/webapi/EventTarget.zig@@ -36,6 +36,8 @@ const MessagePort = @import("MessagePort.zig");const Performance = @import("Performance.zig");const Permissions = @import("Permissions.zig");const Notification = @import("Notification.zig");+const PaymentRequest = @import("payment/PaymentRequest.zig");+const PaymentResponse = @import("payment/PaymentResponse.zig");const SharedWorker = @import("SharedWorker.zig");const ServiceWorker = @import("ServiceWorker.zig");const ServiceWorkerContainer = @import("ServiceWorkerContainer.zig");@@ -102,6 +104,8 @@ pub const Type = enum(u8) {navigation_history_entry,node,notification,+ payment_request,+ payment_response,performance,permission_status,screen,@@ -148,6 +152,8 @@ pub fn Subtype(comptime tag: Type) type {.navigation_history_entry => NavigationHistoryEntry,.node => Node,.notification => Notification,+ .payment_request => PaymentRequest,+ .payment_response => PaymentResponse,.performance => Performance,.permission_status => Permissions.PermissionStatus,.screen => Screen,@@ -420,6 +426,8 @@ pub fn format(self: *EventTarget, writer: *std.Io.Writer) !void {.idb_database => writer.writeAll("<IDBDatabase>"),.idb_transaction => writer.writeAll("<IDBTransaction>"),.notification => writer.writeAll("<Notification>"),+ .payment_request => writer.writeAll("<PaymentRequest>"),+ .payment_response => writer.writeAll("<PaymentResponse>"),.permission_status => writer.writeAll("<PermissionStatus>"),.navigation_history_entry => writer.writeAll("<NavigationHistoryEntry>"),};@@ -448,6 +456,8 @@ pub fn toString(self: *EventTarget) []const u8 {.navigation_history_entry => return "[object NavigationHistoryEntry]",.node => return "[object Node]",.notification => return "[object Notification]",+ .payment_request => return "[object PaymentRequest]",+ .payment_response => return "[object PaymentResponse]",.performance => return "[object Performance]",.permission_status => return "[object PermissionStatus]",.screen => return "[object Screen]",diff --git a/src/browser/webapi/payment/PaymentMethodChangeEvent.zig b/src/browser/webapi/payment/PaymentMethodChangeEvent.zignew file mode 100644index 000000000..b65a0d1ba--- /dev/null+++ b/src/browser/webapi/payment/PaymentMethodChangeEvent.zig@@ -0,0 +1,95 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const lp = @import("lightpanda");++const js = @import("../../js/js.zig");+const Page = @import("../../Page.zig");++const Event = @import("../Event.zig");+const PaymentRequestUpdateEvent = @import("PaymentRequestUpdateEvent.zig");++const String = lp.String;++// https://w3c.github.io/payment-request/#paymentmethodchangeevent-interface+const PaymentMethodChangeEvent = @This();++pub const Proto = PaymentRequestUpdateEvent;++_proto: *PaymentRequestUpdateEvent,+_method_name: []const u8,+_method_details: ?js.Object.Global,++const PaymentMethodChangeEventOptions = struct {+ methodDetails: ?js.Object.Global = null,+ methodName: []const u8 = "",+};++const Options = Event.inheritOptions(PaymentMethodChangeEvent, PaymentMethodChangeEventOptions);++pub fn init(typ: []const u8, opts_: ?Options, page: *Page) !*PaymentMethodChangeEvent {+ const arena = try page.getArena(.tiny, "PaymentMethodChangeEvent");+ errdefer arena.release();+ const type_string = try String.init(arena.allocator(), typ, .{});++ const opts = opts_ orelse Options{};+ const event = try page.factory.eventWithParent(+ PaymentRequestUpdateEvent,+ arena,+ type_string,+ PaymentMethodChangeEvent{+ ._proto = undefined,+ ._method_name = try arena.dupe(u8, opts.methodName),+ ._method_details = opts.methodDetails,+ },+ );++ Event.populatePrototypes(event, opts, false);+ return event;+}++pub fn deinit(self: *PaymentMethodChangeEvent, _: *Page) void {+ if (self._method_details) |d| {+ d.release();+ }+}++pub fn asEvent(self: *PaymentMethodChangeEvent) *Event {+ return self._proto.asEvent();+}++fn getMethodName(self: *const PaymentMethodChangeEvent) []const u8 {+ return self._method_name;+}++fn getMethodDetails(self: *const PaymentMethodChangeEvent) ?js.Object.Global {+ return self._method_details;+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(PaymentMethodChangeEvent);++ pub const Meta = struct {+ pub const name = "PaymentMethodChangeEvent";+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const constructor = bridge.constructor(PaymentMethodChangeEvent.init, .{});+ pub const methodName = bridge.accessor(getMethodName, null, .{});+ pub const methodDetails = bridge.accessor(getMethodDetails, null, .{});+};diff --git a/src/browser/webapi/payment/PaymentRequest.zig b/src/browser/webapi/payment/PaymentRequest.zignew file mode 100644index 000000000..323ab13da--- /dev/null+++ b/src/browser/webapi/payment/PaymentRequest.zig@@ -0,0 +1,360 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++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 EventTarget = @import("../EventTarget.zig");++const Execution = js.Execution;++// https://w3c.github.io/payment-request/#paymentrequest-interface+//+// Behaves like Chrome with no payment app installed, which sends checkout+// pages to their card-form fallback.+const PaymentRequest = @This();++pub const Proto = EventTarget;++_rc: lp.RC = .{},+_arena: *lp.Arena,+_proto: *EventTarget,+_id: []const u8,+// The spec's "interactive" state is never entered: show() closes at once.+_closed: bool = false,+_shipping_option: ?[]const u8 = null,+_shipping_type: ?ShippingType = null,++const ShippingType = enum {+ shipping,+ delivery,+ pickup,+ pub const js_enum_from_string = true;+};++const PaymentCurrencyAmount = struct {+ currency: []const u8,+ value: []const u8,+};++const PaymentItem = struct {+ amount: PaymentCurrencyAmount,+ label: []const u8,+};++const PaymentShippingOption = struct {+ amount: PaymentCurrencyAmount,+ id: []const u8,+ label: []const u8,+ selected: bool = false,+};++const PaymentMethodData = struct {+ supportedMethods: []const u8,+};++const PaymentDetailsModifier = struct {+ additionalDisplayItems: ?[]const PaymentItem = null,+ supportedMethods: []const u8,+ total: ?PaymentItem = null,+};++const PaymentDetailsInit = struct {+ displayItems: ?[]const PaymentItem = null,+ id: ?[]const u8 = null,+ modifiers: ?[]const PaymentDetailsModifier = null,+ shippingOptions: ?[]const PaymentShippingOption = null,+ total: PaymentItem,+};++const PaymentOptions = struct {+ requestShipping: bool = false,+ shippingType: ShippingType = .shipping,+};++pub fn init(+ method_data: []const PaymentMethodData,+ details: PaymentDetailsInit,+ options_: ?PaymentOptions,+ exec: *const Execution,+) !*PaymentRequest {+ // Chrome's order decides which error a multiply-invalid request throws.+ if (details.id) |id| {+ try validateLength(id, exec);+ }++ if (method_data.len == 0) {+ return exec.js.typeError("At least one payment method is required");+ }+ try validateListLength(method_data.len, exec);+ for (method_data, 0..) |md, i| {+ try validateMethod(md.supportedMethods, exec);+ for (method_data[0..i]) |prev| {+ if (std.mem.eql(u8, prev.supportedMethods, md.supportedMethods)) {+ return error.RangeError;+ }+ }+ }++ try validateTotal(details.total, exec);+ try validateItems(details.displayItems orelse &.{}, exec);++ const options = options_ orelse PaymentOptions{};+ var selected_shipping: ?[]const u8 = null;+ if (options.requestShipping) {+ const shipping_options = details.shippingOptions orelse &.{};+ try validateListLength(shipping_options.len, exec);+ for (shipping_options, 0..) |opt, i| {+ try validateItem(opt.label, opt.amount, exec);+ try validateLength(opt.id, exec);+ for (shipping_options[0..i]) |prev| {+ if (std.mem.eql(u8, prev.id, opt.id)) {+ return exec.js.typeError("Cannot have duplicate shipping option identifiers");+ }+ }+ if (opt.selected) {+ selected_shipping = opt.id;+ }+ }+ }++ const modifiers = details.modifiers orelse &.{};+ try validateListLength(modifiers.len, exec);+ for (modifiers) |modifier| {+ if (modifier.total) |total| {+ try validateTotal(total, exec);+ }+ try validateItems(modifier.additionalDisplayItems orelse &.{}, exec);+ try validateMethod(modifier.supportedMethods, exec);+ }++ const arena = try exec.getArena(.tiny, "PaymentRequest");+ errdefer arena.release();++ const id = if (details.id) |id| try arena.dupe(u8, id) else blk: {+ const uuid = try arena.alloc(u8, 36);+ @import("../../../id.zig").uuidv4(uuid);+ break :blk uuid;+ };++ return exec._factory.eventTargetWithAllocator(arena.allocator(), PaymentRequest{+ ._arena = arena,+ ._proto = undefined,+ ._id = id,+ ._shipping_option = if (selected_shipping) |s| try arena.dupe(u8, s) else null,+ ._shipping_type = if (options.requestShipping) options.shippingType else null,+ });+}++pub fn deinit(self: *PaymentRequest, page: *Page) void {+ page.removeTarget(self._proto);+ self._arena.release();+}++pub fn releaseRef(self: *PaymentRequest, page: *Page) void {+ self._rc.release(self, page);+}++pub fn acquireRef(self: *PaymentRequest) void {+ self._rc.acquire();+}++pub fn asEventTarget(self: *PaymentRequest) *EventTarget {+ return self._proto;+}++// Chrome's caps.+const max_string_length = 1024;+const max_list_length = 1024;++fn validateLength(s: []const u8, exec: *const Execution) !void {+ if (s.len > max_string_length) {+ return exec.js.typeError(std.fmt.comptimePrint("Value cannot be longer than {d} characters", .{max_string_length}));+ }+}++fn validateListLength(len: usize, exec: *const Execution) !void {+ if (len > max_list_length) {+ return exec.js.typeError(std.fmt.comptimePrint("At most {d} entries allowed", .{max_list_length}));+ }+}++// Chrome's IsValidMethodFormat, laxer than the spec: plain http is allowed on+// a loopback host.+fn validateMethod(pmi: []const u8, exec: *const Execution) !void {+ if (isStandardizedMethod(pmi)) {+ return;+ }+ const href = URL.resolve(exec.call_arena, "", pmi, .{}) catch return error.RangeError;+ if (URL.getUsername(href).len > 0 or URL.getPassword(href).len > 0) {+ return error.RangeError;+ }+ if (std.mem.startsWith(u8, href, "https:")) {+ return;+ }+ if (std.mem.startsWith(u8, href, "http:") and URL.isLoopbackHost(URL.getHostname(href))) {+ return;+ }+ return error.RangeError;+}++// [a-z]+[0-9a-z]*(-[a-z]+[0-9a-z]*)*+fn isStandardizedMethod(pmi: []const u8) bool {+ var it = std.mem.splitScalar(u8, pmi, '-');+ while (it.next()) |part| {+ if (part.len == 0 or !std.ascii.isLower(part[0])) {+ return false;+ }+ for (part) |c| {+ if (!std.ascii.isLower(c) and !std.ascii.isDigit(c)) {+ return false;+ }+ }+ }+ return true;+}++fn validateTotal(total: PaymentItem, exec: *const Execution) !void {+ try validateItem(total.label, total.amount, exec);+ if (total.amount.value[0] == '-') {+ return exec.js.typeError("Total amount value should be non-negative");+ }+}++fn validateItems(items: []const PaymentItem, exec: *const Execution) !void {+ try validateListLength(items.len, exec);+ for (items) |item| {+ try validateItem(item.label, item.amount, exec);+ }+}++// https://w3c.github.io/payment-request/#validity-checkers+fn validateItem(label: []const u8, amount: PaymentCurrencyAmount, exec: *const Execution) !void {+ try validateLength(label, exec);+ try validateLength(amount.currency, exec);+ try validateLength(amount.value, exec);++ if (amount.currency.len != 3) {+ return error.RangeError;+ }+ for (amount.currency) |c| {+ if (!std.ascii.isAlphabetic(c)) {+ return error.RangeError;+ }+ }+ if (!isValidDecimalMonetaryValue(amount.value)) {+ return exec.js.typeError("Invalid amount value");+ }+}++// -?[0-9]+(\.[0-9]+)?+fn isValidDecimalMonetaryValue(value: []const u8) bool {+ const unsigned = if (value.len > 0 and value[0] == '-') value[1..] else value;+ const dot = std.mem.indexOfScalar(u8, unsigned, '.');+ const integer = unsigned[0 .. dot orelse unsigned.len];+ const fraction: []const u8 = if (dot) |d| unsigned[d + 1 ..] else "0";+ return isDigits(integer) and isDigits(fraction);+}++fn isDigits(s: []const u8) bool {+ if (s.len == 0) {+ return false;+ }+ for (s) |c| {+ if (!std.ascii.isDigit(c)) {+ return false;+ }+ }+ return true;+}++pub fn show(self: *PaymentRequest, _: ?js.Value) !js.Promise {+ if (self._closed) {+ return error.InvalidStateError;+ }+ self._closed = true;+ return error.NotSupported;+}++// Only an interactive request can be aborted, and none ever is.+pub fn abort(_: *PaymentRequest) !js.Promise {+ return error.InvalidStateError;+}++pub fn canMakePayment(self: *PaymentRequest, exec: *const Execution) !js.Promise {+ if (self._closed) {+ return error.InvalidStateError;+ }+ return exec.js.local.?.resolvePromise(false);+}++// Dropped from the spec; Chrome still ships it.+pub fn hasEnrolledInstrument(self: *PaymentRequest, exec: *const Execution) !js.Promise {+ return self.canMakePayment(exec);+}++fn getId(self: *const PaymentRequest) []const u8 {+ return self._id;+}++fn getShippingAddress(_: *const PaymentRequest) ?js.Object {+ return null;+}++fn getShippingOption(self: *const PaymentRequest) ?[]const u8 {+ return self._shipping_option;+}++fn getShippingType(self: *const PaymentRequest) ?[]const u8 {+ const shipping_type = self._shipping_type orelse return null;+ return @tagName(shipping_type);+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(PaymentRequest);++ pub const Meta = struct {+ pub const name = "PaymentRequest";+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const constructor = bridge.constructor(PaymentRequest.init, .{});++ pub const show = bridge.function(PaymentRequest.show, .{});+ pub const abort = bridge.function(PaymentRequest.abort, .{});+ pub const canMakePayment = bridge.function(PaymentRequest.canMakePayment, .{});+ pub const hasEnrolledInstrument = bridge.function(PaymentRequest.hasEnrolledInstrument, .{});++ pub const id = bridge.accessor(getId, null, .{});+ pub const shippingAddress = bridge.accessor(getShippingAddress, null, .{});+ pub const shippingOption = bridge.accessor(getShippingOption, null, .{});+ pub const shippingType = bridge.accessor(getShippingType, null, .{});++ pub const onshippingaddresschange = EventTarget.handlerAccessor(PaymentRequest, "shippingaddresschange");+ pub const onshippingoptionchange = EventTarget.handlerAccessor(PaymentRequest, "shippingoptionchange");+ pub const onpaymentmethodchange = EventTarget.handlerAccessor(PaymentRequest, "paymentmethodchange");+};++const testing = @import("../../../testing.zig");+test "WebApi: PaymentRequest" {+ try testing.htmlRunner("payment_request.html", .{});+}diff --git a/src/browser/webapi/payment/PaymentRequestUpdateEvent.zig b/src/browser/webapi/payment/PaymentRequestUpdateEvent.zignew file mode 100644index 000000000..6a9f83584--- /dev/null+++ b/src/browser/webapi/payment/PaymentRequestUpdateEvent.zig@@ -0,0 +1,87 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const lp = @import("lightpanda");++const js = @import("../../js/js.zig");+const Page = @import("../../Page.zig");++const Event = @import("../Event.zig");++const String = lp.String;++// https://w3c.github.io/payment-request/#paymentrequestupdateevent-interface+const PaymentRequestUpdateEvent = @This();++pub const Proto = Event;++_type: Type,+_proto: *Event,++pub const Type = union(enum) {+ generic,+ payment_method_change_event: *@import("PaymentMethodChangeEvent.zig"),+};++pub const Options = Event.inheritOptions(PaymentRequestUpdateEvent, struct {});++pub fn init(typ: []const u8, opts_: ?Options, page: *Page) !*PaymentRequestUpdateEvent {+ const arena = try page.getArena(.tiny, "PaymentRequestUpdateEvent");+ errdefer arena.release();+ const type_string = try String.init(arena.allocator(), typ, .{});++ const event = try page.factory.event(+ arena,+ type_string,+ PaymentRequestUpdateEvent{+ ._type = .generic,+ ._proto = undefined,+ },+ );++ Event.populatePrototypes(event, opts_ orelse Options{}, false);+ return event;+}++pub fn is(self: *PaymentRequestUpdateEvent, comptime T: type) ?*T {+ switch (self._type) {+ .generic => return if (T == PaymentRequestUpdateEvent) self else null,+ .payment_method_change_event => |e| return if (T == @import("PaymentMethodChangeEvent.zig")) e else null,+ }+}++pub fn asEvent(self: *PaymentRequestUpdateEvent) *Event {+ return self._proto;+}++// Only a trusted event can; there's no payment UI to dispatch one.+fn updateWith(_: *PaymentRequestUpdateEvent, _: js.Value) !void {+ return error.InvalidStateError;+}++pub const JsApi = struct {+ pub const bridge = js.Bridge(PaymentRequestUpdateEvent);++ pub const Meta = struct {+ pub const name = "PaymentRequestUpdateEvent";+ pub var class_id: bridge.ClassId = undefined;+ };++ pub const constructor = bridge.constructor(PaymentRequestUpdateEvent.init, .{});+ pub const updateWith = bridge.function(PaymentRequestUpdateEvent.updateWith, .{});+};diff --git a/src/browser/webapi/payment/PaymentResponse.zig b/src/browser/webapi/payment/PaymentResponse.zignew file mode 100644index 000000000..782e3957d--- /dev/null+++ b/src/browser/webapi/payment/PaymentResponse.zig@@ -0,0 +1,38 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const js = @import("../../js/js.zig");++const EventTarget = @import("../EventTarget.zig");++// https://w3c.github.io/payment-request/#paymentresponse-interface+// Never created: show() never succeeds.+const PaymentResponse = @This();++pub const Proto = EventTarget;++_proto: *EventTarget,++pub const JsApi = struct {+ pub const bridge = js.Bridge(PaymentResponse);++ pub const Meta = struct {+ pub const name = "PaymentResponse";+ pub var class_id: bridge.ClassId = undefined;+ };+};