Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

feat(gamepad): expose native interfaces and event payloads

ldm0859b14061958
diff --git a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
index 0b3c3b3d5..7cf2431fc 100644
--- a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
+++ b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
@@ -114,6 +114,7 @@ pub(in crate::context_bootstrap) fn build_constructor_template<'s>(
build_value_event_template(scope, ValueEventKind::Transition)
}
ConstructorKind::BlobEvent => build_value_event_template(scope, ValueEventKind::Blob),
+ ConstructorKind::GamepadEvent => build_value_event_template(scope, ValueEventKind::Gamepad),
ConstructorKind::WebGLContextEvent => {
build_value_event_template(scope, ValueEventKind::WebGlContext)
}
diff --git a/moli-renderer-v8/src/context_bootstrap/events/value.rs b/moli-renderer-v8/src/context_bootstrap/events/value.rs
index 560a4075c..1412d20d6 100644
--- a/moli-renderer-v8/src/context_bootstrap/events/value.rs
+++ b/moli-renderer-v8/src/context_bootstrap/events/value.rs
@@ -17,6 +17,7 @@ const BLOB_SLOT: &str = "__moliValueEventBlob";
const STATUS_MESSAGE_SLOT: &str = "__moliWebGlContextEventStatusMessage";
const TIMECODE_SLOT: &str = "__moliValueEventTimecode";
const TOOL_NAME_SLOT: &str = "__moliToolEventName";
+const GAMEPAD_SLOT: &str = "__moliValueEventGamepad";
#[derive(Clone, Copy)]
pub(in crate::context_bootstrap) enum ValueEventKind {
@@ -26,6 +27,7 @@ pub(in crate::context_bootstrap) enum ValueEventKind {
WebGlContext,
ToolActivated,
ToolCancel,
+ Gamepad,
}
impl ValueEventKind {
@@ -37,6 +39,7 @@ impl ValueEventKind {
Self::WebGlContext => "WebGLContextEvent",
Self::ToolActivated => "ToolActivatedEvent",
Self::ToolCancel => "ToolCancelEvent",
+ Self::Gamepad => "GamepadEvent",
}
}
@@ -162,6 +165,45 @@ struct TransitionEventInit<'s> {
pseudo_element: v8::Local<'s, v8::String>,
}
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::GamepadEvent, enumerable, receiver)]
+struct GamepadEventPrototypeDeclaration {
+ #[webapi(accessor_property, getter = payload_getter, data = v8str(scope, GAMEPAD_SLOT))]
+ gamepad: (),
+}
+
+#[derive(webidl::WebIdlDictionary)]
+#[webidl(prefix = "GamepadEventInit")]
+struct GamepadEventInit<'s> {
+ #[webidl(default = false)]
+ bubbles: bool,
+ #[webidl(default = false)]
+ cancelable: bool,
+ #[webidl(default = false)]
+ composed: bool,
+ #[webidl(with = gamepad_member)]
+ gamepad: Option<v8::Local<'s, v8::Object>>,
+}
+
+fn gamepad_member<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ object: v8::Local<'s, v8::Object>,
+ name: &'static str,
+) -> Result<Option<v8::Local<'s, v8::Object>>, webidl::WebIdlError> {
+ let context = webidl::Context::member("GamepadEventInit", name);
+ let value = webidl::property_result(scope, object, name, context)?
+ .unwrap_or_else(|| v8::undefined(scope).into());
+ if value.is_null_or_undefined() {
+ return Ok(None);
+ }
+ let gamepad = v8::Local::<v8::Object>::try_from(value)
+ .map_err(|_| webidl::WebIdlError::cannot_convert(context, "Gamepad"))?;
+ if !web_api_interfaces::Gamepad::is_instance(scope, gamepad) {
+ return Err(webidl::WebIdlError::cannot_convert(context, "Gamepad"));
+ }
+ Ok(Some(gamepad))
+}
+
#[derive(webidl::WebIdlDictionary)]
#[webidl(prefix = "BlobEventInit")]
struct BlobEventInit<'s> {
@@ -217,6 +259,9 @@ pub(in crate::context_bootstrap) fn install_value_event_template_bindings<'s>(
"ToolCancelEvent" => {
ToolCancelEventPrototypeDeclaration::initialize_prototype_template(scope, prototype)
}
+ "GamepadEvent" => {
+ GamepadEventPrototypeDeclaration::initialize_prototype_template(scope, prototype)
+ }
_ => {}
}
}
@@ -254,6 +299,7 @@ fn value_event_constructor<'s>(
Some(3) => ValueEventKind::WebGlContext,
Some(4) => ValueEventKind::ToolActivated,
Some(5) => ValueEventKind::ToolCancel,
+ Some(6) => ValueEventKind::Gamepad,
_ => return,
};
if !args.is_construct_call() {
@@ -339,6 +385,16 @@ fn value_event_constructor<'s>(
set_event_private_value(scope, state, TOOL_NAME_SLOT, parsed.tool_name.into());
(parsed.bubbles, parsed.cancelable, parsed.composed)
}
+ ValueEventKind::Gamepad => {
+ let parsed =
+ webidl::parse_dictionary_object::<GamepadEventInit>(scope, dictionary)?;
+ let gamepad = parsed
+ .gamepad
+ .map(Into::into)
+ .unwrap_or_else(|| v8::null(scope).into());
+ set_event_private_value(scope, state, GAMEPAD_SLOT, gamepad);
+ (parsed.bubbles, parsed.cancelable, parsed.composed)
+ }
};
initialize_event_object_with_type(scope, state, event_type, bubbles, cancelable);
define_event_property(
diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/gamepad.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/gamepad.rs
index d6f89a5fa..2e0d14f78 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/gamepad.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/gamepad.rs
@@ -1,6 +1,89 @@
+//! Device interface shells and native Gamepad polling without a device backend.
+//!
+//! Polling returns no devices. Do not create fake device snapshots or actuator
+//! results; Event payloads are implemented by the shared value-event bindings.
+
use super::super::context_host_ptr_from_global_bridge;
use super::navigator::navigator_receiver_branded;
-use crate::{util::throw_type_error, webidl};
+use crate::{util::throw_type_error, web_api_interfaces, webidl};
+use moli_webapi_declare::WebApiFunctionTemplate;
+
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::Gamepad, enumerable, receiver)]
+struct GamepadPrototypeDeclaration {
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ id: (),
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ index: (),
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ connected: (),
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ timestamp: (),
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ mapping: (),
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ axes: (),
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ buttons: (),
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ touches: (),
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ vibration_actuator: (),
+}
+
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::GamepadButton, enumerable, receiver)]
+struct GamepadButtonPrototypeDeclaration {
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ pressed: (),
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ touched: (),
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ value: (),
+}
+
+#[derive(WebApiFunctionTemplate)]
+#[webapi(interface = web_api_interfaces::GamepadHapticActuator, enumerable, receiver)]
+struct GamepadHapticActuatorPrototypeDeclaration {
+ #[webapi(accessor_property, getter = device_backend_unavailable)]
+ effects: (),
+ #[webapi(method, returns_promise, length = 1, callback = device_backend_unavailable)]
+ play_effect: (),
+ #[webapi(method, returns_promise, length = 0, callback = device_backend_unavailable)]
+ reset: (),
+}
+
+pub(super) fn install<'s>(
+ scope: &mut v8::PinScope<'s, '_, ()>,
+ template: v8::Local<'s, v8::FunctionTemplate>,
+ interface_name: &str,
+) {
+ let prototype = template.prototype_template(scope);
+ match interface_name {
+ "Gamepad" => GamepadPrototypeDeclaration::initialize_prototype_template(scope, prototype),
+ "GamepadButton" => {
+ GamepadButtonPrototypeDeclaration::initialize_prototype_template(scope, prototype)
+ }
+ "GamepadHapticActuator" => {
+ GamepadHapticActuatorPrototypeDeclaration::initialize_prototype_template(
+ scope, prototype,
+ )
+ }
+ _ => {}
+ }
+}
+
+fn device_backend_unavailable<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ _args: v8::FunctionCallbackArguments<'s>,
+ _rv: v8::ReturnValue<'s>,
+) {
+ webidl::throw_dom_exception(
+ scope,
+ "NotSupportedError",
+ "Gamepad device and haptic backends are not implemented.",
+ );
+}
pub(super) fn navigator_get_gamepads_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
diff --git a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
index 43348dce6..0f57c2d9a 100644
--- a/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
+++ b/moli-renderer-v8/src/context_bootstrap/navigator_runtime/navigator.rs
@@ -893,6 +893,7 @@ pub(in crate::context_bootstrap) fn install_navigator_template_bindings<'s>(
install_clipboard_template_bindings(scope, template, interface_name);
install_geolocation_template_bindings(scope, template, interface_name);
install_navigator_collection_template_bindings(scope, template, interface_name);
+ super::gamepad::install(scope, template, interface_name);
install_media_capabilities_template_bindings(scope, template, interface_name);
let prototype = template.prototype_template(scope);
match interface_name {
diff --git a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
index fcef1b21c..bd637dcac 100644
--- a/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
+++ b/moli-renderer-v8/src/context_bootstrap/specs/registry.rs
@@ -328,6 +328,22 @@ const CONSTRUCTOR_SPECS_BEFORE_STREAMS: &[ConstructorSpec] = &[
interface: web_api_interfaces::TouchEvent::DESCRIPTOR,
kind: ConstructorKind::TouchEvent,
},
+ ConstructorSpec {
+ interface: web_api_interfaces::GamepadEvent::DESCRIPTOR,
+ kind: ConstructorKind::GamepadEvent,
+ },
+ ConstructorSpec {
+ interface: web_api_interfaces::Gamepad::DESCRIPTOR,
+ kind: ConstructorKind::Illegal,
+ },
+ ConstructorSpec {
+ interface: web_api_interfaces::GamepadButton::DESCRIPTOR,
+ kind: ConstructorKind::Illegal,
+ },
+ ConstructorSpec {
+ interface: web_api_interfaces::GamepadHapticActuator::DESCRIPTOR,
+ kind: ConstructorKind::Illegal,
+ },
ConstructorSpec {
interface: web_api_interfaces::MessageEvent::DESCRIPTOR,
kind: ConstructorKind::MessageEvent,
diff --git a/moli-renderer-v8/src/context_bootstrap/specs/types.rs b/moli-renderer-v8/src/context_bootstrap/specs/types.rs
index 5e929d3dc..38c42fddc 100644
--- a/moli-renderer-v8/src/context_bootstrap/specs/types.rs
+++ b/moli-renderer-v8/src/context_bootstrap/specs/types.rs
@@ -13,6 +13,7 @@ pub(in crate::context_bootstrap) enum ConstructorKind {
WebGLContextEvent,
ToolActivatedEvent,
ToolCancelEvent,
+ GamepadEvent,
UiEvent,
FocusEvent,
CompositionEvent,
diff --git a/moli-renderer-v8/src/script_vm/tests/gamepad_interfaces.js b/moli-renderer-v8/src/script_vm/tests/gamepad_interfaces.js
new file mode 100644
index 000000000..d24e6f92c
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/gamepad_interfaces.js
@@ -0,0 +1,134 @@
+(async () => {
+ const rows = [];
+ const assert = (condition, message) => { if (!condition) throw Error(message); };
+ const check = async (name, callback) => {
+ try { await callback(); rows.push({name, pass: true}); }
+ catch (error) { rows.push({name, pass: false, message: String(error)}); }
+ };
+ const thrown = callback => {
+ try { callback(); } catch (error) { return error; }
+ throw Error('expected exception');
+ };
+ const realms = [['main', window], ['child', document.getElementById('child').contentWindow]];
+ for (const [label, w] of realms) {
+ for (const [name, fields] of [
+ ['Gamepad', ['id', 'index', 'connected', 'timestamp', 'mapping', 'axes', 'buttons', 'vibrationActuator']],
+ ['GamepadButton', ['pressed', 'touched', 'value']],
+ ['GamepadHapticActuator', ['effects']]
+ ]) {
+ await check(label + '/' + name + '/interface', () => {
+ const C = w[name], descriptor = Object.getOwnPropertyDescriptor(w, name);
+ assert(typeof C === 'function' && C.name === name && C.length === 0, 'interface object');
+ assert(descriptor.writable && descriptor.configurable && !descriptor.enumerable, 'global descriptor');
+ assert(Object.getPrototypeOf(C) === w.Function.prototype && Object.getPrototypeOf(C.prototype) === w.Object.prototype, 'ordinary interface inheritance');
+ assert(C.prototype.constructor === C && Object.prototype.toString.call(C.prototype) === '[object ' + name + ']', 'prototype identity');
+ assert(thrown(() => C()) instanceof w.TypeError && thrown(() => new C()) instanceof w.TypeError, 'not author constructible');
+ });
+ await check(label + '/' + name + '/readonly getters and native receivers', () => {
+ let traps = 0;
+ const trap = () => { traps++; throw Error('author trap'); }, revoked = Proxy.revocable({}, {}); revoked.revoke();
+ for (const field of fields) {
+ const descriptor = Object.getOwnPropertyDescriptor(w[name].prototype, field), getter = descriptor.get;
+ assert(descriptor.enumerable && descriptor.configurable && !descriptor.set && getter.name === 'get ' + field && getter.length === 0, 'readonly shared ' + field);
+ for (const receiver of [null, undefined, {}, w[name].prototype, Object.create(w[name].prototype), new Proxy({}, {get: trap, getPrototypeOf: trap}), revoked.proxy]) {
+ assert(thrown(() => getter.call(receiver)) instanceof w.TypeError, 'native receiver required for ' + field);
+ }
+ }
+ assert(traps === 0, 'author traps are not consulted for branding');
+ });
+ }
+ for (const name of ['playEffect', 'reset']) {
+ await check(label + '/GamepadHapticActuator/' + name + '/rejected Promise receivers', async () => {
+ const descriptor = Object.getOwnPropertyDescriptor(w.GamepadHapticActuator.prototype, name), method = descriptor.value;
+ assert(descriptor.enumerable && descriptor.configurable && descriptor.writable && method.name === name, 'method descriptor');
+ if (name === 'reset') assert(method.length === 0, 'reset arity');
+ let conversions = 0, traps = 0;
+ const trap = () => { traps++; throw Error('trap'); }, value = {toString() { conversions++; throw Error('conversion'); }};
+ const params = new Proxy({}, {get() { conversions++; throw Error('dictionary conversion'); }});
+ const revoked = Proxy.revocable({}, {}); revoked.revoke();
+ for (const receiver of [null, {}, w.GamepadHapticActuator.prototype, new Proxy({}, {get: trap}), revoked.proxy]) {
+ const promise = method.call(receiver, value, params);
+ assert(promise instanceof w.Promise, 'brand failure returns callee Promise');
+ let error; try { await promise; } catch (failure) { error = failure; }
+ assert(error instanceof w.TypeError, 'callee realm TypeError rejection');
+ }
+ assert(conversions === 0 && traps === 0, 'receiver before author conversion');
+ });
+ }
+ await check(label + '/GamepadEvent/interface and defaults', () => {
+ const C = w.GamepadEvent, descriptor = Object.getOwnPropertyDescriptor(w, 'GamepadEvent');
+ assert(typeof C === 'function' && C.name === 'GamepadEvent' && C.length === 1 && descriptor.writable && descriptor.configurable && !descriptor.enumerable, 'event constructor');
+ assert(Object.getPrototypeOf(C) === w.Event && Object.getPrototypeOf(C.prototype) === w.Event.prototype, 'Event inheritance');
+ assert(thrown(() => C('test')) instanceof w.TypeError && thrown(() => new C()) instanceof w.TypeError, 'requires new and type');
+ for (const init of [undefined, null, {}, {gamepad: null}, {gamepad: undefined}]) {
+ const event = new C('test', init);
+ assert(event instanceof C && event instanceof w.Event && event.gamepad === null && event.gamepad === event.gamepad, 'nullable default and identity');
+ assert(event.type === 'test' && !event.bubbles && !event.cancelable && !event.composed && !event.isTrusted, 'base event defaults');
+ assert(!Object.hasOwn(event, 'gamepad') && Reflect.set(event, 'gamepad', {}) === false && event.gamepad === null, 'readonly private payload');
+ }
+ });
+ await check(label + '/GamepadEvent/dictionary and payload validation', () => {
+ const C = w.GamepadEvent;
+ for (const init of [1, true, 'options', Symbol()]) assert(thrown(() => new C('test', init)) instanceof w.TypeError, 'dictionary must be an object');
+ for (const gamepad of [{}, Object.create(w.Gamepad.prototype), new Proxy({}, {}), 1, 'device', false, Symbol()]) {
+ assert(thrown(() => new C('test', {gamepad})) instanceof w.TypeError, 'nullable native Gamepad required');
+ }
+ let traps = 0;
+ const proxy = new Proxy({}, {get() { traps++; throw Error('trap'); }, getPrototypeOf() { traps++; throw Error('trap'); }});
+ assert(thrown(() => new C('test', {gamepad: proxy})) instanceof w.TypeError && traps === 0, 'payload branding avoids author traps');
+ const revoked = Proxy.revocable({}, {}); revoked.revoke();
+ assert(thrown(() => new C('test', {gamepad: revoked.proxy})) instanceof w.TypeError, 'revoked proxy rejected');
+ const inherited = Object.create({bubbles: true, gamepad: null});
+ const event = new C('test', inherited); assert(event.bubbles && event.gamepad === null, 'inherited dictionary members');
+ });
+ await check(label + '/GamepadEvent/conversion order and exception identity', () => {
+ const order = [], init = Object.create(null), sentinel = {};
+ const type = {toString() { order.push('type'); return 'test'; }};
+ for (const [key, value] of [['bubbles', true], ['cancelable', true], ['composed', true], ['gamepad', null]]) Object.defineProperty(init, key, {get() { order.push(key); return value; }});
+ const event = new w.GamepadEvent(type, init);
+ assert(order.join() === 'type,bubbles,cancelable,composed,gamepad' && event.bubbles && event.cancelable && event.composed, 'type before inherited and derived members');
+ assert(thrown(() => new w.GamepadEvent('test', {get gamepad() { throw sentinel; }})) === sentinel, 'preserve payload getter exception');
+ let reads = 0;
+ assert(thrown(() => new w.GamepadEvent(Symbol(), new Proxy({}, {get() { reads++; throw sentinel; }}))) instanceof w.TypeError && reads === 0, 'type failure precedes dictionary read');
+ assert(thrown(() => new w.GamepadEvent({toString() { throw sentinel; }}, init)) === sentinel, 'preserve type conversion exception');
+ const lone = new w.GamepadEvent('\ud800'); assert(lone.type.charCodeAt(0) === 0xd800, 'DOMString retains lone surrogate');
+ });
+ await check(label + '/GamepadEvent/getter brands and cross-realm calls', () => {
+ const getter = Object.getOwnPropertyDescriptor(w.GamepadEvent.prototype, 'gamepad').get;
+ assert(getter.name === 'get gamepad' && getter.length === 0, 'getter name and arity');
+ const event = new w.GamepadEvent('test'), foreign = new window.GamepadEvent('foreign');
+ assert(getter.call(foreign) === null, 'foreign genuine event accepted');
+ let traps = 0; const trap = () => { traps++; throw Error('trap'); }, revoked = Proxy.revocable(event, {}); revoked.revoke();
+ for (const receiver of [null, {}, new w.Event('test'), w.GamepadEvent.prototype, Object.create(event), new Proxy(event, {get: trap, getPrototypeOf: trap}), revoked.proxy]) assert(thrown(() => getter.call(receiver)) instanceof w.TypeError, 'callee realm receiver error');
+ assert(traps === 0, 'brand check does not unwrap author Proxy');
+ Object.setPrototypeOf(event, null); assert(getter.call(event) === null, 'native identity survives prototype mutation');
+ class Sub extends w.GamepadEvent {};
+ const sub = new Sub('test'); assert(sub instanceof Sub && sub instanceof w.GamepadEvent && sub.gamepad === null, 'new.target prototype');
+ });
+ await check(label + '/GamepadEvent/EventTarget and Window dispatch', () => {
+ const event = new w.GamepadEvent('gamepadconnected', {cancelable: true}), target = new w.EventTarget();
+ let calls = 0;
+ const listener = value => { assert(value === event && value.target === target && value.gamepad === null, 'dispatch retains event payload'); calls++; value.preventDefault(); };
+ target.addEventListener('gamepadconnected', listener);
+ assert(target.dispatchEvent(event) === false && calls === 1, 'native Event cancellation');
+ target.removeEventListener('gamepadconnected', listener);
+ const windowEvent = new w.GamepadEvent('gamepaddisconnected');
+ const handler = function(value) { assert(this === w && value === windowEvent && value.gamepad === null, 'Window listener receiver and event'); calls++; };
+ w.addEventListener('gamepaddisconnected', handler);
+ try { assert(w.dispatchEvent(windowEvent), 'Window dispatch'); } finally { w.removeEventListener('gamepaddisconnected', handler); }
+ assert(calls === 2, 'one Window handler invocation');
+ event.initEvent('reused', false, false); assert(event.type === 'reused' && event.gamepad === null, 'base reinitialization retains subclass payload');
+ });
+ await check(label + '/Navigator/polling snapshots and receivers', () => {
+ const method = w.Navigator.prototype.getGamepads, first = method.call(w.navigator), second = method.call(w.navigator);
+ assert(method.name === 'getGamepads' && method.length === 0 && Array.isArray(first) && first !== second, 'fresh Array snapshots');
+ assert(first.every(value => value === null), 'no hardware in the control environment');
+ first.push('author mutation'); assert(!method.call(w.navigator).includes('author mutation'), 'snapshot mutation does not alter polling state');
+ let traps = 0; const trap = () => { traps++; throw Error('trap'); }, revoked = Proxy.revocable(w.navigator, {}); revoked.revoke();
+ for (const receiver of [null, {}, w.Navigator.prototype, Object.create(w.navigator), new Proxy(w.navigator, {get: trap, getPrototypeOf: trap}), revoked.proxy]) assert(thrown(() => method.call(receiver)) instanceof w.TypeError, 'native Navigator receiver');
+ assert(traps === 0, 'polling brand does not execute author traps');
+ });
+ }
+ globalThis.__nodeReplacementResults = {rows, passed: rows.filter(row => row.pass).length, total: rows.length, failures: rows.filter(row => !row.pass)};
+ return rows.every(row => row.pass);
+})()
diff --git a/moli-renderer-v8/src/script_vm/tests/gamepad_interfaces.rs b/moli-renderer-v8/src/script_vm/tests/gamepad_interfaces.rs
new file mode 100644
index 000000000..7ede6f72f
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/gamepad_interfaces.rs
@@ -0,0 +1,106 @@
+use super::*;
+
+#[test]
+fn gamepad_interfaces_use_native_brands_and_shared_event_payloads() {
+ let mut vm = new_storage_page_task_executor_test_vm("https://gamepad-interfaces.test/");
+ vm.eval("document.body.innerHTML = '<iframe id=child></iframe>'")
+ .unwrap();
+ vm.eval(&format!("({}).then(value => globalThis.__gamepadDone = value, error => globalThis.__gamepadDone = String(error));", include_str!("gamepad_interfaces.js"))).unwrap();
+ assert_eq!(
+ vm.eval_after_selected_page_tasks("JSON.stringify(__nodeReplacementResults.failures)")
+ .unwrap(),
+ "[]"
+ );
+ assert_eq!(vm.eval("__nodeReplacementResults.total").unwrap(), "28");
+ assert_eq!(vm.eval("__gamepadDone").unwrap(), "true");
+}
+
+#[test]
+fn gamepad_events_preserve_native_payload_identity_and_registered_proxy_brands() {
+ let mut vm = new_storage_page_task_executor_test_vm("https://gamepad-payload.test/");
+ vm.eval("document.body.innerHTML = '<iframe id=child></iframe>'")
+ .unwrap();
+ let context_ptr = &vm.page_default_context as *const _;
+ vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| {
+ let global = scope.get_current_context().global(scope);
+ // Native identity fixtures only; these are not devices published by
+ // navigator.getGamepads and contain no fabricated hardware snapshots.
+ for (name, interface) in [
+ ("nativeGamepad", "Gamepad"),
+ ("nativeActuator", "GamepadHapticActuator"),
+ ] {
+ let prototype =
+ crate::context_bootstrap::ensure_intrinsic_interface_prototype(scope, interface)?;
+ let object = v8::Object::new(scope);
+ assert_eq!(object.set_prototype(scope, prototype.into()), Some(true));
+ moli_webapi_declare::initialize_web_api_object(scope, object, interface).unwrap();
+ assert_eq!(
+ global.create_data_property(
+ scope,
+ crate::util::v8str(scope, name).into(),
+ object.into()
+ ),
+ Some(true)
+ );
+ if interface == "Gamepad" {
+ let handler = crate::util::new_null_prototype_object(scope);
+ let proxy = v8::Proxy::new(scope, object, handler).unwrap();
+ moli_webapi_declare::register_web_api_proxy(scope, proxy).unwrap();
+ assert!(crate::web_api_interfaces::Gamepad::is_instance(
+ scope,
+ proxy.into()
+ ));
+ assert_eq!(
+ global.create_data_property(
+ scope,
+ crate::util::v8str(scope, "nativeGamepadProxy").into(),
+ proxy.into()
+ ),
+ Some(true)
+ );
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ vm.eval(r#"(async () => {
+ const assert = (ok, message) => { if (!ok) throw Error(message); };
+ const foreign = document.getElementById('child').contentWindow;
+ const getter = Object.getOwnPropertyDescriptor(foreign.GamepadEvent.prototype, 'gamepad').get;
+ for (const gamepad of [nativeGamepad, nativeGamepadProxy]) {
+ let reads = 0;
+ Object.defineProperty(gamepad, 'id', {configurable: true, get() { reads++; throw Error('author lookup'); }});
+ const event = new foreign.GamepadEvent('gamepadconnected', {gamepad});
+ assert(event.gamepad === gamepad && getter.call(event) === gamepad && reads === 0, 'native payload is retained by identity without public field lookup');
+ const receiver = new EventTarget(); let observed;
+ receiver.addEventListener('gamepadconnected', value => { observed = getter.call(value); });
+ receiver.dispatchEvent(event); assert(observed === gamepad, 'cross-realm dispatch keeps payload');
+ event.initEvent('reused', false, false); assert(getter.call(event) === gamepad, 'initEvent retains the subclass payload');
+ let traps = 0; const trap = () => { traps++; throw Error('trap'); };
+ for (const forged of [Object.create(gamepad), new Proxy(gamepad, {get: trap, getPrototypeOf: trap})]) {
+ let error; try { new foreign.GamepadEvent('test', {gamepad: forged}); } catch (value) { error = value; }
+ assert(error instanceof foreign.TypeError, 'author objects do not acquire the native payload brand');
+ }
+ assert(traps === 0, 'payload validation does not execute author traps');
+ delete gamepad.id;
+ }
+ Object.setPrototypeOf(nativeGamepad, null);
+ assert(new GamepadEvent('test', {gamepad: nativeGamepad}).gamepad === nativeGamepad, 'native payload brand survives prototype removal');
+ nativeActuator.__moliGamepadEffects = ['dual-rumble'];
+ for (const name of ['playEffect','reset']) {
+ const promise = foreign.GamepadHapticActuator.prototype[name].call(nativeActuator, 'dual-rumble', {});
+ assert(promise instanceof foreign.Promise, 'unsupported operation returns callee Promise');
+ let error; try { await promise; } catch (value) { error = value; }
+ assert(error instanceof foreign.DOMException && error.name === 'NotSupportedError', 'no fabricated haptic success');
+ }
+ const effects = Object.getOwnPropertyDescriptor(GamepadHapticActuator.prototype, 'effects').get;
+ let error; try { effects.call(nativeActuator); } catch (value) { error = value; }
+ assert(error instanceof DOMException && error.name === 'NotSupportedError', 'public shadow cannot fabricate a hardware capability list');
+ globalThis.__gamepadNativeDone = true;
+ })().catch(error => globalThis.__gamepadNativeDone = String(error))"#).unwrap();
+ assert_eq!(
+ vm.eval_after_selected_page_tasks("__gamepadNativeDone")
+ .unwrap(),
+ "true"
+ );
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index 3c9a79968..45ab7b1af 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -2140,6 +2140,9 @@ mod canvas_transform_snapshots;
mod canvas_webgl;
mod child_dynamic_inline_scripts;
mod device_events;
+
+mod gamepad_interfaces;
+
mod dom_elements;
mod dom_exception_proxy_identity;
mod dom_xhr;
diff --git a/moli-renderer-v8/src/web_api_interfaces.rs b/moli-renderer-v8/src/web_api_interfaces.rs
index 7d157729e..e2ab3a2f1 100644
--- a/moli-renderer-v8/src/web_api_interfaces.rs
+++ b/moli-renderer-v8/src/web_api_interfaces.rs
@@ -180,6 +180,10 @@ interfaces! {
GeolocationCoordinates;
GeolocationPosition;
GeolocationPositionError;
+ Gamepad;
+ GamepadButton;
+ GamepadEvent: Event;
+ GamepadHapticActuator;
HTMLAllCollection;
HTMLAnchorElement: HTMLElement;
HTMLAreaElement: HTMLElement;