dommy 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. checksums.yaml +4 -4
  2. data/lib/dommy/backend.rb +16 -15
  3. data/lib/dommy/blob.rb +17 -0
  4. data/lib/dommy/bridge/values.rb +29 -2
  5. data/lib/dommy/bridge/wire_tags.rb +8 -4
  6. data/lib/dommy/browser.rb +324 -49
  7. data/lib/dommy/character_data.rb +20 -27
  8. data/lib/dommy/class_list.rb +24 -9
  9. data/lib/dommy/cookie_jar.rb +408 -0
  10. data/lib/dommy/cookie_store.rb +104 -49
  11. data/lib/dommy/css.rb +34 -8
  12. data/lib/dommy/custom_elements.rb +362 -114
  13. data/lib/dommy/data_transfer.rb +22 -2
  14. data/lib/dommy/document.rb +1071 -200
  15. data/lib/dommy/dom_exception.rb +6 -0
  16. data/lib/dommy/dom_parser.rb +46 -14
  17. data/lib/dommy/dom_string_list.rb +36 -0
  18. data/lib/dommy/element.rb +217 -102
  19. data/lib/dommy/element_internals.rb +215 -0
  20. data/lib/dommy/encodings.rb +10 -0
  21. data/lib/dommy/event.rb +378 -122
  22. data/lib/dommy/event_source.rb +4 -30
  23. data/lib/dommy/file_reader.rb +5 -29
  24. data/lib/dommy/form_data.rb +40 -6
  25. data/lib/dommy/form_entry_list.rb +106 -137
  26. data/lib/dommy/fragment.rb +11 -10
  27. data/lib/dommy/history.rb +247 -90
  28. data/lib/dommy/html_canvas_element.rb +15 -35
  29. data/lib/dommy/html_collection.rb +49 -30
  30. data/lib/dommy/html_elements/base.rb +111 -69
  31. data/lib/dommy/html_elements/embedded.rb +349 -105
  32. data/lib/dommy/html_elements/forms/form.rb +407 -368
  33. data/lib/dommy/html_elements/forms/input.rb +333 -174
  34. data/lib/dommy/html_elements/forms/select.rb +90 -74
  35. data/lib/dommy/html_elements/interactive.rb +274 -64
  36. data/lib/dommy/html_elements/media.rb +71 -30
  37. data/lib/dommy/html_elements/metadata.rb +215 -71
  38. data/lib/dommy/html_elements/miscellaneous.rb +58 -14
  39. data/lib/dommy/html_elements/tables.rb +7 -9
  40. data/lib/dommy/html_elements.rb +23 -1
  41. data/lib/dommy/hyperlink_utils.rb +15 -4
  42. data/lib/dommy/interaction/drag_and_drop.rb +187 -0
  43. data/lib/dommy/interaction/event_synthesis.rb +182 -24
  44. data/lib/dommy/interaction/field_interactor.rb +17 -5
  45. data/lib/dommy/interaction/form_submission.rb +10 -4
  46. data/lib/dommy/interaction/key_sender.rb +101 -16
  47. data/lib/dommy/interaction.rb +1 -0
  48. data/lib/dommy/internal/accessibility_tree.rb +15 -3
  49. data/lib/dommy/internal/accessible_description.rb +1 -1
  50. data/lib/dommy/internal/accessible_name.rb +10 -17
  51. data/lib/dommy/internal/aria_role.rb +1 -1
  52. data/lib/dommy/internal/autofill.rb +2 -2
  53. data/lib/dommy/internal/backend_prefilter.rb +1 -5
  54. data/lib/dommy/internal/ce_reactions.rb +285 -0
  55. data/lib/dommy/internal/ce_reactions_table.rb +296 -0
  56. data/lib/dommy/internal/child_list.rb +7 -43
  57. data/lib/dommy/internal/child_navigable.rb +155 -0
  58. data/lib/dommy/internal/child_node.rb +44 -41
  59. data/lib/dommy/internal/close_watcher_manager.rb +238 -0
  60. data/lib/dommy/internal/complex_match.rb +3 -1
  61. data/lib/dommy/internal/constraint_validation.rb +130 -0
  62. data/lib/dommy/internal/css/ancestor_filter.rb +107 -0
  63. data/lib/dommy/internal/css/cascade.rb +7 -7
  64. data/lib/dommy/internal/css/cascaded_declarations.rb +4 -1
  65. data/lib/dommy/internal/css/computed_style_builder.rb +9 -3
  66. data/lib/dommy/internal/css/custom_properties.rb +41 -29
  67. data/lib/dommy/internal/css/parser.rb +0 -22
  68. data/lib/dommy/internal/css/renderability.rb +6 -0
  69. data/lib/dommy/internal/css/rule_index.rb +149 -98
  70. data/lib/dommy/internal/css/rule_index_inputs.rb +135 -0
  71. data/lib/dommy/internal/css/selector_dependencies.rb +8 -2
  72. data/lib/dommy/internal/css/style_cache.rb +7 -4
  73. data/lib/dommy/internal/css/ua_stylesheet.rb +34 -0
  74. data/lib/dommy/internal/declarative_shadow_roots.rb +182 -0
  75. data/lib/dommy/internal/document_generations.rb +55 -2
  76. data/lib/dommy/internal/document_interaction_state.rb +293 -9
  77. data/lib/dommy/internal/dom_matching.rb +2 -2
  78. data/lib/dommy/internal/element_aria.rb +25 -19
  79. data/lib/dommy/internal/element_popover.rb +226 -25
  80. data/lib/dommy/internal/element_shadow.rb +97 -26
  81. data/lib/dommy/internal/element_state.rb +98 -5
  82. data/lib/dommy/internal/element_top_layer.rb +15 -1
  83. data/lib/dommy/internal/enumerated_keyword_sets.rb +40 -0
  84. data/lib/dommy/internal/event_handler_tables.rb +241 -0
  85. data/lib/dommy/internal/event_handlers.rb +149 -0
  86. data/lib/dommy/internal/exception_report.rb +1 -1
  87. data/lib/dommy/internal/focusability.rb +267 -0
  88. data/lib/dommy/internal/form_associated_custom_elements.rb +127 -0
  89. data/lib/dommy/internal/html_or_svg_or_mathml_element.rb +34 -23
  90. data/lib/dommy/internal/html_serialization.rb +292 -0
  91. data/lib/dommy/internal/idl_reflection.rb +202 -0
  92. data/lib/dommy/internal/idl_reflection_table.rb +589 -0
  93. data/lib/dommy/internal/infra.rb +9 -0
  94. data/lib/dommy/internal/input_type.rb +76 -18
  95. data/lib/dommy/internal/insertion_point.rb +27 -3
  96. data/lib/dommy/internal/js_number.rb +60 -0
  97. data/lib/dommy/internal/light_dismiss.rb +178 -0
  98. data/lib/dommy/internal/mime_type.rb +8 -0
  99. data/lib/dommy/internal/mutation_coordinator.rb +94 -62
  100. data/lib/dommy/internal/node_adopter.rb +52 -4
  101. data/lib/dommy/internal/node_factory.rb +111 -7
  102. data/lib/dommy/internal/node_identity.rb +1 -1
  103. data/lib/dommy/internal/node_traversal.rb +22 -4
  104. data/lib/dommy/internal/node_wrapper_cache.rb +6 -38
  105. data/lib/dommy/internal/observer_options.rb +24 -14
  106. data/lib/dommy/internal/origin.rb +86 -0
  107. data/lib/dommy/internal/parent_node.rb +10 -8
  108. data/lib/dommy/internal/popover_invoker_element.rb +67 -0
  109. data/lib/dommy/internal/popover_stack.rb +120 -0
  110. data/lib/dommy/internal/post_insertion_steps.rb +140 -71
  111. data/lib/dommy/internal/reflected_attributes.rb +128 -18
  112. data/lib/dommy/internal/rendered_text/collector.rb +1 -5
  113. data/lib/dommy/internal/rendered_text/fragment.rb +6 -2
  114. data/lib/dommy/internal/selector_arguments.rb +2 -1
  115. data/lib/dommy/internal/selector_match.rb +1 -1
  116. data/lib/dommy/internal/selector_matcher.rb +11 -6
  117. data/lib/dommy/internal/selector_parser.rb +14 -1
  118. data/lib/dommy/internal/sequential_focus_navigation.rb +210 -0
  119. data/lib/dommy/internal/shadow_root_registry.rb +7 -0
  120. data/lib/dommy/internal/template_content_registry.rb +7 -1
  121. data/lib/dommy/internal/text_selection.rb +185 -32
  122. data/lib/dommy/internal/toggle_events.rb +6 -4
  123. data/lib/dommy/internal/unsafe_html.rb +107 -0
  124. data/lib/dommy/internal/url_parser.rb +84 -8
  125. data/lib/dommy/internal/user_activation.rb +192 -0
  126. data/lib/dommy/internal/web_idl.rb +149 -16
  127. data/lib/dommy/internal/window_constructors.rb +26 -6
  128. data/lib/dommy/internal/xml_serialization.rb +3 -3
  129. data/lib/dommy/js/constructor_resolver.rb +18 -0
  130. data/lib/dommy/js/custom_element_bridge.rb +57 -82
  131. data/lib/dommy/js/dom_interfaces.rb +50 -15
  132. data/lib/dommy/js/host_bridge.rb +189 -40
  133. data/lib/dommy/js/host_runtime.js +1897 -415
  134. data/lib/dommy/js/marshaller.rb +13 -4
  135. data/lib/dommy/js/module_loader.rb +37 -6
  136. data/lib/dommy/js/module_preload.rb +107 -29
  137. data/lib/dommy/js/script_boot.rb +197 -115
  138. data/lib/dommy/js/serialized_record.rb +32 -0
  139. data/lib/dommy/js/webidl_event_handlers.js +45 -0
  140. data/lib/dommy/js/webidl_members.js +196 -0
  141. data/lib/dommy/js/webidl_signatures.js +2055 -0
  142. data/lib/dommy/js/webidl_tables.js +47 -100
  143. data/lib/dommy/js/window_wiring.rb +9 -5
  144. data/lib/dommy/location.rb +129 -76
  145. data/lib/dommy/media_query_list.rb +4 -13
  146. data/lib/dommy/message_channel.rb +137 -64
  147. data/lib/dommy/mutation_observer.rb +2 -0
  148. data/lib/dommy/navigation.rb +59 -9
  149. data/lib/dommy/navigator.rb +131 -5
  150. data/lib/dommy/node.rb +19 -11
  151. data/lib/dommy/notification.rb +9 -1
  152. data/lib/dommy/promise.rb +8 -0
  153. data/lib/dommy/range.rb +5 -34
  154. data/lib/dommy/resources.rb +38 -3
  155. data/lib/dommy/scheduler.rb +176 -48
  156. data/lib/dommy/shadow_root.rb +117 -19
  157. data/lib/dommy/storage.rb +135 -25
  158. data/lib/dommy/structured_data.rb +45 -0
  159. data/lib/dommy/style_declaration.rb +16 -0
  160. data/lib/dommy/text_codec.rb +2 -14
  161. data/lib/dommy/tree_walker.rb +10 -18
  162. data/lib/dommy/url.rb +11 -4
  163. data/lib/dommy/validity_state.rb +109 -107
  164. data/lib/dommy/version.rb +1 -1
  165. data/lib/dommy/web_socket.rb +5 -28
  166. data/lib/dommy/window.rb +811 -99
  167. data/lib/dommy/worker.rb +4 -28
  168. data/lib/dommy/xml_http_request.rb +32 -45
  169. data/lib/dommy.rb +35 -1
  170. metadata +35 -4
  171. data/lib/dommy/internal/cookie_jar.rb +0 -29
@@ -5,18 +5,17 @@
5
5
  // Values crossing the boundary are tagged: a bridge-able Ruby object is
6
6
  // `{ __rb_handle: id }`, a JS function passed to Ruby is `{ __rb_callback: id }`.
7
7
  globalThis.__rbHost = (function () {
8
- // The platform's own enumerations — what interfaces, members, constants and
9
- // handler attributes the specs declare — live in webidl_tables.js, evaluated
10
- // just before this file. They are bound here as plain consts so the code below
11
- // reads (and costs) the same as when they were written inline.
8
+ // The platform's own enumerations — what interfaces, members and constants
9
+ // the specs declare — live in webidl_tables.js (and the generated
10
+ // webidl_*.js), evaluated just before this file. They are bound here as
11
+ // plain consts so the code below reads (and costs) the same as when they
12
+ // were written inline.
12
13
  const {
13
14
  ARRAY_LIKE_COLLECTIONS, INDEXED_SETTER_INTERFACES, ENTRIES_ITERABLES, PAIR_ITERABLE_COLLECTIONS,
14
- NAMED_PROP_COLLECTIONS, NULL_TO_EMPTY_STRING_SETTERS,
15
- INTERFACE_NULL_TO_EMPTY_STRING_SETTERS, FORM_VALUE_FIELDS, READONLY_ATTRS,
15
+ FORM_VALUE_FIELDS, READONLY_ATTRS,
16
16
  UNFORGEABLE_ATTRS, UNFORGEABLE_METHODS, UNFORGEABLE_DATA, FIXED_SHAPE_INTERFACES,
17
17
  INTERFACE_CONSTANTS, INTERFACE_MEMBERS, FROZEN_ARRAY_ATTRIBUTES, INTERFACE_UNSCOPABLES, PROTO_RESOLVED_METHODS,
18
- NODE_OR_STRING_METHODS, ELEMENT_HANDLER_ATTRIBUTES, WINDOW_REFLECTED_HANDLERS,
19
- BODY_REFLECTED_HANDLERS, METHOD_ARITY, INTERFACE_METHOD_ARITY, CONSTRUCTOR_ARITY,
18
+ NODE_OR_STRING_METHODS, METHOD_ARITY, INTERFACE_METHOD_ARITY, CONSTRUCTOR_ARITY,
20
19
  VOID_METHODS, INTERFACE_VOID_METHODS, JS_GLOBALS,
21
20
  } = globalThis.__rbIdl;
22
21
 
@@ -75,14 +74,17 @@ globalThis.__rbHost = (function () {
75
74
  return fn;
76
75
  }
77
76
 
77
+ // One function per (interface, attribute), shared by every instance, like
78
+ // the getter.
78
79
  const unforgeableSetters = new Map();
79
- function unforgeableSetter(name) {
80
- let fn = unforgeableSetters.get(name);
80
+ function unforgeableSetter(iface, name) {
81
+ const key = iface + "." + name;
82
+ let fn = unforgeableSetters.get(key);
81
83
  if (!fn) {
82
84
  // A location setter navigates, which is a DOM mutation like any other —
83
85
  // hostSet brackets it with the epoch bumps that says so.
84
- fn = function (value) { hostSet(this[HKEY], name, value); };
85
- unforgeableSetters.set(name, fn);
86
+ fn = function (value) { hostSet(this[HKEY], name, convertAttributeValue(iface, name, value)); };
87
+ unforgeableSetters.set(key, fn);
86
88
  }
87
89
  return fn;
88
90
  }
@@ -104,9 +106,11 @@ globalThis.__rbHost = (function () {
104
106
  if (!isProxy(this) || !interfaceChainOf(this).includes(iface)) {
105
107
  throw new TypeError("Illegal invocation: " + iface + "." + name + " called on a different object");
106
108
  }
109
+ const call = declaredConversion(iface, "operations", name);
110
+ const wire = dehydrateArgs(call ? convertArguments(call, args) : args);
107
111
  bumpDomEpoch();
108
112
  try {
109
- return hostCallResult(name, __rb_host_call(this[HKEY], name, dehydrateArgs(args)), iface);
113
+ return hostCallResult(name, __rb_host_call(this[HKEY], name, wire), iface);
110
114
  } finally {
111
115
  bumpDomEpoch();
112
116
  }
@@ -144,7 +148,7 @@ globalThis.__rbHost = (function () {
144
148
  for (const [name, writable] of Object.entries(UNFORGEABLE_ATTRS[iface] || {})) {
145
149
  Object.defineProperty(target, name, {
146
150
  get: unforgeableGetter(name),
147
- set: writable ? unforgeableSetter(name) : undefined,
151
+ set: writable ? unforgeableSetter(iface, name) : undefined,
148
152
  enumerable: true, configurable: false,
149
153
  });
150
154
  }
@@ -165,70 +169,226 @@ globalThis.__rbHost = (function () {
165
169
  return isProxy(arg) ? arg : String(arg);
166
170
  }
167
171
 
168
- function isHandlerAttribute(el, name) {
169
- if (ELEMENT_HANDLER_ATTRIBUTES.has(name)) return true;
170
- if (!WINDOW_REFLECTED_HANDLERS.has(name)) return false;
171
-
172
+ // HTML "get the current value of the event handler", the compile step: an
173
+ // event handler content attribute's body becomes a function named after the
174
+ // handler (`function onclick(event) {\n…\n}`, so its source text reads as a
175
+ // browser's), whose scope is the element, its form owner and its document
176
+ // for an element's handler and the global alone for a Window's — where
177
+ // `onerror` takes (event, source, lineno, colno, error). Called from Ruby
178
+ // (Document#event_handler_compiler) when the handler is first read or run.
179
+ // A body that is not a FunctionBody throws its SyntaxError back, tagged, so
180
+ // the Ruby side reports it.
181
+ function compileEventHandler(wireEl, name, code, windowHandler) {
182
+ bumpDomEpoch(); // Ruby -> JS entry: see invokeCallback
172
183
  try {
173
- const tag = el.tagName;
174
- return tag === "BODY" || tag === "FRAMESET";
184
+ const el = wireEl == null ? null : rehydrate(wireEl);
185
+ const params = windowHandler && name === "onerror"
186
+ ? ["event", "source", "lineno", "colno", "error"] : ["event"];
187
+ const body = String(code);
188
+ // Parse the body as a FunctionBody first: wrapping it below could let a
189
+ // stray `}` close the function early and still parse.
190
+ new Function(...params, body);
191
+ const scopes = [];
192
+ if (typeof globalThis.window !== "undefined" && globalThis.window !== globalThis) scopes.push(globalThis.window);
193
+ if (el) {
194
+ const doc = el.ownerDocument;
195
+ if (doc) scopes.push(doc);
196
+ let form = null;
197
+ try { form = el.form || null; } catch (e) { /* no form owner */ }
198
+ if (form && typeof form === "object") scopes.push(form);
199
+ scopes.push(el);
200
+ }
201
+ const names = scopes.map((_, i) => "__s" + i);
202
+ const opens = names.map((n) => "with (" + n + ") ").join("");
203
+ const source = "function " + name + "(" + params.join(", ") + ") {\n" + body + "\n}";
204
+ const make = indirectEval("(function (" + names.join(", ") + ") { " + opens + "{ return " + source + "; } })");
205
+ return dehydrate(make(...scopes));
175
206
  } catch (e) {
176
- return false;
207
+ return tagThrow(e);
177
208
  }
178
209
  }
179
210
 
180
- // Setting an on* content attribute at runtime (`el.setAttribute("onclick",
181
- // code)`) must compile+activate the handler synchronously, exactly like the
182
- // boot-time inline-handler wiring (script_boot). Mirrors its scope chain —
183
- // [element, form owner, document] — so `onclick="getElementById(…)"` or a
184
- // form control's bare member resolve, and assigns via the on* IDL setter
185
- // (el.onclick = fn), which the proxy routes to the Ruby handler registry.
186
- // A null code (removeAttribute) clears the handler. Invalid source is ignored.
187
- function wireInlineHandler(el, name, code) {
188
- try {
189
- if (!isHandlerAttribute(el, name)) return;
190
- if (code == null) { el[name] = null; return; }
191
- let src = "with(this){\n" + String(code) + "\n}";
192
- try { if (el.form) src = "with(this.form){\n" + src + "\n}"; } catch (e) { /* no form owner */ }
193
- src = "with(document){\n" + src + "\n}";
194
- let fn;
195
- try { fn = new Function("event", src); }
196
- catch (e) { fn = new Function("event", String(code)); } // fall back to plain scope
197
- el[name] = fn;
198
- } catch (e) { /* syntactically invalid handler: skip, non-fatal */ }
199
- }
200
-
201
- // Compile every on* content attribute already in the document into a live
202
- // handler. Run once at boot, after parsing and before scripts (matching the
203
- // spec, where content attributes are set as the document is parsed), and
204
- // replayed whenever an element carrying one turns up later (cloneNode,
205
- // innerHTML, a template's fragment). Idempotent: an element whose handler is
206
- // already compiled is left alone.
211
+ // ===== WebIDL string conversions =====
207
212
  //
208
- // The scan is selector-driven — only elements carrying a known handler
209
- // attribute — rather than a walk of every element. A handler on body/frameset
210
- // for a window-reflected event belongs on the WINDOW, so it is wired with
211
- // addEventListener; the element's own load never fires, which is what makes
212
- // `<body onload>` work. Everything else goes through wireInlineHandler, the
213
- // same compilation the runtime `setAttribute("on*")` path uses.
214
- function wireInlineHandlers() {
215
- const selector = [...ELEMENT_HANDLER_ATTRIBUTES, ...WINDOW_REFLECTED_HANDLERS]
216
- .map((name) => "[" + name + "]").join(",");
217
- const body = document.body;
218
- for (const el of document.querySelectorAll(selector)) {
219
- const onBody = el === body || el.tagName === "FRAMESET";
220
- for (const name of el.getAttributeNames()) {
221
- if (!ELEMENT_HANDLER_ATTRIBUTES.has(name) &&
222
- !(onBody && WINDOW_REFLECTED_HANDLERS.has(name))) continue;
223
- if (onBody && BODY_REFLECTED_HANDLERS.has(name)) {
224
- try {
225
- window.addEventListener(name.slice(2), new Function("event", el.getAttribute(name)));
226
- } catch (e) { /* syntactically invalid handler: skip, non-fatal */ }
227
- } else if (typeof el[name] !== "function") {
228
- wireInlineHandler(el, name, el.getAttribute(name));
213
+ // A value a script hands an operation, a constructor or an attribute setter
214
+ // is converted to the string type the spec declares for it BEFORE it crosses
215
+ // into Ruby. Only here can a JS object's own toString run (and throw before
216
+ // the operation does anything), a Symbol throw, and null still be told from
217
+ // undefined; across the bridge an object is a Ruby Hash or an opaque ref.
218
+ // Which arguments and attributes are strings, and of which type, is
219
+ // webidl_signatures.js, generated from the specs' own IDL; this section is the
220
+ // conversions themselves, and every entry point below goes through it.
221
+ const SIGNATURES = globalThis.__rbIdlSignatures || {};
222
+
223
+ // https://webidl.spec.whatwg.org/#es-DOMString — ToString, which a template
224
+ // literal performs and String() does not: String(Symbol()) is "Symbol()",
225
+ // where ToString throws a TypeError.
226
+ function toDOMString(v) {
227
+ return typeof v === "string" ? v : `${v}`;
228
+ }
229
+
230
+ // https://webidl.spec.whatwg.org/#es-USVString — a DOMString whose lone
231
+ // surrogates become U+FFFD.
232
+ function toUSVString(v) {
233
+ const s = toDOMString(v);
234
+ return /[\ud800-\udfff]/.test(s) ? scrubLoneSurrogates(s) : s;
235
+ }
236
+
237
+ // https://webidl.spec.whatwg.org/#es-ByteString — a DOMString none of whose
238
+ // code units is above U+00FF; one that is is a TypeError, not a truncation.
239
+ function toByteString(v) {
240
+ const s = toDOMString(v);
241
+ if (/[^\u0000-\u00ff]/.test(s)) {
242
+ throw new TypeError("Failed to convert value to 'ByteString': it contains a code unit above U+00FF.");
243
+ }
244
+ return s;
245
+ }
246
+
247
+ const STRING_CONVERSIONS = { DOMString: toDOMString, USVString: toUSVString, ByteString: toByteString };
248
+
249
+ // One signature entry ("USVString", "optional DOMString", "DOMString?",
250
+ // "[LegacyNullToEmptyString] DOMString", "DOMString...") as the conversion it
251
+ // names, parsed once per distinct entry.
252
+ const parsedConversions = new Map();
253
+ function conversionFor(entry) {
254
+ if (entry === null || entry === undefined) return null;
255
+ let conversion = parsedConversions.get(entry);
256
+ if (conversion) return conversion;
257
+ let type = entry;
258
+ const optional = type.startsWith("optional ");
259
+ if (optional) type = type.slice("optional ".length);
260
+ const nullToEmpty = type.startsWith("[LegacyNullToEmptyString] ");
261
+ if (nullToEmpty) type = type.slice("[LegacyNullToEmptyString] ".length);
262
+ const variadic = type.endsWith("...");
263
+ if (variadic) type = type.slice(0, -3);
264
+ const nullable = type.endsWith("?");
265
+ if (nullable) type = type.slice(0, -1);
266
+ const toString = STRING_CONVERSIONS[type];
267
+ if (!toString) throw new Error("webidl_signatures.js: unknown string type in " + JSON.stringify(entry));
268
+ conversion = {
269
+ optional,
270
+ variadic,
271
+ convert(v) {
272
+ // A nullable type takes undefined as null too; [LegacyNullToEmptyString]
273
+ // only null.
274
+ if (nullable && (v === null || v === undefined)) return null;
275
+ if (nullToEmpty && v === null) return "";
276
+ return toString(v);
277
+ },
278
+ };
279
+ parsedConversions.set(entry, conversion);
280
+ return conversion;
281
+ }
282
+
283
+ // The interfaces to search for a member of an object of interface `iface`,
284
+ // nearest first: the chain its proxy was described with when there is one,
285
+ // which is the one Ruby answers for, else the IDL's own `inherits`.
286
+ function signatureChain(iface) {
287
+ const desc = descByInterface.get(iface);
288
+ if (desc && desc.chain) return desc.chain;
289
+ const chain = [];
290
+ for (let name = iface; name && chain.indexOf(name) === -1; name = hasOwn(SIGNATURES, name) ? SIGNATURES[name].inherits : undefined) {
291
+ chain.push(name);
292
+ }
293
+ return chain;
294
+ }
295
+
296
+ // The nearest declaration of member `name` in `kind` ("operations",
297
+ // "static_operations", "attributes") for an object of interface `iface`, or
298
+ // null when nothing in its chain converts it. A declaration recorded as null
299
+ // still ends the search: that interface's member is not a string. Static
300
+ // members belong to the interface itself, not its chain, and so does its
301
+ // constructor (kind "constructor", no name).
302
+ const hasOwn = (object, key) => !!object && Object.prototype.hasOwnProperty.call(object, key);
303
+ const declarations = new Map();
304
+ function declaredConversion(iface, kind, name) {
305
+ if (iface === undefined || iface === null) return null;
306
+ const key = iface + "\u0000" + kind + "\u0000" + (name || "");
307
+ if (declarations.has(key)) return declarations.get(key);
308
+ let found = null;
309
+ let declarer = iface;
310
+ if (kind === "constructor") {
311
+ if (hasOwn(SIGNATURES, iface) && hasOwn(SIGNATURES[iface], "constructor")) found = SIGNATURES[iface].constructor;
312
+ } else {
313
+ const chain = kind === "static_operations" ? [iface] : signatureChain(iface);
314
+ for (const owner of chain) {
315
+ const table = hasOwn(SIGNATURES, owner) ? SIGNATURES[owner][kind] : undefined;
316
+ if (hasOwn(table, name)) {
317
+ found = table[name];
318
+ declarer = owner;
319
+ break;
229
320
  }
230
321
  }
231
322
  }
323
+ if (typeof found === "string") {
324
+ found = conversionFor(found);
325
+ } else if (found) {
326
+ // A call: what WebIDL's overload resolution checks, and how the
327
+ // arguments convert. The label names it in the TypeError a short call
328
+ // throws, in the shape engines use.
329
+ found = {
330
+ required: found.required || 0,
331
+ conversions: (found.arguments || []).map(conversionFor),
332
+ label: kind === "constructor"
333
+ ? "Failed to construct '" + iface + "'"
334
+ : "Failed to execute '" + name + "' on '" + declarer + "'",
335
+ };
336
+ }
337
+ declarations.set(key, found);
338
+ return found;
339
+ }
340
+
341
+ // The arguments a script passed to `call` (a declaredConversion of a call),
342
+ // checked and converted. Fewer than the required count is a TypeError, as
343
+ // WebIDL's overload resolution finds no overload for them; then each string
344
+ // argument is converted in order. An optional argument passed as undefined
345
+ // stays undefined (the operation's default applies).
346
+ function convertArguments(call, args) {
347
+ if (args.length < call.required) {
348
+ throw new TypeError(call.label + ": " + call.required + " argument" + (call.required === 1 ? "" : "s") +
349
+ " required, but only " + args.length + " present.");
350
+ }
351
+ const conversions = call.conversions;
352
+ let out = args;
353
+ for (let i = 0; i < args.length; i++) {
354
+ const conversion = i < conversions.length
355
+ ? conversions[i]
356
+ : (conversions.length && conversions[conversions.length - 1] && conversions[conversions.length - 1].variadic
357
+ ? conversions[conversions.length - 1] : null);
358
+ if (!conversion) continue;
359
+ if (conversion.optional && args[i] === undefined) continue;
360
+ const value = conversion.convert(args[i]);
361
+ if (value === args[i]) continue;
362
+ if (out === args) out = args.slice();
363
+ out[i] = value;
364
+ }
365
+ return out;
366
+ }
367
+
368
+ // `fn` with its arguments checked and converted as `iface`'s `kind` member
369
+ // `name` declares them, keeping `this` (a stub may read it); `fn` itself
370
+ // when there is nothing to check.
371
+ function withConvertedArguments(fn, iface, kind, name) {
372
+ const call = declaredConversion(iface, kind, name);
373
+ if (!call) return fn;
374
+ return function (...args) {
375
+ return fn.apply(this, convertArguments(call, args));
376
+ };
377
+ }
378
+
379
+ // A static operation's function, named and with the `length` WebIDL gives
380
+ // it: the shortest overload's required argument count.
381
+ function withStaticArity(fn, name, call) {
382
+ Object.defineProperty(fn, "name", { value: name, configurable: true });
383
+ Object.defineProperty(fn, "length", { value: call ? call.required : 0, configurable: true });
384
+ return fn;
385
+ }
386
+
387
+ // The value an attribute setter receives, converted as `iface`'s attribute
388
+ // `name` declares it, or as it is when the attribute is not a string.
389
+ function convertAttributeValue(iface, name, value) {
390
+ const conversion = declaredConversion(iface, "attributes", name);
391
+ return conversion ? conversion.convert(value) : value;
232
392
  }
233
393
 
234
394
  function withArity(fn, name, iface) {
@@ -274,7 +434,10 @@ globalThis.__rbHost = (function () {
274
434
  const fn = this[name];
275
435
  if (typeof fn === "function" && fn !== stub) return fn.apply(this, args);
276
436
  }
277
- const wire = dehydrateArgs(coerce ? args.map(coerceNodeOrString) : args);
437
+ checkReceiver(this, iface, name);
438
+ const call = declaredConversion(receiverInterface(this, iface), "operations", name);
439
+ const converted = call ? convertArguments(call, args) : args;
440
+ const wire = dehydrateArgs(coerce ? converted.map(coerceNodeOrString) : converted);
278
441
  return readOnly
279
442
  ? hostCallResult(name, __rb_host_call(this[HKEY], name, wire), iface)
280
443
  : callMutating(this[HKEY], name, wire, iface);
@@ -302,8 +465,13 @@ globalThis.__rbHost = (function () {
302
465
  // The return value is the host's answer to "did I claim this write?" — false
303
466
  // means the caller should keep the value JS-side as an expando.
304
467
  function hostSet(handle, name, value) {
468
+ return hostSetWire(handle, name, dehydrateTop(value));
469
+ }
470
+
471
+ // hostSet for a value already in its wire form.
472
+ function hostSetWire(handle, name, wire) {
305
473
  bumpDomEpoch();
306
- const handled = __rb_host_set(handle, name, dehydrateTop(value));
474
+ const handled = __rb_host_set(handle, name, wire);
307
475
  bumpDomEpoch();
308
476
  if (handled && typeof handled === "object" && handled.__rb_exception__) {
309
477
  throw makeHostError(handled.__rb_exception__);
@@ -311,34 +479,101 @@ globalThis.__rbHost = (function () {
311
479
  return handled;
312
480
  }
313
481
 
314
- function memberGetStub(name) {
315
- return function () { return rehydrate(__rb_host_get(this[HKEY], name)); };
482
+ // An operation or attribute on an interface prototype is one function
483
+ // shared by every instance, so it takes its object from `this`, which WebIDL
484
+ // requires to implement the interface: anything else — the prototype itself,
485
+ // a plain object, an instance of another interface — is a TypeError rather
486
+ // than a host call on no object.
487
+ function checkReceiver(receiver, iface, name) {
488
+ if (!isProxy(receiver) || !interfaceChainOf(receiver).includes(iface)) {
489
+ throw new TypeError("Illegal invocation: " + iface + "." + name + " called on a different object");
490
+ }
316
491
  }
317
- // [LegacyNullToEmptyString]: null becomes "" rather than "null". Declared per
318
- // attribute in the IDL, so a name that is null-to-empty on one interface and a
319
- // plain DOMString on another (`value`, on the text controls and on nothing
320
- // else) is answered by the interface's own list.
321
- function nullToEmptyString(iface, name) {
322
- if (NULL_TO_EMPTY_STRING_SETTERS.has(name)) return true;
323
- const own = iface === undefined ? undefined : INTERFACE_NULL_TO_EMPTY_STRING_SETTERS[iface];
324
- return !!own && own.indexOf(name) !== -1;
492
+
493
+ function memberGetStub(name, iface) {
494
+ return function () {
495
+ checkReceiver(this, iface, name);
496
+ return rehydrate(__rb_host_get(this[HKEY], name));
497
+ };
498
+ }
499
+ // The interface a prototype member converts its values as: the receiver's
500
+ // own when it is one of our proxies (a derived interface may declare the
501
+ // member again), else the interface whose prototype holds the member.
502
+ function receiverInterface(receiver, iface) {
503
+ return (isProxy(receiver) && proxyInterfaces.get(receiver)) || iface;
325
504
  }
326
505
 
327
506
  function memberSetStub(name, iface) {
328
- // Mirror the proxy set trap for a reflected attribute: [LegacyNullToEmptyString]
329
- // coercion, then the shared host write (the set trap delegates instance
330
- // writes to this prototype setter, so it must invalidate the same caches).
331
- // Called with the element as `this`.
507
+ // Mirror the proxy set trap for a reflected attribute: the WebIDL
508
+ // conversion of the value, then the shared host write (the set trap
509
+ // delegates instance writes to this prototype setter, so it must
510
+ // invalidate the same caches). Called with the element as `this`. An
511
+ // event handler's value crosses as eventHandlerWire makes it.
512
+ if (declaresEventHandler(iface, name)) {
513
+ return function (v) {
514
+ checkReceiver(this, iface, name);
515
+ hostSetWire(this[HKEY], name, eventHandlerWire(v));
516
+ };
517
+ }
332
518
  return function (v) {
333
- if (nullToEmptyString(iface, name)) v = v === null ? "" : String(v);
334
- hostSet(this[HKEY], name, v);
519
+ checkReceiver(this, iface, name);
520
+ hostSet(this[HKEY], name, convertAttributeValue(receiverInterface(this, iface), name, v));
335
521
  };
336
522
  }
523
+
524
+ // ===== Event handler IDL attributes =====
525
+ //
526
+ // Which `on…` names are event handlers on which objects is the IDL's call
527
+ // (webidl_event_handlers.js, generated from it): a name is one on an object
528
+ // when an interface in its chain declares it — `onclick` on an element,
529
+ // Document or Window, `onreadystatechange` on Document and XMLHttpRequest —
530
+ // and on nothing else, so `div.onbogus = f` is an ordinary expando and
531
+ // `"onClick" in div` is false. An EventTarget whose interfaces the IDL
532
+ // fixture does not cover (Animation, Performance, …) keeps the old reading:
533
+ // any `on` + lowercase name is one.
534
+ const EVENT_HANDLERS = new Map(
535
+ Object.entries(globalThis.__rbIdlEventHandlers || {}).map(([iface, names]) => [iface, new Set(names)]));
536
+ function declaresEventHandler(iface, name) {
537
+ const own = EVENT_HANDLERS.get(iface);
538
+ return own !== undefined && own.has(name);
539
+ }
540
+ // The handler names along `chain`, or null when the IDL fixture does not
541
+ // know the object's interface at all (an EventTarget Dommy has without its
542
+ // spec's IDL — Animation, Performance, …), which keeps the `on` + lowercase
543
+ // reading. A node, and any interface the fixture covers (its
544
+ // webidl_signatures.js entry says so) has exactly the handlers its chain
545
+ // declares — none for a bare `new EventTarget()`.
546
+ function eventHandlersOf(chain, isNode) {
547
+ let names = null;
548
+ for (const iface of chain || []) {
549
+ const own = EVENT_HANDLERS.get(iface);
550
+ if (own) for (const n of own) (names ||= new Set()).add(n);
551
+ }
552
+ const covered = isNode || (chain && chain.length > 0 && hasOwn(SIGNATURES, chain[0]));
553
+ return names || (covered ? new Set() : null);
554
+ }
555
+ // Whether `prop` is an event handler IDL attribute of an object of `shape`.
556
+ function isEventHandlerName(shape, prop) {
557
+ if (typeof prop !== "string") return false;
558
+ if (shape.handlers !== null) return shape.handlers.has(prop);
559
+ return shape.methods.has("addEventListener") && /^on[a-z]/.test(prop);
560
+ }
561
+
337
562
  // Seed interface `name`'s WebIDL members onto its prototype (idempotent — skips
338
563
  // names already present so a subclass never shadows an inherited member).
564
+ // The generated table (webidl_members.js: the IDL's members that the bridge
565
+ // classes answer) and the hand-kept INTERFACE_MEMBERS (members answered
566
+ // other than by name, e.g. JS-side) are seeded together.
567
+ const GENERATED_MEMBERS = globalThis.__rbIdlMembers || {};
339
568
  function seedInterfaceMembers(proto, name) {
340
- const members = INTERFACE_MEMBERS[name];
341
- if (!members) return;
569
+ const own = (table) => (Object.prototype.hasOwnProperty.call(table, name) ? table[name] : undefined);
570
+ const hand = own(INTERFACE_MEMBERS);
571
+ const generated = own(GENERATED_MEMBERS);
572
+ if (!hand && !generated) return;
573
+ const members = {};
574
+ for (const kind of ["m", "g", "p"]) {
575
+ members[kind] = [...((hand && hand[kind]) || []), ...((generated && generated[kind]) || [])];
576
+ }
342
577
  const def = (key, desc) => {
343
578
  if (!Object.prototype.hasOwnProperty.call(proto, key)) {
344
579
  Object.defineProperty(proto, key, desc);
@@ -347,18 +582,32 @@ globalThis.__rbHost = (function () {
347
582
  (members.m || []).forEach((mname) =>
348
583
  def(mname, { value: memberMethodStub(mname, name), writable: true, enumerable: true, configurable: true }));
349
584
  (members.g || []).forEach((gname) =>
350
- def(gname, { get: memberGetStub(gname), enumerable: true, configurable: true }));
585
+ def(gname, { get: memberGetStub(gname, name), enumerable: true, configurable: true }));
351
586
  (members.p || []).forEach((pname) =>
352
- def(pname, { get: memberGetStub(pname), set: memberSetStub(pname, name), enumerable: true, configurable: true }));
587
+ def(pname, { get: memberGetStub(pname, name), set: memberSetStub(pname, name), enumerable: true, configurable: true }));
353
588
  }
354
589
 
355
- // 1d: custom elements. ceRegistry maps a tag name to its JS constructor;
356
- // constructionStack carries the element being upgraded so the interface base
357
- // constructor (see protoForChain) adopts it when `super()` runs; cePending
358
- // holds whenDefined() resolvers waiting for a name to be defined.
359
- const ceRegistry = new Map();
360
- const constructionStack = [];
361
- const cePending = new Map();
590
+ // 1d: custom elements. Each CustomElementRegistry (a window's, an iframe's)
591
+ // keeps its definitions JS-side (ceStates, keyed by the registry's proxy);
592
+ // a definition is also findable by its id (Ruby names it so) and by its
593
+ // constructor (the HTML element constructor looks it up by NewTarget). A
594
+ // definition's construction stack carries the element being upgraded, so
595
+ // the HTMLElement constructor adopts it when `super()` runs.
596
+ const ceStates = new WeakMap();
597
+ const ceDefsById = new Map();
598
+ // A global registry's definitions by constructor — the fallback for a
599
+ // `new MyElement()` whose class the window's own registry does not define
600
+ // (an iframe's registry: Dommy has one realm for every window).
601
+ const ceDefsByCtor = new Map();
602
+ // HTML "active custom element constructor map": the registry a
603
+ // constructor being run by create-an-element or an upgrade belongs to.
604
+ const ceActiveRegistries = new Map();
605
+ // The window's own registry (its document's), whatever the page does to
606
+ // the `customElements` global.
607
+ let ceWindowRegistry;
608
+ let ceNextId = 0;
609
+ // HTML "already constructed marker".
610
+ const CE_ALREADY_CONSTRUCTED = Symbol("already constructed");
362
611
 
363
612
  // When a proxy is garbage-collected, drop the Ruby-side handle entry
364
613
  // (unless a live re-proxy for the same handle exists). Keeps the
@@ -532,17 +781,64 @@ globalThis.__rbHost = (function () {
532
781
  const out = { capture: !!options.capture };
533
782
  if (method === "addEventListener") {
534
783
  out.once = !!options.once;
535
- out.passive = !!options.passive;
784
+ // `passive` has no default in AddEventListenerOptions: left out, the
785
+ // target's default passive value decides (DOM "flatten more").
786
+ const passive = options.passive;
787
+ if (passive !== undefined) out.passive = !!passive;
536
788
  const signal = options.signal;
537
789
  if (signal !== undefined) out.signal = signal;
538
790
  }
539
791
  return out;
540
792
  }
541
793
 
794
+ // ===== Host promises as realm Promises =====
795
+ //
796
+ // A host API that returns a promise (fetch(), img.decode(), media.play(),
797
+ // clipboard reads, document.fonts.ready, …) hands back a Ruby PromiseValue.
798
+ // The page must get a Promise of this realm — `p instanceof Promise`,
799
+ // `Object.prototype.toString.call(p)` "[object Promise]", `Promise.resolve(p)
800
+ // === p` — so the PromiseValue crosses as a native Promise subscribed to it,
801
+ // settled when the host settles it. The same PromiseValue keeps giving the
802
+ // same Promise while that Promise is alive, and the Promise goes back to the
803
+ // host as the PromiseValue it stands for.
804
+ const hostPromiseProxies = new WeakMap(); // realm Promise -> host proxy (keeps the handle alive)
805
+ const realmPromises = new Map(); // handle -> WeakRef(realm Promise)
806
+ // Host promise proxies handed to script as themselves (makeHostDeferred's
807
+ // `promise`): that proxy is the PromiseValue's face in the realm, so it
808
+ // must come back as itself — a value that passes JS -> Ruby -> JS keeps its
809
+ // identity (see dehydrateSettle) — not as a realm Promise standing for it.
810
+ const exposedHostPromiseProxies = new WeakSet();
811
+ function realmPromiseFor(proxy) {
812
+ const handle = proxyHandles.get(proxy);
813
+ const ref = realmPromises.get(handle);
814
+ const existing = ref && ref.deref();
815
+ if (existing && hostPromiseProxies.get(existing) === proxy) return existing;
816
+ let resolveFn, rejectFn;
817
+ const promise = new Promise((resolve, reject) => { resolveFn = resolve; rejectFn = reject; });
818
+ hostPromiseProxies.set(promise, proxy);
819
+ realmPromises.set(handle, new WeakRef(promise));
820
+ // Subscribe without a chained host promise (nothing to hand back).
821
+ __rb_host_promise_subscribe(handle, dehydrate(resolveFn), dehydrate(rejectFn));
822
+ return promise;
823
+ }
824
+
825
+ // The time value of a Date object, or undefined for anything else. getTime
826
+ // throws unless its receiver has a [[DateValue]] slot, which is the brand
827
+ // check; it is captured here so a page replacing it changes nothing.
828
+ const dateGetTime = Date.prototype.getTime;
829
+ function dateTimeValue(v) {
830
+ try {
831
+ return dateGetTime.call(v);
832
+ } catch (_) {
833
+ return undefined;
834
+ }
835
+ }
836
+
542
837
  function dehydrate(v, seen) {
543
838
  if (typeof v === "string") return /[\ud800-\udfff]/.test(v) ? scrubLoneSurrogates(v) : v;
544
839
  if (typeof v === "function") return { __rb_callback: registerCallback(v) };
545
840
  if (isProxy(v)) return { __rb_handle: proxyHandles.get(v) };
841
+ if (hostPromiseProxies.has(v)) return { __rb_handle: proxyHandles.get(hostPromiseProxies.get(v)) };
546
842
  // A BufferSource (ArrayBuffer or any typed-array/DataView view) crosses as
547
843
  // its raw bytes, so host code gets a uniform byte buffer (TextDecoder.decode,
548
844
  // Blob, …) rather than a key→value object from Object.keys.
@@ -587,6 +883,12 @@ globalThis.__rbHost = (function () {
587
883
  const ref = { __rb_js_ref: registerJsRef(v) };
588
884
  if (handlesEvents) ref.__rb_handle_event = true;
589
885
  if (acceptsNodes) ref.__rb_accept_node = true;
886
+ // A Date also carries its time value, which the host cannot read
887
+ // through the ref (`input.valueAsDate = d`). Recognised by its internal
888
+ // slot, as WebIDL does, so a Date from another realm counts and an
889
+ // object merely inheriting from Date.prototype does not.
890
+ const time = dateTimeValue(v);
891
+ if (time !== undefined) ref.__rb_date = time;
590
892
  // An Error crossing as an opaque ref still needs a readable label and its
591
893
  // frames: the host cannot reach through a ref to read `.message` or
592
894
  // `.stack`, so an error the page hands us (`reportError(new
@@ -703,6 +1005,7 @@ globalThis.__rbHost = (function () {
703
1005
  const t = typeof v;
704
1006
  if (t === "object" || t === "function") {
705
1007
  if (isProxy(v)) return { __rb_handle: proxyHandles.get(v) };
1008
+ if (hostPromiseProxies.has(v)) return { __rb_handle: proxyHandles.get(hostPromiseProxies.get(v)) };
706
1009
  return { __rb_js_ref: registerJsRef(v) };
707
1010
  }
708
1011
  return v;
@@ -716,7 +1019,8 @@ globalThis.__rbHost = (function () {
716
1019
  // TypeError; §2.3.3.3.3 a thenable settles at most once; §2.3.3.3.4 a throwing
717
1020
  // `then` rejects.
718
1021
  function resolveHostPromise(handle, value, knownThen) {
719
- if (isProxy(value) && proxyHandles.get(value) === handle) {
1022
+ if ((isProxy(value) && proxyHandles.get(value) === handle) ||
1023
+ (hostPromiseProxies.has(value) && proxyHandles.get(hostPromiseProxies.get(value)) === handle)) {
720
1024
  __rb_settle_host_promise(handle, false, dehydrateSettle(new TypeError("Chaining cycle detected for promise")));
721
1025
  return;
722
1026
  }
@@ -755,6 +1059,8 @@ globalThis.__rbHost = (function () {
755
1059
  // plain values are unaffected. Used only for callback RETURN values, never for
756
1060
  // arguments (a promise passed as an argument must not be resolved).
757
1061
  function dehydrateReturn(v) {
1062
+ // A realm promise standing for a host promise goes back as that promise.
1063
+ if (hostPromiseProxies.has(v)) return dehydrateSettle(v);
758
1064
  if (v !== null && (typeof v === "object" || typeof v === "function") && !isProxy(v)) {
759
1065
  // Read `then` ONCE here (§2.3.3.1) and reuse it, so a one-time getter is not
760
1066
  // consumed by a separate type-probe before resolveHostPromise reads it.
@@ -783,8 +1089,10 @@ globalThis.__rbHost = (function () {
783
1089
  // conformance adapter builds on this.
784
1090
  function makeHostDeferred() {
785
1091
  const handle = __rb_new_host_promise();
1092
+ const promise = makeProxy(handle);
1093
+ exposedHostPromiseProxies.add(promise);
786
1094
  return {
787
- promise: makeProxy(handle),
1095
+ promise,
788
1096
  resolve: (value) => resolveHostPromise(handle, value),
789
1097
  reject: (reason) => __rb_settle_host_promise(handle, false, dehydrateSettle(reason)),
790
1098
  };
@@ -845,12 +1153,16 @@ globalThis.__rbHost = (function () {
845
1153
  // A host byte buffer tagged as an ArrayBuffer (Response/Blob/FileReader/
846
1154
  // XHR arrayBuffer) rehydrates to a bare ArrayBuffer.
847
1155
  if (v.__rb_arraybuffer) return new Uint8Array(v.__rb_arraybuffer).buffer;
1156
+ // A host point in time (valueAsDate) rehydrates to a new Date.
1157
+ if ("__rb_date" in v) return new Date(v.__rb_date);
848
1158
  if ("__rb_handle" in v) {
849
1159
  // A dispatch-in-flight host twin resolves to its JS event, so a
850
1160
  // listener's argument IS the object the caller constructed.
851
1161
  const jsEvent = jsEventByHandle.get(v.__rb_handle);
852
1162
  if (jsEvent !== undefined) return jsEvent;
853
- return makeProxy(v.__rb_handle, v.__rb_if, v.__rb_ce);
1163
+ const proxy = makeProxy(v.__rb_handle, v.__rb_if);
1164
+ return proxyInterfaces.get(proxy) === "PromiseValue" && !exposedHostPromiseProxies.has(proxy)
1165
+ ? realmPromiseFor(proxy) : proxy;
854
1166
  }
855
1167
  // An opaque JS-value reference round-tripping back from Ruby — restore the
856
1168
  // exact original object (identity-preserving).
@@ -876,6 +1188,619 @@ globalThis.__rbHost = (function () {
876
1188
  return Array.isArray(wire) ? wire.map(rehydrate) : [];
877
1189
  }
878
1190
 
1191
+ // ===== Structured serialization (HTML §2.7 "Safe passing of structured data") =====
1192
+ //
1193
+ // StructuredSerializeInternal / StructuredDeserialize and their WithTransfer
1194
+ // forms, run in the JS realm where the values live: only here can a cycle, a
1195
+ // lone surrogate, a BigInt, a String wrapper or a RegExp's flags be seen, and
1196
+ // only here can an ArrayBuffer be detached. The serialized form is a tree of
1197
+ // plain records (pointing at each other for cycles) that never crosses as
1198
+ // data: Ruby holds it as an opaque `__rb_serialized` reference
1199
+ // (Dommy::Js::SerializedRecord) and asks for it to be deserialized when the
1200
+ // message is delivered.
1201
+ //
1202
+ // Platform objects stay the host's business: a serializable one (Blob, File,
1203
+ // FileList, ImageData, DOMException, …) is snapshotted by the host
1204
+ // (`__rb_host_clone`) and the snapshot cloned again on each deserialization;
1205
+ // a transferable one (MessagePort) is transferred by the host
1206
+ // (`__rb_host_transfer`). Every other platform object is a DataCloneError.
1207
+ //
1208
+ // The intrinsics are captured up front, so a page replacing
1209
+ // `Map.prototype.entries` or a RegExp flag getter cannot steer the algorithm,
1210
+ // which reads internal slots rather than properties.
1211
+ function dataCloneError(message) {
1212
+ return makeHostError({ name: "DataCloneError", message });
1213
+ }
1214
+ const getterOf = (proto, name) => {
1215
+ const d = proto && Object.getOwnPropertyDescriptor(proto, name);
1216
+ return d && d.get;
1217
+ };
1218
+ const callOrUndefined = (fn, v, ...args) => {
1219
+ if (!fn) return undefined;
1220
+ try { return fn.call(v, ...args); } catch (_) { return undefined; }
1221
+ };
1222
+ const brandedBy = (fn, v, ...args) => {
1223
+ if (!fn) return false;
1224
+ try { fn.call(v, ...args); return true; } catch (_) { return false; }
1225
+ };
1226
+ const SC = {
1227
+ booleanValueOf: Boolean.prototype.valueOf,
1228
+ numberValueOf: Number.prototype.valueOf,
1229
+ stringValueOf: String.prototype.valueOf,
1230
+ bigintValueOf: typeof BigInt === "function" ? BigInt.prototype.valueOf : null,
1231
+ symbolValueOf: Symbol.prototype.valueOf,
1232
+ regexpSource: getterOf(RegExp.prototype, "source"),
1233
+ // [[OriginalFlags]], one brand-checked getter per flag (the `flags`
1234
+ // getter would Get each one through the prototype chain).
1235
+ regexpFlags: [["hasIndices", "d"], ["global", "g"], ["ignoreCase", "i"], ["multiline", "m"],
1236
+ ["dotAll", "s"], ["unicode", "u"], ["unicodeSets", "v"], ["sticky", "y"]]
1237
+ .map(([name, flag]) => [getterOf(RegExp.prototype, name), flag]).filter(([g]) => g),
1238
+ abByteLength: getterOf(ArrayBuffer.prototype, "byteLength"),
1239
+ abDetached: getterOf(ArrayBuffer.prototype, "detached"),
1240
+ abResizable: getterOf(ArrayBuffer.prototype, "resizable"),
1241
+ abMaxByteLength: getterOf(ArrayBuffer.prototype, "maxByteLength"),
1242
+ abTransfer: ArrayBuffer.prototype.transfer,
1243
+ abResize: ArrayBuffer.prototype.resize,
1244
+ sabByteLength: typeof SharedArrayBuffer === "function" ? getterOf(SharedArrayBuffer.prototype, "byteLength") : null,
1245
+ typedArrayProto: Object.getPrototypeOf(Uint8Array.prototype),
1246
+ dvBuffer: getterOf(DataView.prototype, "buffer"),
1247
+ dvByteLength: getterOf(DataView.prototype, "byteLength"),
1248
+ dvByteOffset: getterOf(DataView.prototype, "byteOffset"),
1249
+ mapSize: getterOf(Map.prototype, "size"),
1250
+ mapEntries: Map.prototype.entries,
1251
+ mapSet: Map.prototype.set,
1252
+ setSize: getterOf(Set.prototype, "size"),
1253
+ setValues: Set.prototype.values,
1254
+ setAdd: Set.prototype.add,
1255
+ mapIterNext: Object.getPrototypeOf(new Map().entries()).next,
1256
+ setIterNext: Object.getPrototypeOf(new Set().values()).next,
1257
+ weakMapHas: WeakMap.prototype.has,
1258
+ weakSetHas: WeakSet.prototype.has,
1259
+ weakRefDeref: typeof WeakRef === "function" ? WeakRef.prototype.deref : null,
1260
+ isError: typeof Error.isError === "function" ? Error.isError : null,
1261
+ u8Set: Object.getPrototypeOf(Uint8Array.prototype).set,
1262
+ defineProperty: Object.defineProperty,
1263
+ getOwnPropertyDescriptor: Object.getOwnPropertyDescriptor,
1264
+ keys: Object.keys,
1265
+ hasOwn: Object.prototype.hasOwnProperty,
1266
+ objToString: Object.prototype.toString,
1267
+ isArray: Array.isArray,
1268
+ };
1269
+ SC.taBuffer = getterOf(SC.typedArrayProto, "buffer");
1270
+ SC.taByteLength = getterOf(SC.typedArrayProto, "byteLength");
1271
+ SC.taByteOffset = getterOf(SC.typedArrayProto, "byteOffset");
1272
+ SC.taLength = getterOf(SC.typedArrayProto, "length");
1273
+ SC.taName = getterOf(SC.typedArrayProto, Symbol.toStringTag);
1274
+ SC.taEntries = SC.typedArrayProto.entries;
1275
+ // Whether a view of a resizable buffer tracks its length ([[ByteLength]] is
1276
+ // auto). No getter says so; growing the buffer by a byte (and shrinking it
1277
+ // back, which keeps every original byte) does. A buffer already at its
1278
+ // maximum cannot tell, and is taken as fixed-length.
1279
+ function isLengthTracking(view, buffer, isDataView) {
1280
+ if (!isArrayBuffer(buffer) || callOrUndefined(SC.abResizable, buffer) !== true) return false;
1281
+ const size = SC.abByteLength.call(buffer);
1282
+ if (size >= SC.abMaxByteLength.call(buffer)) return false;
1283
+ const lengthOf = () => (isDataView ? SC.dvByteLength.call(view) : SC.taByteLength.call(view));
1284
+ const before = lengthOf();
1285
+ SC.abResize.call(buffer, size + 1);
1286
+ let after;
1287
+ try { after = lengthOf(); } finally { SC.abResize.call(buffer, size); }
1288
+ return after !== before;
1289
+ }
1290
+ const ERROR_NAMES = ["Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError"];
1291
+ const ERROR_CTORS = {
1292
+ Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError,
1293
+ };
1294
+ const TYPED_ARRAY_CTORS = {};
1295
+ for (const name of ["Int8Array", "Uint8Array", "Uint8ClampedArray", "Int16Array", "Uint16Array",
1296
+ "Int32Array", "Uint32Array", "Float16Array", "Float32Array", "Float64Array", "BigInt64Array", "BigUint64Array"]) {
1297
+ if (typeof globalThis[name] === "function") TYPED_ARRAY_CTORS[name] = globalThis[name];
1298
+ }
1299
+
1300
+ const isObjectLike = (v) => v !== null && (typeof v === "object" || typeof v === "function");
1301
+ const isArrayBuffer = (v) => SC.abByteLength !== undefined && brandedBy(SC.abByteLength, v);
1302
+ const isSharedArrayBuffer = (v) => !!SC.sabByteLength && brandedBy(SC.sabByteLength, v);
1303
+ const isDetachedBuffer = (v) => SC.abDetached ? SC.abDetached.call(v) === true : false;
1304
+ // [[ErrorData]], told apart from an object merely claiming to be an Error
1305
+ // through Symbol.toStringTag: Error.isError where the engine has it, else the
1306
+ // builtin tag with no own/inherited toStringTag override.
1307
+ function hasErrorData(v) {
1308
+ if (SC.isError) return SC.isError(v);
1309
+ if (SC.objToString.call(v) !== "[object Error]") return false;
1310
+ for (let o = v; o; o = Object.getPrototypeOf(o)) {
1311
+ const d = SC.getOwnPropertyDescriptor(o, Symbol.toStringTag);
1312
+ if (d) return false;
1313
+ }
1314
+ return true;
1315
+ }
1316
+ // A platform object, as far as this realm can tell: a host proxy, or a
1317
+ // JS-side Event (docs/js-side-events-design.md).
1318
+ const isPlatformObject = (v) => isProxy(v) || (typeof v === "object" && v[JS_EVENT] !== undefined);
1319
+ const primaryInterfaceOf = (v) => (isProxy(v) ? proxyInterfaces.get(v) || interfaceChainOf(v)[0] : undefined);
1320
+
1321
+ // The host's view of a platform object's transferability: "transferable",
1322
+ // "detached", or anything else (not transferable at all).
1323
+ function hostTransferState(v) {
1324
+ if (!isProxy(v)) return null;
1325
+ return __rb_host_transfer_state(proxyHandles.get(v));
1326
+ }
1327
+
1328
+ function structuredSerializeInternal(value, forStorage, memory) {
1329
+ if (memory.has(value)) return memory.get(value);
1330
+ const type = typeof value;
1331
+ if (value === undefined || value === null || type === "boolean" || type === "number" ||
1332
+ type === "bigint" || type === "string") {
1333
+ return { type: "primitive", value };
1334
+ }
1335
+ if (type === "symbol") throw dataCloneError("A Symbol could not be cloned");
1336
+
1337
+ let serialized;
1338
+ let deep = false;
1339
+ if (type === "object" && brandedBy(SC.booleanValueOf, value)) {
1340
+ serialized = { type: "Boolean", value: SC.booleanValueOf.call(value) };
1341
+ } else if (type === "object" && brandedBy(SC.numberValueOf, value)) {
1342
+ serialized = { type: "Number", value: SC.numberValueOf.call(value) };
1343
+ } else if (type === "object" && SC.bigintValueOf && brandedBy(SC.bigintValueOf, value)) {
1344
+ serialized = { type: "BigInt", value: SC.bigintValueOf.call(value) };
1345
+ } else if (type === "object" && brandedBy(SC.stringValueOf, value)) {
1346
+ serialized = { type: "String", value: SC.stringValueOf.call(value) };
1347
+ } else if (type === "object" && dateTimeValue(value) !== undefined) {
1348
+ serialized = { type: "Date", value: dateTimeValue(value) };
1349
+ } else if (type === "object" && SC.regexpSource && brandedBy(SC.regexpSource, value)) {
1350
+ let flags = "";
1351
+ for (const [getter, flag] of SC.regexpFlags) if (getter.call(value)) flags += flag;
1352
+ serialized = { type: "RegExp", source: SC.regexpSource.call(value), flags };
1353
+ } else if (type === "object" && isSharedArrayBuffer(value)) {
1354
+ // The current settings object's cross-origin isolated capability is
1355
+ // false here (no COOP/COEP), so shared memory never leaves.
1356
+ throw dataCloneError("A SharedArrayBuffer could not be cloned: the page is not cross-origin isolated");
1357
+ } else if (type === "object" && isArrayBuffer(value)) {
1358
+ if (isDetachedBuffer(value)) throw dataCloneError("A detached ArrayBuffer could not be cloned");
1359
+ const size = SC.abByteLength.call(value);
1360
+ const copy = new Uint8Array(size);
1361
+ SC.u8Set.call(copy, new Uint8Array(value));
1362
+ serialized = { type: "ArrayBuffer", data: copy.buffer, byteLength: size };
1363
+ if (callOrUndefined(SC.abResizable, value) === true) {
1364
+ serialized.type = "ResizableArrayBuffer";
1365
+ serialized.maxByteLength = SC.abMaxByteLength.call(value);
1366
+ }
1367
+ } else if (type === "object" && (brandedBy(SC.taBuffer, value) || brandedBy(SC.dvBuffer, value))) {
1368
+ const isDataView = brandedBy(SC.dvBuffer, value);
1369
+ // IsArrayBufferViewOutOfBounds: a DataView's getters throw for it; a
1370
+ // typed array's report 0, but ValidateTypedArray (behind `entries`)
1371
+ // throws. A view of a detached buffer is out of bounds too.
1372
+ let byteLength, byteOffset, length;
1373
+ try {
1374
+ if (!isDataView) SC.taEntries.call(value);
1375
+ byteLength = isDataView ? SC.dvByteLength.call(value) : SC.taByteLength.call(value);
1376
+ byteOffset = isDataView ? SC.dvByteOffset.call(value) : SC.taByteOffset.call(value);
1377
+ if (!isDataView) length = SC.taLength.call(value);
1378
+ } catch (_) {
1379
+ throw dataCloneError("An out-of-bounds ArrayBufferView could not be cloned");
1380
+ }
1381
+ const buffer = isDataView ? SC.dvBuffer.call(value) : SC.taBuffer.call(value);
1382
+ const bufferSerialized = structuredSerializeInternal(buffer, forStorage, memory);
1383
+ serialized = {
1384
+ type: "ArrayBufferView", constructor: isDataView ? "DataView" : SC.taName.call(value),
1385
+ buffer: bufferSerialized, byteLength, byteOffset, length,
1386
+ lengthTracking: isLengthTracking(value, buffer, isDataView),
1387
+ };
1388
+ } else if (type === "object" && brandedBy(SC.mapSize, value)) {
1389
+ serialized = { type: "Map", entries: [] };
1390
+ deep = true;
1391
+ } else if (type === "object" && brandedBy(SC.setSize, value)) {
1392
+ serialized = { type: "Set", entries: [] };
1393
+ deep = true;
1394
+ } else if (type === "object" && !isPlatformObject(value) && hasErrorData(value)) {
1395
+ let name = value.name;
1396
+ if (!ERROR_NAMES.includes(name)) name = "Error";
1397
+ const messageDesc = SC.getOwnPropertyDescriptor(value, "message");
1398
+ const message = messageDesc && "value" in messageDesc ? String(messageDesc.value) : undefined;
1399
+ let stack;
1400
+ try { stack = value.stack; } catch (_) { /* a throwing stack accessor: none */ }
1401
+ serialized = { type: "Error", name, message, stack: typeof stack === "string" ? stack : undefined };
1402
+ // "Interesting accompanying data": an own `cause`, which every engine
1403
+ // carries across (WPT structured-clone battery checks it).
1404
+ const causeDesc = SC.getOwnPropertyDescriptor(value, "cause");
1405
+ if (causeDesc && "value" in causeDesc) serialized.hasCause = true;
1406
+ memory.set(value, serialized);
1407
+ if (serialized.hasCause) serialized.cause = structuredSerializeInternal(causeDesc.value, forStorage, memory);
1408
+ return serialized;
1409
+ } else if (type === "object" && SC.isArray(value) && !isProxy(value)) {
1410
+ serialized = { type: "Array", length: SC.getOwnPropertyDescriptor(value, "length").value, properties: [] };
1411
+ deep = true;
1412
+ } else if (isPlatformObject(value)) {
1413
+ const state = hostTransferState(value);
1414
+ if (state === "detached") throw dataCloneError("A detached " + primaryInterfaceOf(value) + " could not be cloned");
1415
+ // A serializable platform object: the host snapshots it (and throws a
1416
+ // DataCloneError for any other interface, a Node or a Window included).
1417
+ if (!isProxy(value)) throw dataCloneError("The object could not be cloned");
1418
+ const snapshot = rehydrate(__rb_host_clone(proxyHandles.get(value), !!forStorage));
1419
+ serialized = { type: "Platform", interface: primaryInterfaceOf(value), snapshot };
1420
+ } else if (type === "function") {
1421
+ throw dataCloneError("A function could not be cloned");
1422
+ } else if (brandedBy(SC.symbolValueOf, value) || brandedBy(SC.weakMapHas, value, {}) ||
1423
+ brandedBy(SC.weakSetHas, value, {}) || (SC.weakRefDeref && brandedBy(SC.weakRefDeref, value)) ||
1424
+ SC.objToString.call(value) === "[object Promise]") {
1425
+ // Any other internal slot: [[SymbolData]], [[WeakMapData]],
1426
+ // [[PromiseState]], … (an engine cannot be asked about every one, so the
1427
+ // common ones are recognised by their brand checks).
1428
+ throw dataCloneError("The object could not be cloned");
1429
+ } else {
1430
+ serialized = { type: "Object", properties: [] };
1431
+ deep = true;
1432
+ }
1433
+ memory.set(value, serialized);
1434
+
1435
+ if (deep) {
1436
+ if (serialized.type === "Map") {
1437
+ const copied = [];
1438
+ const it = SC.mapEntries.call(value);
1439
+ for (let step = SC.mapIterNext.call(it); !step.done; step = SC.mapIterNext.call(it)) copied.push(step.value);
1440
+ for (const [k, v] of copied) {
1441
+ serialized.entries.push([structuredSerializeInternal(k, forStorage, memory),
1442
+ structuredSerializeInternal(v, forStorage, memory)]);
1443
+ }
1444
+ } else if (serialized.type === "Set") {
1445
+ const copied = [];
1446
+ const it = SC.setValues.call(value);
1447
+ for (let step = SC.setIterNext.call(it); !step.done; step = SC.setIterNext.call(it)) copied.push(step.value);
1448
+ for (const v of copied) serialized.entries.push(structuredSerializeInternal(v, forStorage, memory));
1449
+ } else {
1450
+ for (const key of SC.keys(value)) {
1451
+ if (!SC.hasOwn.call(value, key)) continue;
1452
+ const inputValue = value[key];
1453
+ serialized.properties.push([key, structuredSerializeInternal(inputValue, forStorage, memory)]);
1454
+ }
1455
+ }
1456
+ }
1457
+ return serialized;
1458
+ }
1459
+
1460
+ function structuredDeserialize(serialized, memory) {
1461
+ if (memory.has(serialized)) return memory.get(serialized);
1462
+ let value;
1463
+ let deep = false;
1464
+ switch (serialized.type) {
1465
+ case "primitive": return serialized.value;
1466
+ case "Boolean": value = new Boolean(serialized.value); break;
1467
+ case "Number": value = new Number(serialized.value); break;
1468
+ case "BigInt": value = Object(serialized.value); break;
1469
+ case "String": value = new String(serialized.value); break;
1470
+ case "Date": value = new Date(serialized.value); break;
1471
+ case "RegExp": value = new RegExp(serialized.source, serialized.flags); break;
1472
+ case "ArrayBuffer":
1473
+ case "ResizableArrayBuffer": {
1474
+ try {
1475
+ value = serialized.type === "ResizableArrayBuffer"
1476
+ ? new ArrayBuffer(serialized.byteLength, { maxByteLength: serialized.maxByteLength })
1477
+ : new ArrayBuffer(serialized.byteLength);
1478
+ } catch (_) {
1479
+ throw dataCloneError("The ArrayBuffer could not be allocated");
1480
+ }
1481
+ SC.u8Set.call(new Uint8Array(value), new Uint8Array(serialized.data));
1482
+ break;
1483
+ }
1484
+ case "ArrayBufferView": {
1485
+ const buffer = structuredDeserialize(serialized.buffer, memory);
1486
+ // A length-tracking view stays one (its length argument omitted).
1487
+ const tracking = serialized.lengthTracking;
1488
+ if (serialized.constructor === "DataView") {
1489
+ value = tracking
1490
+ ? new DataView(buffer, serialized.byteOffset)
1491
+ : new DataView(buffer, serialized.byteOffset, serialized.byteLength);
1492
+ } else {
1493
+ const Ctor = TYPED_ARRAY_CTORS[serialized.constructor];
1494
+ if (!Ctor) throw dataCloneError(serialized.constructor + " is not supported");
1495
+ value = tracking ? new Ctor(buffer, serialized.byteOffset) : new Ctor(buffer, serialized.byteOffset, serialized.length);
1496
+ }
1497
+ break;
1498
+ }
1499
+ case "Map": value = new Map(); deep = true; break;
1500
+ case "Set": value = new Set(); deep = true; break;
1501
+ case "Array": value = new Array(serialized.length); deep = true; break;
1502
+ case "Object": value = {}; deep = true; break;
1503
+ case "Error": {
1504
+ const Ctor = ERROR_CTORS[serialized.name] || Error;
1505
+ value = new Ctor();
1506
+ if (serialized.message !== undefined) {
1507
+ SC.defineProperty(value, "message", { value: serialized.message, writable: true, enumerable: false, configurable: true });
1508
+ }
1509
+ if (serialized.stack !== undefined) {
1510
+ SC.defineProperty(value, "stack", { value: serialized.stack, writable: true, enumerable: false, configurable: true });
1511
+ } else {
1512
+ try { delete value.stack; } catch (_) { /* engine-owned */ }
1513
+ }
1514
+ memory.set(serialized, value);
1515
+ if (serialized.hasCause) {
1516
+ SC.defineProperty(value, "cause", {
1517
+ value: structuredDeserialize(serialized.cause, memory), writable: true, enumerable: false, configurable: true,
1518
+ });
1519
+ }
1520
+ return value;
1521
+ }
1522
+ case "Platform":
1523
+ // A new instance from the host's snapshot.
1524
+ value = rehydrate(__rb_host_clone(proxyHandles.get(serialized.snapshot), false));
1525
+ break;
1526
+ case "TransferredArrayBuffer":
1527
+ case "TransferredPlatform":
1528
+ // Received by structuredDeserializeWithTransfer, which seeds memory.
1529
+ throw dataCloneError("A transferred value was deserialized twice");
1530
+ default:
1531
+ throw dataCloneError("Unknown serialized type " + serialized.type);
1532
+ }
1533
+ memory.set(serialized, value);
1534
+ if (deep) {
1535
+ if (serialized.type === "Map") {
1536
+ for (const [k, v] of serialized.entries) {
1537
+ SC.mapSet.call(value, structuredDeserialize(k, memory), structuredDeserialize(v, memory));
1538
+ }
1539
+ } else if (serialized.type === "Set") {
1540
+ for (const v of serialized.entries) SC.setAdd.call(value, structuredDeserialize(v, memory));
1541
+ } else {
1542
+ for (const [key, v] of serialized.properties) {
1543
+ SC.defineProperty(value, key, { value: structuredDeserialize(v, memory), writable: true, enumerable: true, configurable: true });
1544
+ }
1545
+ }
1546
+ }
1547
+ return value;
1548
+ }
1549
+
1550
+ // WebIDL sequence<object> (the transfer list): an iterable of objects.
1551
+ function toObjectSequence(v, what) {
1552
+ if (!isObjectLike(v)) throw new TypeError(what + " is not an iterable of objects");
1553
+ const method = v[Symbol.iterator];
1554
+ if (typeof method !== "function") throw new TypeError(what + " is not iterable");
1555
+ const out = [];
1556
+ for (const item of { [Symbol.iterator]: () => method.call(v) }) {
1557
+ if (!isObjectLike(item)) throw new TypeError(what + " contains a value that is not an object");
1558
+ out.push(item);
1559
+ }
1560
+ return out;
1561
+ }
1562
+
1563
+ // WebIDL StructuredSerializeOptions (and its WindowPostMessageOptions
1564
+ // extension): members read in order, inherited dictionaries first.
1565
+ function toSerializeOptions(v, withTargetOrigin) {
1566
+ const out = { transfer: [] };
1567
+ if (withTargetOrigin) out.targetOrigin = "/";
1568
+ if (v === undefined || v === null) return out;
1569
+ if (!isObjectLike(v)) throw new TypeError("The options argument is not an object");
1570
+ const transfer = v.transfer;
1571
+ if (transfer !== undefined) out.transfer = toObjectSequence(transfer, "transfer");
1572
+ if (withTargetOrigin) {
1573
+ const targetOrigin = v.targetOrigin;
1574
+ if (targetOrigin !== undefined) out.targetOrigin = toUSVString(targetOrigin);
1575
+ }
1576
+ return out;
1577
+ }
1578
+
1579
+ function structuredSerializeWithTransfer(value, transferList) {
1580
+ const memory = new Map();
1581
+ for (const transferable of transferList) {
1582
+ const buffer = isArrayBuffer(transferable);
1583
+ if (!buffer && hostTransferState(transferable) == null) {
1584
+ throw dataCloneError("The object is not transferable");
1585
+ }
1586
+ if (!buffer && isSharedArrayBuffer(transferable)) throw dataCloneError("A SharedArrayBuffer is not transferable");
1587
+ if (memory.has(transferable)) throw dataCloneError("The transfer list contains the same object twice");
1588
+ memory.set(transferable, { type: undefined });
1589
+ }
1590
+ const serialized = structuredSerializeInternal(value, false, memory);
1591
+ const transferDataHolders = [];
1592
+ for (const transferable of transferList) {
1593
+ const holder = memory.get(transferable);
1594
+ if (isArrayBuffer(transferable)) {
1595
+ if (isDetachedBuffer(transferable)) throw dataCloneError("A detached ArrayBuffer could not be transferred");
1596
+ } else if (hostTransferState(transferable) === "detached") {
1597
+ throw dataCloneError("A detached " + primaryInterfaceOf(transferable) + " could not be transferred");
1598
+ }
1599
+ }
1600
+ for (const transferable of transferList) {
1601
+ const holder = memory.get(transferable);
1602
+ if (isArrayBuffer(transferable)) {
1603
+ holder.type = "TransferredArrayBuffer";
1604
+ holder.buffer = SC.abTransfer.call(transferable);
1605
+ } else {
1606
+ holder.type = "TransferredPlatform";
1607
+ holder.interface = primaryInterfaceOf(transferable);
1608
+ holder.value = rehydrate(__rb_host_transfer(proxyHandles.get(transferable)));
1609
+ }
1610
+ transferDataHolders.push(holder);
1611
+ }
1612
+ return { serialized, transferDataHolders };
1613
+ }
1614
+
1615
+ // -> { deserialized, transferredValues }
1616
+ function structuredDeserializeWithTransfer(record) {
1617
+ const memory = new Map();
1618
+ const transferredValues = [];
1619
+ for (const holder of record.transferDataHolders) {
1620
+ const value = holder.type === "TransferredArrayBuffer" ? holder.buffer : holder.value;
1621
+ memory.set(holder, value);
1622
+ transferredValues.push(value);
1623
+ }
1624
+ return { deserialized: structuredDeserialize(record.serialized, memory), transferredValues };
1625
+ }
1626
+
1627
+ // Serialized records Ruby holds by id (Dommy::Js::SerializedRecord). An entry
1628
+ // lives until Ruby releases it.
1629
+ const serializedRecords = new Map();
1630
+ let serializedRecordSeq = 0;
1631
+ function serializedTag(record) {
1632
+ const id = ++serializedRecordSeq;
1633
+ serializedRecords.set(id, record);
1634
+ return { __rb_serialized: id };
1635
+ }
1636
+ // Called from Ruby when a message is delivered: the record deserialized in
1637
+ // this realm, as `{ value, ports }` (the MessagePorts among the transferred
1638
+ // values, in order), or `{ error }` when deserialization threw — the caller
1639
+ // then fires `messageerror`.
1640
+ function deserializeRecord(id) {
1641
+ const record = serializedRecords.get(id);
1642
+ if (!record) return { error: "The serialized message is gone" };
1643
+ try {
1644
+ const { deserialized, transferredValues } = structuredDeserializeWithTransfer(record);
1645
+ const ports = transferredValues.filter((v) => isProxy(v) && primaryInterfaceOf(v) === "MessagePort");
1646
+ return { value: dehydrateSettle(deserialized), ports: ports.map((p) => ({ __rb_handle: proxyHandles.get(p) })) };
1647
+ } catch (e) {
1648
+ return { error: String(e && e.message) };
1649
+ }
1650
+ }
1651
+ function releaseRecord(id) {
1652
+ serializedRecords.delete(id);
1653
+ }
1654
+
1655
+ // The `structuredClone(value, options)` method steps, entirely in this realm.
1656
+ function structuredCloneSteps(value, options) {
1657
+ const { transfer } = toSerializeOptions(options, false);
1658
+ const record = structuredSerializeWithTransfer(value, transfer);
1659
+ return structuredDeserializeWithTransfer(record).deserialized;
1660
+ }
1661
+
1662
+ // The targetOrigin argument of window.postMessage: "/" (the incumbent's own
1663
+ // origin) and "*" pass through; anything else must parse as a URL, whose
1664
+ // origin it then stands for.
1665
+ function postMessageTargetOrigin(targetOrigin) {
1666
+ if (targetOrigin === "/" || targetOrigin === "*") return targetOrigin;
1667
+ let parsed;
1668
+ try {
1669
+ parsed = new globalThis.URL(targetOrigin);
1670
+ } catch (_) {
1671
+ throw makeHostError({ name: "SyntaxError", message: "'" + targetOrigin + "' is not a valid target origin" });
1672
+ }
1673
+ return parsed.origin;
1674
+ }
1675
+
1676
+ // window.postMessage(message, targetOrigin, transfer) /
1677
+ // postMessage(message, options): the overload is picked by the second
1678
+ // argument (WebIDL overload resolution: undefined, null or an object selects
1679
+ // the dictionary).
1680
+ function windowPostMessageStub(prop, ctx) {
1681
+ const { handle, ifaceName } = ctx;
1682
+ return function (message) {
1683
+ if (arguments.length < 1) throw new TypeError("postMessage requires at least 1 argument");
1684
+ const rest = Array.prototype.slice.call(arguments, 1);
1685
+ let targetOrigin, transfer;
1686
+ const second = rest[0];
1687
+ if (rest.length === 0 || second === undefined || second === null || isObjectLike(second)) {
1688
+ ({ targetOrigin, transfer } = toSerializeOptions(second, true));
1689
+ } else {
1690
+ targetOrigin = toUSVString(second);
1691
+ transfer = rest.length > 1 && rest[1] !== undefined ? toObjectSequence(rest[1], "transfer") : [];
1692
+ }
1693
+ targetOrigin = postMessageTargetOrigin(targetOrigin);
1694
+ const record = structuredSerializeWithTransfer(message, transfer);
1695
+ const source = globalThis.window;
1696
+ return hostCallResult(prop, __rb_host_call(handle, prop,
1697
+ [serializedTag(record), targetOrigin, isProxy(source) ? { __rb_handle: proxyHandles.get(source) } : null]), ifaceName);
1698
+ };
1699
+ }
1700
+
1701
+ // MessagePort#postMessage(message, transfer) / (message, options).
1702
+ function portPostMessageStub(prop, ctx) {
1703
+ const { handle, ifaceName } = ctx;
1704
+ return function (message) {
1705
+ if (arguments.length < 1) throw new TypeError("postMessage requires at least 1 argument");
1706
+ const rest = Array.prototype.slice.call(arguments, 1);
1707
+ const second = rest[0];
1708
+ let transfer;
1709
+ if (rest.length === 0 || second === undefined || second === null || !isObjectLike(second) ||
1710
+ typeof second[Symbol.iterator] !== "function") {
1711
+ ({ transfer } = toSerializeOptions(second, false));
1712
+ } else {
1713
+ transfer = toObjectSequence(second, "transfer");
1714
+ }
1715
+ // "If transfer contains this, throw a DataCloneError."
1716
+ if (transfer.some((t) => isProxy(t) && proxyHandles.get(t) === handle)) {
1717
+ throw dataCloneError("A MessagePort cannot transfer itself");
1718
+ }
1719
+ // Posting the target port itself dooms the channel: the message is
1720
+ // serialized (and everything transferred) but never delivered.
1721
+ const target = rehydrate(__rb_host_state(handle, "entangled"));
1722
+ const doomed = target != null && transfer.includes(target);
1723
+ const record = structuredSerializeWithTransfer(message, transfer);
1724
+ return hostCallResult(prop, __rb_host_call(handle, prop, [serializedTag(record), doomed]), ifaceName);
1725
+ };
1726
+ }
1727
+
1728
+ // BroadcastChannel#postMessage(message): StructuredSerialize, no transfer.
1729
+ // The closed check comes first, so it is the host's to make before the
1730
+ // record is built — it answers through `closed`.
1731
+ function broadcastPostMessageStub(prop, ctx) {
1732
+ const { handle, ifaceName } = ctx;
1733
+ return function (message) {
1734
+ if (arguments.length < 1) throw new TypeError("postMessage requires at least 1 argument");
1735
+ if (__rb_host_state(handle, "closed") === true) {
1736
+ throw makeHostError({ name: "InvalidStateError", message: "The BroadcastChannel is closed" });
1737
+ }
1738
+ const record = { serialized: structuredSerializeInternal(message, false, new Map()), transferDataHolders: [] };
1739
+ return hostCallResult(prop, __rb_host_call(handle, prop, [serializedTag(record)]), ifaceName);
1740
+ };
1741
+ }
1742
+
1743
+ // Worker#postMessage: the message is serialized (and transferred) here, so a
1744
+ // throwing getter or an uncloneable value throws at the call; the emulated
1745
+ // worker side is Ruby, which receives the deserialized clone as plain data.
1746
+ function workerPostMessageStub(prop, ctx) {
1747
+ const { handle, ifaceName } = ctx;
1748
+ return function (message) {
1749
+ if (arguments.length < 1) throw new TypeError("postMessage requires at least 1 argument");
1750
+ const rest = Array.prototype.slice.call(arguments, 1);
1751
+ const second = rest[0];
1752
+ let transfer;
1753
+ if (rest.length === 0 || second === undefined || second === null || !isObjectLike(second) ||
1754
+ typeof second[Symbol.iterator] !== "function") {
1755
+ ({ transfer } = toSerializeOptions(second, false));
1756
+ } else {
1757
+ transfer = toObjectSequence(second, "transfer");
1758
+ }
1759
+ const clone = structuredDeserializeWithTransfer(structuredSerializeWithTransfer(message, transfer)).deserialized;
1760
+ return hostCallResult(prop, __rb_host_call(handle, prop, dehydrateArgs([clone])), ifaceName);
1761
+ };
1762
+ }
1763
+
1764
+ const POST_MESSAGE_STUBS = {
1765
+ Window: windowPostMessageStub,
1766
+ MessagePort: portPostMessageStub,
1767
+ BroadcastChannel: broadcastPostMessageStub,
1768
+ Worker: workerPostMessageStub,
1769
+ };
1770
+ function postMessageStub(prop, ctx) {
1771
+ const make = POST_MESSAGE_STUBS[ctx.ifaceName];
1772
+ return make ? make(prop, ctx) : null;
1773
+ }
1774
+
1775
+ function structuredCloneStub(_prop, ctx) {
1776
+ if (ctx.ifaceName !== "Window") return null;
1777
+ return function structuredClone(value, options) {
1778
+ if (arguments.length < 1) throw new TypeError("structuredClone requires at least 1 argument");
1779
+ return structuredCloneSteps(value, options);
1780
+ };
1781
+ }
1782
+
1783
+ // history.pushState / replaceState(data, unused, url): the state is
1784
+ // serialized for storage here — after the fully-active check, before the
1785
+ // host looks at the URL (a DataCloneError wins over a SecurityError). The
1786
+ // string arguments arrive already converted (withConvertedArguments).
1787
+ function historyStateStub(prop, ctx) {
1788
+ if (ctx.ifaceName !== "History") return null;
1789
+ const { handle, ifaceName } = ctx;
1790
+ return function (data, ...rest) {
1791
+ if (__rb_host_state(handle, "fully_active") === false) {
1792
+ throw makeHostError({ name: "SecurityError", message: "The document is not fully active" });
1793
+ }
1794
+ const record = { serialized: structuredSerializeInternal(data, true, new Map()), transferDataHolders: [] };
1795
+ bumpDomEpoch();
1796
+ try {
1797
+ return hostCallResult(prop, __rb_host_call(handle, prop, [serializedTag(record), ...dehydrateArgs(rest)]), ifaceName);
1798
+ } finally {
1799
+ bumpDomEpoch();
1800
+ }
1801
+ };
1802
+ }
1803
+
879
1804
  // ===== wasm host bridge (handle-oriented JS access) =====
880
1805
  //
881
1806
  // A second embedding model, distinct from the Proxy-based one above: a wasm
@@ -910,12 +1835,13 @@ globalThis.__rbHost = (function () {
910
1835
  if ("__rb_js_ref" in v) return jsRefs.get(v.__rb_js_ref);
911
1836
  if (v.__rb_bytes) return new Uint8Array(v.__rb_bytes);
912
1837
  if (v.__rb_arraybuffer) return new Uint8Array(v.__rb_arraybuffer).buffer;
1838
+ if ("__rb_date" in v) return new Date(v.__rb_date);
913
1839
  if ("__rb_handle" in v) {
914
1840
  // A dispatch-in-flight host twin resolves to its JS event, so a
915
1841
  // listener's argument IS the object the caller constructed.
916
1842
  const jsEvent = jsEventByHandle.get(v.__rb_handle);
917
1843
  if (jsEvent !== undefined) return jsEvent;
918
- return makeProxy(v.__rb_handle, v.__rb_if, v.__rb_ce);
1844
+ return makeProxy(v.__rb_handle, v.__rb_if);
919
1845
  }
920
1846
  const out = {};
921
1847
  for (const k of Object.keys(v)) out[k] = wasmUntag(v[k]);
@@ -951,15 +1877,22 @@ globalThis.__rbHost = (function () {
951
1877
  // `with` is skipped for a "use strict" body (where it is illegal). The
952
1878
  // completion value is voided so a trailing expression never trips the
953
1879
  // unawaited-Promise guard.
1880
+ // A throw (a compile error included) comes back tagged, as a callback's
1881
+ // does, so the Ruby side reports the very value the script threw.
954
1882
  function runScript(src) {
955
1883
  bumpDomEpoch(); // Ruby -> JS entry: see invokeCallback
956
1884
  const body = String(src);
957
1885
  const strict = /^\s*(["'])use strict\1/.test(body);
958
- if (!strict && typeof globalThis.window !== "undefined" && globalThis.window !== globalThis) {
959
- indirectEval("with (globalThis.window) {\n" + body + "\n}\n;void 0;");
960
- } else {
961
- indirectEval(body + "\n;void 0;");
1886
+ try {
1887
+ if (!strict && typeof globalThis.window !== "undefined" && globalThis.window !== globalThis) {
1888
+ indirectEval("with (globalThis.window) {\n" + body + "\n}\n;void 0;");
1889
+ } else {
1890
+ indirectEval(body + "\n;void 0;");
1891
+ }
1892
+ } catch (e) {
1893
+ return tagThrow(e);
962
1894
  }
1895
+ return undefined;
963
1896
  }
964
1897
 
965
1898
  function wasmGet(ref, prop) { return wasmTag(wasmDeref(ref)[prop]); }
@@ -1026,12 +1959,22 @@ globalThis.__rbHost = (function () {
1026
1959
  // constructor by interface name; null means "not constructable" so we throw.
1027
1960
  // WebIDL dictionary members for the constructors that take an init dictionary,
1028
1961
  // in the order the spec reads them (inherited members first, then own, each
1029
- // group lexicographic). "boolean" members are coerced with JS ToBoolean; "any"
1030
- // is passed through. Only interfaces with a COMPLETE member list belong here —
1962
+ // group lexicographic). "boolean" members are coerced with JS ToBoolean,
1963
+ // "DOMString" ones with ToString (a throwing toString propagates); "any" is
1964
+ // passed through. Only interfaces with a COMPLETE member list belong here —
1031
1965
  // a partial list would silently drop members.
1032
1966
  const CONSTRUCTOR_DICTS = {
1033
1967
  Event: { bubbles: "boolean", cancelable: "boolean", composed: "boolean" },
1034
1968
  CustomEvent: { bubbles: "boolean", cancelable: "boolean", composed: "boolean", detail: "any" },
1969
+ // `source` is an `Element?`, which Ruby checks.
1970
+ ToggleEvent: {
1971
+ bubbles: "boolean", cancelable: "boolean", composed: "boolean",
1972
+ newState: "DOMString", oldState: "DOMString", source: "any",
1973
+ },
1974
+ CommandEvent: {
1975
+ bubbles: "boolean", cancelable: "boolean", composed: "boolean",
1976
+ command: "DOMString", source: "any",
1977
+ },
1035
1978
  };
1036
1979
 
1037
1980
  // WebIDL argument coercion for a constructor that takes `(DOMString type,
@@ -1120,16 +2063,71 @@ globalThis.__rbHost = (function () {
1120
2063
  return [norm, { type: options.type }];
1121
2064
  }
1122
2065
  if (name === "URLSearchParams") {
1123
- // Per spec a non-string iterable init (another URLSearchParams, a Map, an
1124
- // object with a custom @@iterator) is a *sequence* of pairs — materialize
1125
- // it through its live iterator HERE so the iterator runs JS-side; Ruby only
1126
- // ever sees plain pair arrays. Plain records (no @@iterator) and strings
1127
- // fall through unchanged to the record / string paths.
2066
+ // The init argument is `optional (sequence<sequence<USVString>> or
2067
+ // record<USVString, USVString> or USVString) init = ""`, converted here
2068
+ // per WebIDL so iterators and getters run JS-side and Ruby only ever sees
2069
+ // a string or an array of pairs of strings (a record's keys never travel
2070
+ // as Ruby hash keys, which would cut a key at a NUL).
2071
+ // https://webidl.spec.whatwg.org/#es-union
2072
+ const fail = (what) => new TypeError(
2073
+ "Failed to construct 'URLSearchParams': The provided value cannot be converted to " + what + ".");
2074
+ // "Create a sequence from an iterable", given the @@iterator method
2075
+ // already read: GetIteratorFromMethod, then IteratorStepValue to the end.
2076
+ const fromIterable = (iterable, method, convert, what) => {
2077
+ const iterator = method.call(iterable);
2078
+ if (iterator === null || (typeof iterator !== "object" && typeof iterator !== "function")) throw fail(what);
2079
+ const next = iterator.next;
2080
+ const items = [];
2081
+ for (;;) {
2082
+ const step = next.call(iterator);
2083
+ if (step === null || (typeof step !== "object" && typeof step !== "function")) throw fail(what);
2084
+ if (step.done) return items;
2085
+ items.push(convert(step.value));
2086
+ }
2087
+ };
2088
+ // GetMethod(V, @@iterator): undefined/null mean none; anything else must
2089
+ // be callable.
2090
+ const iteratorMethod = (v, what) => {
2091
+ const method = v[Symbol.iterator];
2092
+ if (method === undefined || method === null) return undefined;
2093
+ if (typeof method !== "function") throw fail(what);
2094
+ return method;
2095
+ };
2096
+ const isObject = (v) => v !== null && (typeof v === "object" || typeof v === "function");
2097
+
2098
+ // An omitted or undefined argument takes the default "". Any other
2099
+ // non-object, null included, is the USVString member.
2100
+ if (args.length === 0 || args[0] === undefined) return [""];
1128
2101
  const init = args[0];
1129
- if (init !== null && typeof init === "object" && typeof init[Symbol.iterator] === "function") {
1130
- return [Array.from(init, (pair) => Array.from(pair))];
2102
+ if (!isObject(init)) return [toUSVString(init)];
2103
+
2104
+ // An object with an @@iterator method is the sequence member: each
2105
+ // element is itself a sequence<USVString>, so it must be an object with
2106
+ // an @@iterator method too. (The URLSearchParams constructor, in Ruby,
2107
+ // then requires each pair to have exactly two items.)
2108
+ const method = iteratorMethod(init, "a sequence");
2109
+ if (method !== undefined) {
2110
+ return [fromIterable(init, method, (pair) => {
2111
+ if (!isObject(pair)) throw fail("a sequence");
2112
+ const pairMethod = iteratorMethod(pair, "a sequence");
2113
+ if (pairMethod === undefined) throw fail("a sequence");
2114
+ return fromIterable(pair, pairMethod, toUSVString, "a sequence");
2115
+ }, "a sequence")];
1131
2116
  }
1132
- return args;
2117
+
2118
+ // Any other object, a function included (`new URLSearchParams(DOMException)`),
2119
+ // is the record member: its own enumerable keys in [[OwnPropertyKeys]]
2120
+ // order, each key and value a USVString, a later key equal to an earlier
2121
+ // one after conversion overwriting its value in place.
2122
+ // https://webidl.spec.whatwg.org/#es-record
2123
+ const record = new Map();
2124
+ for (const key of Reflect.ownKeys(init)) {
2125
+ const desc = Reflect.getOwnPropertyDescriptor(init, key);
2126
+ if (desc === undefined || !desc.enumerable) continue;
2127
+ const typedKey = toUSVString(key);
2128
+ record.set(typedKey, toUSVString(init[key]));
2129
+ }
2130
+ return [Array.from(record)];
1133
2131
  }
1134
2132
  const members = CONSTRUCTOR_DICTS[name];
1135
2133
  if (!members) return args;
@@ -1143,7 +2141,8 @@ globalThis.__rbHost = (function () {
1143
2141
  for (const member in members) {
1144
2142
  const value = init[member];
1145
2143
  if (value === undefined) continue;
1146
- dict[member] = members[member] === "boolean" ? !!value : value;
2144
+ const kind = members[member];
2145
+ dict[member] = kind === "boolean" ? !!value : kind === "DOMString" ? String(value) : value;
1147
2146
  }
1148
2147
  }
1149
2148
  return [type, dict];
@@ -1259,7 +2258,7 @@ globalThis.__rbHost = (function () {
1259
2258
  function jsEventProtoFor(name) {
1260
2259
  let proto = jsEventProtoByName.get(name);
1261
2260
  if (proto) return proto;
1262
- proto = Object.create(protos.get(name));
2261
+ proto = Object.create(protoNamed(name));
1263
2262
  defineJsEventMembers(proto, name);
1264
2263
  jsEventProtoByName.set(name, proto);
1265
2264
  return proto;
@@ -1287,7 +2286,9 @@ globalThis.__rbHost = (function () {
1287
2286
  return ev;
1288
2287
  }
1289
2288
 
1290
- function constructInterface(name, args) {
2289
+ function constructInterface(name, rawArgs) {
2290
+ const call = declaredConversion(name, "constructor");
2291
+ const args = call ? convertArguments(call, rawArgs) : rawArgs;
1291
2292
  if (name === "Event" || name === "CustomEvent") {
1292
2293
  const coerced = coerceConstructorArgs(name, args);
1293
2294
  return makeJsEvent(name, coerced[0], coerced[1]);
@@ -1297,6 +2298,72 @@ globalThis.__rbHost = (function () {
1297
2298
  return r;
1298
2299
  }
1299
2300
 
2301
+ // ===== iterable<K, V> (WebIDL §3.7.9) =====
2302
+ //
2303
+ // A pair iterable's prototype gets entries, keys, values and forEach, and an
2304
+ // @@iterator that is the entries function itself. Each of the three returns
2305
+ // a default iterator object: it inherits from the interface's iterator
2306
+ // prototype (whose own [[Prototype]] is %IteratorPrototype%, so iterator
2307
+ // helpers reach it), and its `next` re-reads the object's value pairs every
2308
+ // step, so a change made while iterating is seen — `for (const [k] of params)
2309
+ // params.delete(...)` observes the deletion. The pairs are read straight
2310
+ // from the host's `entries`.
2311
+ const ITERATOR_PROTOTYPE = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
2312
+ const pairIteratorState = new WeakMap(); // iterator -> { target, kind, index, iface }
2313
+
2314
+ function hostValuePairs(target) {
2315
+ const pairs = rehydrate(__rb_host_call(target[HKEY], "entries", dehydrateArgs([])));
2316
+ return Array.isArray(pairs) ? pairs : [];
2317
+ }
2318
+
2319
+ function installPairIterable(proto, iface) {
2320
+ const iteratorProto = Object.create(ITERATOR_PROTOTYPE);
2321
+ const next = {
2322
+ next() {
2323
+ const state = pairIteratorState.get(this);
2324
+ if (!state || state.iface !== iface) {
2325
+ throw new TypeError("Illegal invocation: next called on an object that is not a " + iface + " Iterator");
2326
+ }
2327
+ const pairs = hostValuePairs(state.target);
2328
+ if (state.index >= pairs.length) return { value: undefined, done: true };
2329
+ const pair = pairs[state.index++];
2330
+ const value = state.kind === "key" ? pair[0] : state.kind === "value" ? pair[1] : [pair[0], pair[1]];
2331
+ return { value, done: false };
2332
+ },
2333
+ }.next;
2334
+ Object.defineProperty(iteratorProto, "next", { value: next, writable: true, enumerable: true, configurable: true });
2335
+ Object.defineProperty(iteratorProto, Symbol.toStringTag, { value: iface + " Iterator", configurable: true });
2336
+
2337
+ const operation = (opName, length, fn) => {
2338
+ Object.defineProperty(fn, "name", { value: opName, configurable: true });
2339
+ Object.defineProperty(fn, "length", { value: length, configurable: true });
2340
+ Object.defineProperty(proto, opName, { value: fn, writable: true, enumerable: true, configurable: true });
2341
+ return fn;
2342
+ };
2343
+ const iteratorOf = (opName, kind) => operation(opName, 0, function () {
2344
+ checkReceiver(this, iface, opName);
2345
+ const iterator = Object.create(iteratorProto);
2346
+ pairIteratorState.set(iterator, { target: this, kind, index: 0, iface });
2347
+ return iterator;
2348
+ });
2349
+ const entries = iteratorOf("entries", "key+value");
2350
+ iteratorOf("keys", "key");
2351
+ iteratorOf("values", "value");
2352
+ operation("forEach", 1, function (callback, thisArg) {
2353
+ checkReceiver(this, iface, "forEach");
2354
+ if (typeof callback !== "function") {
2355
+ throw new TypeError("Failed to execute 'forEach' on '" + iface + "': The callback provided as parameter 1 is not a function.");
2356
+ }
2357
+ // The pairs are re-read after every call: the callback may change them.
2358
+ let pairs = hostValuePairs(this);
2359
+ for (let i = 0; i < pairs.length; i++) {
2360
+ callback.call(thisArg, pairs[i][1], pairs[i][0], this);
2361
+ pairs = hostValuePairs(this);
2362
+ }
2363
+ });
2364
+ Object.defineProperty(proto, Symbol.iterator, { value: entries, writable: true, enumerable: false, configurable: true });
2365
+ }
2366
+
1300
2367
  // 1b: lazily build a JS prototype chain + constructor per DOM interface,
1301
2368
  // mirroring the chain Ruby reports (most-derived first). Cached by name so the
1302
2369
  // shared tail (…Element→Node→EventTarget) is built once and every node links
@@ -1304,6 +2371,21 @@ globalThis.__rbHost = (function () {
1304
2371
  // (via Symbol.toStringTag) work. Constructable interfaces (Event, DOMException,
1305
2372
  // …) build via Ruby; the rest throw Illegal constructor (HTMLElement until 1d).
1306
2373
  const protos = new Map();
2374
+ // Interfaces seeded lazily (seedInterfaces): name -> the chain from it up,
2375
+ // until something first needs it. lazyGlobals holds the names whose global
2376
+ // is still the building accessor (a page assignment replaces it).
2377
+ const lazyChains = new Map();
2378
+ const lazyGlobals = new Set();
2379
+ // Every seeded interface's static method names, once the window is bound
2380
+ // (attachStatics); until then null.
2381
+ let staticNames = null;
2382
+ // The interface's prototype, building it (and its chain) on first use.
2383
+ function protoNamed(name) {
2384
+ const proto = protos.get(name);
2385
+ if (proto) return proto;
2386
+ const chain = lazyChains.get(name);
2387
+ return chain ? protoForChain(chain, 0) : undefined;
2388
+ }
1307
2389
  // Full per-interface descriptor (name + prototype chain + method names) keyed
1308
2390
  // by interface name. A handle that crosses tagged with its interface (see the
1309
2391
  // marshaller) reuses this instead of a `__rb_host_describe` round trip; the
@@ -1313,50 +2395,21 @@ globalThis.__rbHost = (function () {
1313
2395
  const name = chain[i];
1314
2396
  const cached = protos.get(name);
1315
2397
  if (cached) return cached;
1316
- const parent = (i + 1 < chain.length) ? protoForChain(chain, i + 1) : Object.prototype;
2398
+ // WebIDL §3.14.1: the DOMException prototype object's [[Prototype]] is
2399
+ // %Error.prototype% (so `e instanceof Error`, and String(e) is Error's
2400
+ // "name: message"); every other root interface's is %Object.prototype%.
2401
+ const root = name === "DOMException" ? Error.prototype : Object.prototype;
2402
+ const parent = (i + 1 < chain.length) ? protoForChain(chain, i + 1) : root;
1317
2403
  const proto = Object.create(parent);
1318
2404
  Object.defineProperty(proto, Symbol.toStringTag, { value: name, configurable: true });
1319
- // Only node/element constructors adopt an element being upgraded. Otherwise
1320
- // a non-element `new` (e.g. `new IntersectionObserver()` inside a custom
1321
- // element's constructor) would greedily adopt the queued element off the
1322
- // shared construction stack and hijack its prototype.
1323
- const consultsStack = chain.includes("Node");
1324
- const ctor = function (...args) {
2405
+ let ctor = function (...args) {
1325
2406
  const nt = new.target;
1326
2407
  if (nt === undefined) throw new TypeError(name + " requires 'new'");
1327
- // 1d: custom element upgrade — when a construction is queued, `super()`
1328
- // adopts the element being upgraded (its proxy) and stamps it with the
1329
- // derived class's prototype, rather than minting a new backing object.
1330
- if (consultsStack && constructionStack.length > 0) {
1331
- const el = constructionStack[constructionStack.length - 1];
1332
- Object.setPrototypeOf(el, nt.prototype);
1333
- return el;
1334
- }
1335
- // 1d: direct `new MyElement()` (no queued upgrade) — the HTMLElement
1336
- // constructor algorithm. When new.target is a registered custom element
1337
- // constructor, mint its backing Dommy element now (autonomous custom
1338
- // element construction), adopt the proxy WITHOUT re-running this ctor, and
1339
- // stamp it with the derived prototype. An unregistered new.target (bare
1340
- // `new HTMLElement()` / an unregistered subclass) falls through to Ruby,
1341
- // which returns null → "Illegal constructor", per spec.
1342
- // Autonomous custom element construction runs only in the HTMLElement base
1343
- // ctor: an element's super() chain reaches here iff it `extends HTMLElement`.
1344
- // A class that extends a built-in interface instead (HTMLParagraphElement,
1345
- // HTMLButtonElement, …) reaches THAT ctor's name, misses this branch, and
1346
- // falls through to Ruby → TypeError (Dommy has no customized built-ins).
1347
- // `nt !== ctor` additionally rejects `new HTMLElement()` itself (even when
1348
- // HTMLElement was passed to customElements.define): only a user subclass as
1349
- // new.target may construct.
1350
- if (name === "HTMLElement" && nt !== ctor) {
1351
- const ceName = ceNameForCtor(nt);
1352
- if (ceName !== undefined) {
1353
- const wire = __rb_create_custom_element(ceName);
1354
- if (wire && typeof wire === "object" && "__rb_handle" in wire) {
1355
- const p = makeProxy(wire.__rb_handle, wire.__rb_if, wire.__rb_ce, true);
1356
- Object.setPrototypeOf(p, nt.prototype);
1357
- return p;
1358
- }
1359
- }
2408
+ // HTML element constructors ([HTMLConstructor]): a custom element's
2409
+ // `super()` reaches here with its class as NewTarget.
2410
+ if (nt !== ctor && name.startsWith("HTML") && name.endsWith("Element")) {
2411
+ const built = constructCustomElement(name, nt);
2412
+ if (built !== undefined) return built;
1360
2413
  }
1361
2414
  const built = constructInterface(name, args);
1362
2415
  // A JS subclass (`class Foo extends Event {}` / `extends EventTarget`)
@@ -1382,6 +2435,7 @@ globalThis.__rbHost = (function () {
1382
2435
  const ctorArity = CONSTRUCTOR_ARITY[name];
1383
2436
  if (ctorArity !== undefined) Object.defineProperty(ctor, "length", { value: ctorArity, configurable: true });
1384
2437
  ctor.prototype = proto;
2438
+ if (isHTMLElementInterface(name)) ctor = htmlElementConstructor(ctor, name);
1385
2439
  Object.defineProperty(proto, "constructor", { value: ctor, configurable: true, writable: true });
1386
2440
  // [Unscopable] members -> a null-prototyped @@unscopables object on the
1387
2441
  // prototype (WebIDL: configurable, non-writable, non-enumerable).
@@ -1423,39 +2477,9 @@ globalThis.__rbHost = (function () {
1423
2477
  define("forEach", A.forEach);
1424
2478
  }
1425
2479
  } else if (ENTRIES_ITERABLES.has(name)) {
1426
- // A LIVE iterator: re-read entries() at each step (indexed by a running
1427
- // cursor) so a mutation mid-loop is observed — e.g. URLSearchParams
1428
- // `for (const e of params) { params.delete(...) }` must see the new state.
1429
- // entries()/keys()/values()/@@iterator each return such an iterator (the
1430
- // WebIDL maplike contract) — a `for…of` and a direct `.entries().next()`
1431
- // both work — rather than a plain Array. keys/values project the pair.
1432
- // Read the raw [name, value] pairs straight from the host — NOT via
1433
- // `self.entries()`, which is now this same iterator-returning override.
1434
- const rawEntries = (self) => {
1435
- const r = rehydrate(__rb_host_call(self[HKEY], "entries", dehydrateArgs([])));
1436
- return Array.isArray(r) ? r : [];
1437
- };
1438
- const liveIterator = (self, project) => {
1439
- let i = 0;
1440
- const it = {
1441
- next() {
1442
- const entries = rawEntries(self);
1443
- if (i >= entries.length) return { value: undefined, done: true };
1444
- return { value: project(entries[i++]), done: false };
1445
- },
1446
- };
1447
- it[Symbol.iterator] = function () { return this; };
1448
- return it;
1449
- };
1450
- const defineIter = (key, project) => Object.defineProperty(proto, key, {
1451
- value: function () { return liveIterator(this, project); },
1452
- configurable: true, writable: true,
1453
- });
1454
- defineIter(Symbol.iterator, (e) => e);
1455
- defineIter("entries", (e) => e);
1456
- defineIter("keys", (e) => e[0]);
1457
- defineIter("values", (e) => e[1]);
2480
+ installPairIterable(proto, name);
1458
2481
  }
2482
+ if (name === "ElementInternals") installElementInternalsStates(proto);
1459
2483
  if (name === "TextEncoder") {
1460
2484
  // encodeInto mutates the destination Uint8Array in place, so it must run
1461
2485
  // JS-side (a host round trip would only see a copy). Encodes scalar values
@@ -1543,18 +2567,30 @@ globalThis.__rbHost = (function () {
1543
2567
  });
1544
2568
  }
1545
2569
  }
2570
+ // The getter is the attribute's own, so like any WebIDL attribute getter
2571
+ // it checks its receiver: one that does not implement the interface — the
2572
+ // prototype itself, say — is a TypeError, not a host read of nothing.
1546
2573
  const readonlyAttrs = READONLY_ATTRS[name];
1547
2574
  if (readonlyAttrs) {
1548
2575
  for (const field of readonlyAttrs) {
1549
2576
  Object.defineProperty(proto, field, {
1550
2577
  configurable: true,
1551
2578
  enumerable: true,
1552
- get() { return rehydrate(__rb_host_get(this[HKEY], field)); },
2579
+ get() {
2580
+ checkReceiver(this, name, field);
2581
+ return rehydrate(__rb_host_get(this[HKEY], field));
2582
+ },
1553
2583
  });
1554
2584
  }
1555
2585
  }
1556
- if (!(name in globalThis)) globalThis[name] = ctor;
2586
+ lazyChains.delete(name);
2587
+ if (lazyGlobals.delete(name)) {
2588
+ Object.defineProperty(globalThis, name, { value: ctor, writable: true, enumerable: true, configurable: true });
2589
+ } else if (!(name in globalThis)) {
2590
+ globalThis[name] = ctor;
2591
+ }
1557
2592
  protos.set(name, proto);
2593
+ if (staticNames !== null) attachStaticsTo(name, ctor, staticNames[name]);
1558
2594
  return proto;
1559
2595
  }
1560
2596
 
@@ -1565,43 +2601,92 @@ globalThis.__rbHost = (function () {
1565
2601
  // to Ruby (which builds the actual <img>/<audio>/<option> element).
1566
2602
  const NAMED_CONSTRUCTORS = { Image: "HTMLImageElement", Audio: "HTMLAudioElement", Option: "HTMLOptionElement" };
1567
2603
 
2604
+ function namedConstructor(alias) {
2605
+ const proto = protoNamed(NAMED_CONSTRUCTORS[alias]);
2606
+ if (!proto) return undefined;
2607
+ const ctor = function (...args) {
2608
+ if (new.target === undefined) throw new TypeError(alias + " requires 'new'");
2609
+ return constructInterface(alias, args);
2610
+ };
2611
+ Object.defineProperty(ctor, "name", { value: alias, configurable: true });
2612
+ // Share the interface prototype (so `new Image() instanceof HTMLImageElement`)
2613
+ // as a non-writable/enumerable/configurable own property, per WebIDL — a
2614
+ // constructor's `prototype` is not writable.
2615
+ Object.defineProperty(ctor, "prototype", { value: proto, writable: false, enumerable: false, configurable: false });
2616
+ return ctor;
2617
+ }
2618
+
1568
2619
  function exposeNamedConstructors() {
1569
2620
  for (const alias in NAMED_CONSTRUCTORS) {
1570
- if (alias in globalThis) continue;
1571
- const proto = protos.get(NAMED_CONSTRUCTORS[alias]);
1572
- if (!proto) continue;
1573
- const ctor = function (...args) {
1574
- if (new.target === undefined) throw new TypeError(alias + " requires 'new'");
1575
- return constructInterface(alias, args);
1576
- };
1577
- Object.defineProperty(ctor, "name", { value: alias, configurable: true });
1578
- // Share the interface prototype (so `new Image() instanceof HTMLImageElement`)
1579
- // as a non-writable/enumerable/configurable own property, per WebIDL — a
1580
- // constructor's `prototype` is not writable.
1581
- Object.defineProperty(ctor, "prototype", { value: proto, writable: false, enumerable: false, configurable: false });
1582
- globalThis[alias] = ctor;
2621
+ if (alias in globalThis || !lazyChains.has(NAMED_CONSTRUCTORS[alias]) && !protos.has(NAMED_CONSTRUCTORS[alias])) continue;
2622
+ defineLazyGlobal(alias, () => namedConstructor(alias));
1583
2623
  }
1584
2624
  }
1585
2625
 
1586
- // Eagerly build the base interfaces (chains supplied by Ruby, the single
1587
- // source of hierarchy knowledge) so `instanceof Node` / `typeof HTMLElement`
1588
- // resolve before an instance of that exact type has crossed.
2626
+ // A global that builds its value the first time it is read, then becomes an
2627
+ // ordinary data property holding it. Assigning it first replaces it, as
2628
+ // assigning any global does.
2629
+ function defineLazyGlobal(name, build) {
2630
+ lazyGlobals.add(name);
2631
+ Object.defineProperty(globalThis, name, {
2632
+ get() {
2633
+ const value = build();
2634
+ if (lazyGlobals.delete(name)) {
2635
+ Object.defineProperty(globalThis, name, { value, writable: true, enumerable: true, configurable: true });
2636
+ }
2637
+ return value;
2638
+ },
2639
+ set(value) {
2640
+ lazyGlobals.delete(name);
2641
+ Object.defineProperty(globalThis, name, { value, writable: true, enumerable: true, configurable: true });
2642
+ },
2643
+ enumerable: true,
2644
+ configurable: true,
2645
+ });
2646
+ }
2647
+
2648
+ // The base interfaces (chains supplied by Ruby, the single source of
2649
+ // hierarchy knowledge) are global from the start, so `instanceof Node` /
2650
+ // `typeof HTMLElement` resolve before an instance of that exact type has
2651
+ // crossed — but each is built only when first read. A page touches a few
2652
+ // of the ~200; building them all costs every page load several ms.
1589
2653
  function seedInterfaces(chains) {
1590
- chains.forEach((c) => protoForChain(c, 0));
2654
+ for (const chain of chains) {
2655
+ for (let i = 0; i < chain.length; i++) {
2656
+ const name = chain[i];
2657
+ if (protos.has(name) || lazyChains.has(name)) continue;
2658
+ lazyChains.set(name, chain.slice(i));
2659
+ if (!(name in globalThis)) defineLazyGlobal(name, () => (protoNamed(name), globalThis[name]));
2660
+ }
2661
+ }
1591
2662
  exposeNamedConstructors();
1592
2663
  }
1593
2664
 
1594
2665
  // 1c: expose an interface constructor's static/class methods (URL.createObjectURL,
1595
2666
  // URL.parse, …) on the seeded global, delegating to the window's constructor.
1596
- // Called once the window is bound (statics live on the window's constructors).
2667
+ // Called once the window is bound (statics live on the window's constructors):
2668
+ // one crossing fetches every seeded interface's names, those already built
2669
+ // get theirs now, and the rest as they are built (protoForChain).
1597
2670
  function attachStatics() {
1598
- for (const name of protos.keys()) {
1599
- const ctor = globalThis[name];
1600
- if (typeof ctor !== "function") continue;
1601
- for (const m of __rb_static_names(name)) {
1602
- if (m in ctor) continue;
1603
- ctor[m] = (...args) => rehydrate(__rb_static_call(name, m, dehydrateArgs(args)));
1604
- }
2671
+ const names = [...protos.keys(), ...lazyChains.keys()];
2672
+ if (typeof globalThis.__rb_static_names_all === "function") {
2673
+ staticNames = __rb_static_names_all(names) || {};
2674
+ } else {
2675
+ // A host that registered only the per-interface lookup is asked one
2676
+ // name at a time.
2677
+ staticNames = {};
2678
+ for (const name of names) staticNames[name] = __rb_static_names(name);
2679
+ }
2680
+ for (const name of protos.keys()) attachStaticsTo(name, globalThis[name], staticNames[name]);
2681
+ }
2682
+
2683
+ function attachStaticsTo(name, ctor, statics) {
2684
+ if (typeof ctor !== "function" || !statics) return;
2685
+ for (const m of statics) {
2686
+ if (m in ctor) continue;
2687
+ const call = declaredConversion(name, "static_operations", m);
2688
+ ctor[m] = withStaticArity((...args) =>
2689
+ rehydrate(__rb_static_call(name, m, dehydrateArgs(call ? convertArguments(call, args) : args))), m, call);
1605
2690
  }
1606
2691
  }
1607
2692
 
@@ -1619,24 +2704,53 @@ globalThis.__rbHost = (function () {
1619
2704
  // `instanceof` and `doc.defaultView.X` in iframe documents.
1620
2705
  const w = target || globalThis.window;
1621
2706
  if (!w) return;
1622
- const names = [...protos.keys()];
1623
- if (typeof globalThis.DOMException === "function") names.push("DOMException");
2707
+ // The bare `customElements` is the window's registry, the same object as
2708
+ // `window.customElements` ([Replaceable]: an assignment replaces it).
2709
+ if (!target) {
2710
+ const registry = w.customElements;
2711
+ ceWindowRegistry = registry;
2712
+ Object.defineProperty(globalThis, "customElements", {
2713
+ get() { return registry; },
2714
+ set(v) { Object.defineProperty(globalThis, "customElements", { value: v, writable: true, enumerable: true, configurable: true }); },
2715
+ enumerable: true, configurable: true,
2716
+ });
2717
+ }
2718
+ const names = [...protos.keys(), ...lazyChains.keys()];
2719
+ if (!names.includes("DOMException") && typeof globalThis.DOMException === "function") names.push("DOMException");
1624
2720
  // Mirror the JS built-in constructors too, so an iframe's contentWindow
1625
2721
  // resolves `defaultView.TypeError` / `defaultView.Array` like a real window
1626
2722
  // (WPT reaches for `(root.ownerDocument).defaultView.TypeError`). The same
1627
2723
  // list the forced pass at the end of this function uses — a window mirrors
1628
2724
  // one set of native globals, so there is one table of them.
1629
2725
  names.push(...JS_GLOBALS);
1630
- const interfaceNames = new Set(protos.keys());
2726
+ const interfaceNames = new Set(names.filter((name) => protos.has(name) || lazyChains.has(name)));
1631
2727
  // Legacy named constructors are seeded JS functions too; the window
1632
2728
  // otherwise resolves them to the host-backed Constructor proxy (a
1633
2729
  // non-constructable "object"), so replace those the same way as interfaces.
1634
2730
  for (const alias in NAMED_CONSTRUCTORS) { names.push(alias); interfaceNames.add(alias); }
1635
2731
  for (const name of names) {
2732
+ // A global not built yet stays unbuilt: the window resolves it through
2733
+ // the global the first time it is read, then holds it as a value.
2734
+ if (lazyGlobals.has(name)) {
2735
+ try {
2736
+ Object.defineProperty(w, name, {
2737
+ get() {
2738
+ const value = globalThis[name];
2739
+ Object.defineProperty(w, name, { value, configurable: true, writable: true });
2740
+ return value;
2741
+ },
2742
+ set(value) { Object.defineProperty(w, name, { value, configurable: true, writable: true }); },
2743
+ configurable: true,
2744
+ });
2745
+ } catch (e) { /* non-configurable / frozen — leave as-is */ }
2746
+ continue;
2747
+ }
1636
2748
  const ctor = globalThis[name];
1637
2749
  if (typeof ctor !== "function") continue;
1638
2750
  try {
1639
- const current = w[name];
2751
+ // An interface name is replaced whatever the window answers, so only a
2752
+ // non-interface name pays the host read.
2753
+ const current = interfaceNames.has(name) ? null : w[name];
1640
2754
  // Fill in names the window doesn't resolve at all; AND replace a
1641
2755
  // host-backed interface object with the constructable seeded constructor,
1642
2756
  // so `new document.defaultView.MutationObserver(cb)` works — in a real
@@ -1695,6 +2809,23 @@ globalThis.__rbHost = (function () {
1695
2809
  configurable: true, enumerable: false,
1696
2810
  get() { const w = globalThis.window; return w ? w.event : undefined; },
1697
2811
  });
2812
+ defineGlobalEventHandlers();
2813
+ }
2814
+
2815
+ // The Window's event handler IDL attributes, reachable as bare globals
2816
+ // (`onmessage = f`, `onload`): the window IS the global object in a browser,
2817
+ // and here globalThis is not the window proxy, so each one is an accessor
2818
+ // forwarding to the live globalThis.window. A name the realm already has as
2819
+ // its own global is left alone.
2820
+ function defineGlobalEventHandlers() {
2821
+ for (const name of EVENT_HANDLERS.get("Window") || []) {
2822
+ if (Object.hasOwn(globalThis, name)) continue;
2823
+ Object.defineProperty(globalThis, name, {
2824
+ configurable: true, enumerable: true,
2825
+ get() { const w = globalThis.window; return w ? w[name] : undefined; },
2826
+ set(v) { const w = globalThis.window; if (w) w[name] = v; },
2827
+ });
2828
+ }
1698
2829
  }
1699
2830
 
1700
2831
  // ===== Host object proxy =====
@@ -1764,7 +2895,6 @@ globalThis.__rbHost = (function () {
1764
2895
  if (!set) { set = new Set(); declinedByInterface.set(ifaceName, set); }
1765
2896
  return set;
1766
2897
  }
1767
- const isEventHandlerName = (prop) => typeof prop === "string" && /^on[a-z]/.test(prop);
1768
2898
 
1769
2899
  // IDL reflected string attributes that return the content attribute value
1770
2900
  // verbatim ("" when absent): the property name -> its content attribute. These
@@ -1860,26 +2990,44 @@ globalThis.__rbHost = (function () {
1860
2990
  // prototype chain, its method-name set, and the traits the traps branch on.
1861
2991
  // Derived once per interface and memoized, where the handler used to be
1862
2992
  // handed them as positional arguments recomputed on every crossing.
2993
+ // The legacy platform objects with named properties, generated from the IDL
2994
+ // (webidl_members.js): { enumerable, writable, overrideBuiltins } per
2995
+ // interface. An object takes the entry of the nearest interface in its chain
2996
+ // that has one — a document's proxy is an HTMLDocument, whose named getter is
2997
+ // Document's.
2998
+ const NAMED_PROPERTIES = new Map(Object.entries(globalThis.__rbIdlNamedProperties || {}));
2999
+ function namedPropertiesOf(chain) {
3000
+ for (const name of chain) {
3001
+ const flags = NAMED_PROPERTIES.get(name);
3002
+ if (flags) return flags;
3003
+ }
3004
+ return null;
3005
+ }
3006
+
1863
3007
  const shapeByInterface = new Map();
1864
3008
  function interfaceShape(desc) {
1865
3009
  const cached = (desc.name != null) ? shapeByInterface.get(desc.name) : undefined;
1866
3010
  if (cached) return cached;
1867
3011
 
1868
3012
  const methods = new Set(desc.methods);
1869
- // The maplike iterator methods are served as live iterators from the
1870
- // prototype (see ENTRIES_ITERABLES), so drop the Ruby array-returning
1871
- // versions from the method set — otherwise `entries()` would return an
1872
- // Array (no `.next()`) instead of an iterator.
3013
+ // The iterable<> methods are served from the prototype (see
3014
+ // installPairIterable), so drop the Ruby versions from the method set —
3015
+ // otherwise `entries()` would return an Array (no `.next()`) instead of an
3016
+ // iterator, and forEach would skip WebIDL's callback and thisArg handling.
1873
3017
  if (ENTRIES_ITERABLES.has(desc.name)) {
1874
- for (const m of ["entries", "keys", "values"]) methods.delete(m);
3018
+ for (const m of ["entries", "keys", "values", "forEach"]) methods.delete(m);
1875
3019
  }
3020
+ const nodeChain = !!(desc.chain && desc.chain.indexOf("Node") !== -1);
1876
3021
  const shape = {
1877
3022
  name: desc.name,
1878
3023
  chain: desc.chain,
1879
3024
  methods,
1880
3025
  arrayLike: ARRAY_LIKE_COLLECTIONS.has(desc.name),
1881
- named: NAMED_PROP_COLLECTIONS.get(desc.name) || null,
1882
- nodeChain: !!(desc.chain && desc.chain.indexOf("Node") !== -1),
3026
+ named: namedPropertiesOf(desc.chain || [desc.name]),
3027
+ nodeChain,
3028
+ // The event handler IDL attributes its interfaces declare (null: not
3029
+ // covered by the IDL tables, see isEventHandlerName).
3030
+ handlers: eventHandlersOf(desc.chain || [desc.name], nodeChain),
1883
3031
  indexedSetter: INDEXED_SETTER_INTERFACES.has(desc.name),
1884
3032
  constIface: CONST_IFACE_PROPS.get(desc.name) || null,
1885
3033
  stableIface: STABLE_EPOCH_IFACE_PROPS.get(desc.name) || null,
@@ -1974,9 +3122,8 @@ globalThis.__rbHost = (function () {
1974
3122
  return (name) => read(prop, name);
1975
3123
  }
1976
3124
 
1977
- // setAttribute / removeAttribute: a mutating attribute op, and additionally
1978
- // an on* attribute set or removed at runtime (re)compiles or clears the
1979
- // inline event handler.
3125
+ // setAttribute / removeAttribute: a mutating attribute op. (An on*
3126
+ // attribute's handler is the host's business: its attribute change steps.)
1980
3127
  function attrWriteStub(prop, ctx) {
1981
3128
  if (!ctx.nodeChain) return null;
1982
3129
 
@@ -1984,12 +3131,7 @@ globalThis.__rbHost = (function () {
1984
3131
  return function (...args) {
1985
3132
  bumpDomEpoch();
1986
3133
  try {
1987
- const r = hostCallResult(prop, __rb_host_call(handle, prop, dehydrateArgs(args)), ctx.ifaceName);
1988
- const attr = String(args[0] == null ? "" : args[0]);
1989
- if (/^on[a-z]/i.test(attr)) {
1990
- wireInlineHandler(this, attr.toLowerCase(), prop === "removeAttribute" ? null : args[1]);
1991
- }
1992
- return r;
3134
+ return hostCallResult(prop, __rb_host_call(handle, prop, dehydrateArgs(args)), ctx.ifaceName);
1993
3135
  } finally {
1994
3136
  bumpDomEpoch();
1995
3137
  }
@@ -2121,6 +3263,10 @@ globalThis.__rbHost = (function () {
2121
3263
  ["setAttribute", attrWriteStub],
2122
3264
  ["removeAttribute", attrWriteStub],
2123
3265
  ["getRandomValues", randomValuesStub],
3266
+ ["postMessage", postMessageStub],
3267
+ ["structuredClone", structuredCloneStub],
3268
+ ["pushState", historyStateStub],
3269
+ ["replaceState", historyStateStub],
2124
3270
  ]);
2125
3271
 
2126
3272
  function makeMethodStub(prop, ctx) {
@@ -2132,10 +3278,35 @@ globalThis.__rbHost = (function () {
2132
3278
  else if (NODE_OR_STRING_METHODS.has(prop)) fn = nodeOrStringStub(prop, ctx);
2133
3279
  else fn = mutatingStub(prop, ctx);
2134
3280
  }
3281
+ fn = withConvertedArguments(fn, ctx.ifaceName, "operations", prop);
3282
+ if (prop === "toString" && ctx.ifaceName) fn = brandCheckedStringifier(fn, ctx);
2135
3283
  withArity(fn, prop, ctx.ifaceName);
3284
+ // A special stub whose name no arity table lists takes the length its IDL
3285
+ // declares (the shortest overload's required count): `postMessage.length`
3286
+ // and `structuredClone.length` are 1.
3287
+ if (special && fn.length === 0) {
3288
+ const call = declaredConversion(ctx.ifaceName, "operations", prop);
3289
+ if (call && call.required) Object.defineProperty(fn, "length", { value: call.required, configurable: true });
3290
+ }
2136
3291
  return fn;
2137
3292
  }
2138
3293
 
3294
+ // A per-proxy stub closes over its own handle and ignores `this`, which is
3295
+ // harmless for a call through the object but not for the stringifier, the
3296
+ // one operation pages routinely detach: WebIDL's stringifier steps throw a
3297
+ // TypeError when `this` does not implement the interface
3298
+ // (`a.toString.call({})`), and run on `this`, not on the object the function
3299
+ // was read from (`a.toString.call(otherA)` is the other one's href).
3300
+ function brandCheckedStringifier(fn, ctx) {
3301
+ return function (...args) {
3302
+ if (!isProxy(this) || !interfaceChainOf(this).includes(ctx.ifaceName)) {
3303
+ throw new TypeError("Illegal invocation: " + ctx.ifaceName + ".toString called on a different object");
3304
+ }
3305
+ if (this[HKEY] !== ctx.handle) return this.toString(...args);
3306
+ return fn.apply(this, args);
3307
+ };
3308
+ }
3309
+
2139
3310
  // ===== Named properties (WebIDL legacy platform objects) =====
2140
3311
  //
2141
3312
  // The live "supported property names" of a named getter, and the visibility
@@ -2266,7 +3437,9 @@ globalThis.__rbHost = (function () {
2266
3437
  // being written and a later rule handles it.
2267
3438
  function rejectNamedWrite(handle, shape, t, prop) {
2268
3439
  const named = shape.named;
2269
- if (!named || named.writable || Object.hasOwn(t, prop)) return undefined;
3440
+ // A [Global]'s named properties are on its named properties object, so a
3441
+ // write makes an own property that shadows them (`window.someId = 1`).
3442
+ if (!named || named.writable || named.global || Object.hasOwn(t, prop)) return undefined;
2270
3443
  if (!isNamedKeyOf(handle, named, prop)) return undefined;
2271
3444
 
2272
3445
  return false;
@@ -2280,7 +3453,7 @@ globalThis.__rbHost = (function () {
2280
3453
  // on host state, not on the name alone), as do writable named collections.
2281
3454
  function setJsExpando(handle, shape, t, prop, value, receiver) {
2282
3455
  if ((shape.named && shape.named.writable) ||
2283
- isEventHandlerName(prop) || isGlobalWindow(handle)) return undefined;
3456
+ isEventHandlerName(shape, prop) || isGlobalWindow(handle)) return undefined;
2284
3457
  const declined = shape.declinedProps;
2285
3458
  if (!Object.hasOwn(t, prop) && !(declined !== null && declined.has(prop))) return undefined;
2286
3459
 
@@ -2301,7 +3474,7 @@ globalThis.__rbHost = (function () {
2301
3474
  // it registers a listener that actually fires; they read back as null when
2302
3475
  // unset, so the null-means-unresolved test below would otherwise divert them
2303
3476
  // to a plain (never-firing) JS global.
2304
- if (isEventHandlerName(prop)) return undefined;
3477
+ if (isEventHandlerName(shape, prop)) return undefined;
2305
3478
  const cur = __rb_host_get(handle, prop);
2306
3479
  const absent = cur !== null && typeof cur === "object" && cur.__rb_absent === true;
2307
3480
  if (!absent && rehydrate(cur) !== null) return undefined;
@@ -2335,15 +3508,19 @@ globalThis.__rbHost = (function () {
2335
3508
  Object.hasOwn(t, "defaultPrevented")) {
2336
3509
  delete t.defaultPrevented;
2337
3510
  }
2338
- // WebIDL [LegacyNullToEmptyString] DOMString setters coerce JS-side (null →
2339
- // "", else ToString — so `innerHTML = 42` / `{toString…}` work and a toString
2340
- // that throws propagates) before the value crosses into Ruby.
2341
- if (nullToEmptyString(shape.name, prop)) value = value === null ? "" : String(value);
3511
+ // A string attribute's value is converted JS-side before it crosses into
3512
+ // Ruby (see "WebIDL string conversions"): `innerHTML = null` is "",
3513
+ // `id = 42` is "42", a `{toString}` object's toString runs, and one that
3514
+ // throws — or a Symbol — throws here, before the write.
3515
+ value = convertAttributeValue(shape.name, prop, value);
2342
3516
  // A writable named property (Storage/DOMStringMap) has a DOMString named
2343
- // setter: ToString-coerce too, so `storage.x = 42` stores "42", `= null`
2344
- // stores "null", and a `{toString}` object's throwing toString propagates.
2345
- if (shape.named && shape.named.writable) value = String(value);
2346
- if (hostSet(handle, prop, value)) return true;
3517
+ // setter: `storage.x = 42` stores "42" and `= null` stores "null".
3518
+ if (shape.named && shape.named.writable) value = toDOMString(value);
3519
+ if (isEventHandlerName(shape, prop)) {
3520
+ if (hostSetWire(handle, prop, eventHandlerWire(value))) return true;
3521
+ } else if (hostSet(handle, prop, value)) {
3522
+ return true;
3523
+ }
2347
3524
 
2348
3525
  t[prop] = value;
2349
3526
  pinIfProxy(handle, receiver);
@@ -2351,6 +3528,17 @@ globalThis.__rbHost = (function () {
2351
3528
  return true;
2352
3529
  }
2353
3530
 
3531
+ // An EventHandler value as it crosses: the type is
3532
+ // [LegacyTreatNonObjectAsNull], so a value that is not an object is null,
3533
+ // a function is a callback, and any other object crosses as itself — an
3534
+ // opaque reference, never an EventListener, since a handler's handleEvent
3535
+ // is not looked up — so `el.onclick = obj` reads back as `obj`.
3536
+ function eventHandlerWire(v) {
3537
+ if (typeof v === "function") return dehydrate(v);
3538
+ if (v === null || typeof v !== "object") return null;
3539
+ return dehydrateSettle(v);
3540
+ }
3541
+
2354
3542
  // Remember a decline per (interface, prop): the host's set dispatch is a pure
2355
3543
  // function of the wrapper class and the property name, so a declined prop never
2356
3544
  // becomes host-handled later and subsequent writes can stay JS-side without
@@ -2359,7 +3547,7 @@ globalThis.__rbHost = (function () {
2359
3547
  // clearing an overflowed one costs a single re-decline.
2360
3548
  function rememberDecline(handle, shape, prop) {
2361
3549
  const declined = shape.declinedProps;
2362
- if (declined === null || isEventHandlerName(prop) || isGlobalWindow(handle)) return;
3550
+ if (declined === null || isEventHandlerName(shape, prop) || isGlobalWindow(handle)) return;
2363
3551
  if (declined.size >= DECLINED_PROPS_CAP) declined.clear();
2364
3552
  declined.add(prop);
2365
3553
  }
@@ -2381,6 +3569,24 @@ globalThis.__rbHost = (function () {
2381
3569
  return fresh;
2382
3570
  }
2383
3571
 
3572
+ // FrozenArray attributes of non-Node interfaces, by interface: the same
3573
+ // frozen array comes back while it holds the same items (HTML: "the same
3574
+ // object must be returned until the user agent needs to return different
3575
+ // values").
3576
+ const IFACE_FROZEN_ARRAY_ATTRIBUTES = new Map([
3577
+ ["Navigator", new Set(["languages"])],
3578
+ ["MessageEvent", new Set(["ports"])],
3579
+ ]);
3580
+
3581
+ // Attributes whose value is one JS object until the host replaces it, by
3582
+ // interface: attribute -> the host key that reports the value's version. The
3583
+ // value is rehydrated (a fresh JS object) only when the version moves, so
3584
+ // `history.state === history.state` and a page's edits to the object it got
3585
+ // stay visible on the next read, as with a real deserialized state.
3586
+ const VERSIONED_ATTRIBUTES = new Map([
3587
+ ["History", { state: "__dommyStateVersion" }],
3588
+ ]);
3589
+
2384
3590
  // The proxy handler for one host object: `handle` is the object, `shape` is
2385
3591
  // everything its interface decides (see interfaceShape) and `methodCache`
2386
3592
  // memoizes its method stubs. The per-interface traits used to arrive as eight
@@ -2399,6 +3605,11 @@ globalThis.__rbHost = (function () {
2399
3605
  // The frozen array last returned per FrozenArray attribute (see
2400
3606
  // frozenArrayRead); only Node proxies have such attributes.
2401
3607
  const frozenArrays = nodeChain ? new Map() : null;
3608
+ // Per-interface frozen-array / versioned attributes (see the tables above)
3609
+ // and this proxy's cache of their last answers.
3610
+ const ifaceFrozenArrays = IFACE_FROZEN_ARRAY_ATTRIBUTES.get(shape.name) || null;
3611
+ const versionedAttrs = VERSIONED_ATTRIBUTES.get(shape.name) || null;
3612
+ const ifaceAttrCache = (ifaceFrozenArrays !== null || versionedAttrs !== null) ? new Map() : null;
2402
3613
  // Per-epoch cache of stable node props (STABLE_EPOCH_NODE_PROPS). Rebuilt
2403
3614
  // whenever the epoch moves; only used for Node proxies.
2404
3615
  let epochProps = null;
@@ -2458,7 +3669,24 @@ globalThis.__rbHost = (function () {
2458
3669
  // DOM mutations, and the visibility rule.
2459
3670
  const namedKeys = () => namedKeysOf(handle, named);
2460
3671
  const isIndexInRange = (prop) => arrayLike && isArrayIndex(prop) && Number(prop) < liveLength();
2461
- const isNamedKey = (prop) => isNamedKeyOf(handle, named, prop);
3672
+ // An object whose named properties override its builtins
3673
+ // ([LegacyOverrideBuiltIns]: a document, a form, a dataset) checks them on
3674
+ // EVERY property read, so its supported names are fetched once per DOM
3675
+ // epoch — they change only when the tree or an attribute does.
3676
+ let namedKeyCache = null;
3677
+ let namedKeyEpoch = -1;
3678
+ // So does the Window ([Global]), whose names a `"x" in window` check asks
3679
+ // for before anything else.
3680
+ const isNamedKey = named && (named.overrideBuiltins || named.global)
3681
+ ? (prop) => {
3682
+ if (typeof prop !== "string") return false;
3683
+ if (namedKeyEpoch !== domEpoch) {
3684
+ namedKeyCache = new Set(namedKeysOf(handle, named));
3685
+ namedKeyEpoch = domEpoch;
3686
+ }
3687
+ return namedKeyCache.has(prop);
3688
+ }
3689
+ : (prop) => isNamedKeyOf(handle, named, prop);
2462
3690
  const namedShadowedByProto = (t, prop) => namedShadowedByProtoOf(named, t, prop);
2463
3691
  // What a method stub can need beyond its own name (see makeMethodStub).
2464
3692
  const stubContext = {
@@ -2480,7 +3708,7 @@ globalThis.__rbHost = (function () {
2480
3708
  // prototype's methods AND accessors, so resolve it before either. An own
2481
3709
  // expando (checked above) still wins.
2482
3710
  if (named && named.overrideBuiltins && typeof prop === "string" && isNamedKey(prop)) {
2483
- return rehydrate(__rb_host_get(handle, prop));
3711
+ return rehydrate(__rb_named_get(handle, prop));
2484
3712
  }
2485
3713
  if (methods.has(prop)) {
2486
3714
  // A read-only collection operation resolves to the interface
@@ -2504,6 +3732,17 @@ globalThis.__rbHost = (function () {
2504
3732
  return Reflect.get(t, prop, receiver);
2505
3733
  }
2506
3734
  if (constCache !== null && constCache.has(prop)) return constCache.get(prop);
3735
+ if (ifaceFrozenArrays !== null && ifaceFrozenArrays.has(prop)) {
3736
+ return frozenArrayRead(ifaceAttrCache, prop, rehydrate(__rb_host_get(handle, prop)));
3737
+ }
3738
+ if (versionedAttrs !== null && typeof prop === "string" && Object.hasOwn(versionedAttrs, prop)) {
3739
+ const version = rehydrate(__rb_host_get(handle, versionedAttrs[prop]));
3740
+ const hit = ifaceAttrCache.get(prop);
3741
+ if (hit !== undefined && hit.version === version) return hit.value;
3742
+ const value = rehydrate(__rb_host_get(handle, prop));
3743
+ ifaceAttrCache.set(prop, { version, value });
3744
+ return value;
3745
+ }
2507
3746
  // Reflected string attribute (id/className/slot): answer from the
2508
3747
  // element's attribute snapshot, no crossing. Only when a snapshot is
2509
3748
  // available (HTML elements) — non-elements / foreign-namespace get null
@@ -2553,15 +3792,24 @@ globalThis.__rbHost = (function () {
2553
3792
  // global of the same name (an OWN globalThis prop — inherited names already
2554
3793
  // resolved via `prop in t` above), so e.g. a UMD bundle's
2555
3794
  // `globalThis.Stimulus = …` is visible as `window.Stimulus`.
2556
- if (hostHasNoValue && isGlobalWindow(handle) && Object.hasOwn(globalThis, prop)) return globalThis[prop];
3795
+ if (hostHasNoValue && isGlobalWindow(handle) && Object.hasOwn(globalThis, prop) &&
3796
+ !isEventHandlerName(shape, prop)) return globalThis[prop];
3797
+ // A Window's named properties (HTML "named access on the Window
3798
+ // object") come after every member and global: they live on the named
3799
+ // properties object at the bottom of its prototype chain.
3800
+ if (hostHasNoValue && named && named.global && typeof prop === "string" && isNamedKey(prop)) {
3801
+ return rehydrate(__rb_named_get(handle, prop));
3802
+ }
2557
3803
  // A legacy platform collection returns `undefined` (not the host's null)
2558
3804
  // for a string property that resolves to no value. An out-of-range array
2559
3805
  // index is `undefined` and does NOT fall back to a named lookup (so
2560
3806
  // `coll[2147483648]` is undefined even if an element's id is that digit
2561
- // string); other unsupported strings (`coll[""]`, `coll["x"]`) too.
2562
- if (hostHasNoValue && (arrayLike || named) && typeof prop === "string" && prop !== "length") {
3807
+ // string); other unsupported strings (`coll[""]`, `coll["x"]`) too. A
3808
+ // node (a select, a form) answers an unknown name with ABSENT itself, so
3809
+ // its null is a real attribute value (`select.form`) and is kept.
3810
+ if (hostHasNoValue && (arrayLike || (named && !named.global)) && typeof prop === "string" && prop !== "length") {
2563
3811
  if (arrayLike && isArrayIndex(prop)) return undefined;
2564
- if (!isNamedKey(prop)) return undefined;
3812
+ if (!nodeChain && !isNamedKey(prop)) return undefined;
2565
3813
  }
2566
3814
  return v;
2567
3815
  },
@@ -2599,7 +3847,7 @@ globalThis.__rbHost = (function () {
2599
3847
  writable: false, enumerable: true, configurable: true,
2600
3848
  };
2601
3849
  }
2602
- if (isNamedKey(prop) && !namedShadowedByProto(t, prop)) {
3850
+ if (isNamedKey(prop) && !named.global && !namedShadowedByProto(t, prop)) {
2603
3851
  return {
2604
3852
  value: rehydrate(__rb_host_get(handle, prop)),
2605
3853
  writable: named.writable, enumerable: named.enumerable, configurable: true,
@@ -2611,7 +3859,7 @@ globalThis.__rbHost = (function () {
2611
3859
  if (typeof prop === "string" && deletedGlobals.has(prop)) deletedGlobals.delete(prop);
2612
3860
  // Cannot redefine a live indexed or read-only named property.
2613
3861
  if (arrayLike && isArrayIndex(prop)) return false;
2614
- if (named && !named.writable && !Object.hasOwn(t, prop) && isNamedKey(prop)) return false;
3862
+ if (named && !named.writable && !named.global && !Object.hasOwn(t, prop) && isNamedKey(prop)) return false;
2615
3863
  // A writable named collection (Storage/DOMStringMap) has a named setter:
2616
3864
  // `Object.defineProperty(storage, k, {value})` routes to it (ToString-
2617
3865
  // coerced) rather than planting a JS expando that the named getter can't
@@ -2644,7 +3892,10 @@ globalThis.__rbHost = (function () {
2644
3892
  if (typeof prop !== "symbol" && isGlobalWindow(handle) && Object.hasOwn(globalThis, prop)) {
2645
3893
  const removed = delete globalThis[prop];
2646
3894
  if (removed) {
2647
- deletedGlobals.add(prop);
3895
+ // A named property behind it (`<div id=x>` after `window.x = 1;
3896
+ // delete window.x`) shows through again; the host does not resolve
3897
+ // it, so it needs no tombstone.
3898
+ if (!(named && named.global && isNamedKey(prop))) deletedGlobals.add(prop);
2648
3899
  Reflect.deleteProperty(t, prop);
2649
3900
  }
2650
3901
  return removed;
@@ -2657,7 +3908,7 @@ globalThis.__rbHost = (function () {
2657
3908
  // mutation, so invalidate attribute snapshots.
2658
3909
  bumpDomEpoch();
2659
3910
  if (rehydrate(__rb_host_delete(handle, prop))) return true;
2660
- } else if (isNamedKey(prop)) {
3911
+ } else if (!named.global && isNamedKey(prop)) {
2661
3912
  return false; // read-only named property cannot be deleted
2662
3913
  }
2663
3914
  }
@@ -2665,7 +3916,8 @@ globalThis.__rbHost = (function () {
2665
3916
  },
2666
3917
  ownKeys(t) {
2667
3918
  const keys = Reflect.ownKeys(t);
2668
- if (!arrayLike && !named) return keys;
3919
+ // (A [Global]'s named properties are not its own: see `named.global`.)
3920
+ if (!arrayLike && (!named || named.global)) return keys;
2669
3921
  const n = arrayLike ? liveLength() : 0;
2670
3922
  const result = [];
2671
3923
  for (let i = 0; i < n; i++) result.push(String(i));
@@ -2690,16 +3942,20 @@ globalThis.__rbHost = (function () {
2690
3942
  // or ABI method is present.
2691
3943
  if (Reflect.has(t, prop)) return true;
2692
3944
  if (typeof prop === "symbol") return false;
2693
- if (methods.has(prop) || prop === "length") return true;
3945
+ // (`length` is not assumed: a collection, a select, a form, Storage
3946
+ // and History answer it from the host below, and `"length" in div`
3947
+ // or in a URLSearchParams is false, as it is in a browser.)
3948
+ if (methods.has(prop)) return true;
2694
3949
  // The global window also reports its JS globals (`"Stimulus" in window`);
2695
3950
  // inherited names already answered true via Reflect.has(t) above.
2696
3951
  if (isGlobalWindow(handle) && Object.hasOwn(globalThis, prop)) return true;
2697
- // Event-handler IDL attributes (onclick, oninput, …) exist on event
2698
- // targets as null-default properties, so `("oninput" in document)` is
2699
- // true even when unset — React's isEventSupported feature-detect relies
2700
- // on this to use the native input event (else it falls back to a keydown
2701
- // polyfill and controlled-input onChange never fires).
2702
- if (typeof prop === "string" && /^on[a-z]/.test(prop)) return true;
3952
+ // Event-handler IDL attributes (onclick, oninput, …) the object's
3953
+ // interfaces declare exist as null-default properties, so
3954
+ // `("oninput" in document)` is true even when unset — React's
3955
+ // isEventSupported feature-detect relies on this to use the native
3956
+ // input event (else it falls back to a keydown polyfill and
3957
+ // controlled-input onChange never fires).
3958
+ if (isEventHandlerName(shape, prop)) return true;
2703
3959
  // Otherwise reflect the ABI: a property whose host value is non-null is
2704
3960
  // present; a null/absent one reports missing. We can't distinguish
2705
3961
  // present-but-null from genuinely-absent across the ABI, and reporting
@@ -2722,7 +3978,7 @@ globalThis.__rbHost = (function () {
2722
3978
  };
2723
3979
  }
2724
3980
 
2725
- function makeProxy(handle, iface, ce, suppressUpgrade) {
3981
+ function makeProxy(handle, iface) {
2726
3982
  const ref = cache.get(handle);
2727
3983
  if (ref) {
2728
3984
  const existing = ref.deref();
@@ -2739,16 +3995,12 @@ globalThis.__rbHost = (function () {
2739
3995
  }
2740
3996
  // Reuse the cached per-interface descriptor when the handle crossed tagged
2741
3997
  // with a known interface — skipping the describe round trip. Otherwise (no
2742
- // tag, or first sighting of this interface) describe once and cache it. The
2743
- // custom-element tag is per-instance, so it comes from the handle tag (the
2744
- // describe path falls back to the describe's own `ce`).
3998
+ // tag, or first sighting of this interface) describe once and cache it.
2745
3999
  let desc = (iface != null) ? descByInterface.get(iface) : undefined;
2746
- let ceName = ce;
2747
4000
  if (!desc) {
2748
4001
  const d = __rb_host_describe(handle);
2749
4002
  desc = { name: d.name, chain: d.chain, methods: d.methods };
2750
4003
  if (d.name != null) descByInterface.set(d.name, desc);
2751
- if (ceName === undefined) ceName = d.ce;
2752
4004
  }
2753
4005
  // 2d: the method-name set and the trap traits are per-interface; reuse them
2754
4006
  // across every proxy of that type.
@@ -2779,16 +4031,13 @@ globalThis.__rbHost = (function () {
2779
4031
  // expando-bearing proxy) instead of caching them only weakly. Residency is
2780
4032
  // bounded by the distinct nodes touched — the same set the Ruby-side wrapper
2781
4033
  // cache already retains. Non-node proxies stay weak + finalizer-released.
2782
- if (isNode) {
4034
+ // A CustomElementRegistry is pinned too: its definitions live JS-side,
4035
+ // keyed by its proxy (see ceStateOf).
4036
+ if (isNode || desc.name === "CustomElementRegistry") {
2783
4037
  pinned.set(handle, p);
2784
4038
  } else {
2785
4039
  finalizers.register(p, handle);
2786
4040
  }
2787
- // 1d: a Dommy-registered custom element node is upgraded to its JS class on
2788
- // first crossing — so the constructor runs before any lifecycle callback.
2789
- // Suppressed when the proxy IS the return value of an in-flight direct
2790
- // construction (`new MyElement()`), whose ctor is already on the stack.
2791
- if (ceName && !suppressUpgrade) upgradeElement(p, ceName);
2792
4041
  // An iframe's contentWindow crosses as a NON-global Window proxy. Seed its
2793
4042
  // own constructor set (Event/DOMException/Range/… + JS builtins) the first
2794
4043
  // time it materializes, so a nested realm resolves
@@ -2803,56 +4052,132 @@ globalThis.__rbHost = (function () {
2803
4052
  }
2804
4053
 
2805
4054
  // ===== Custom elements (1d) =====
4055
+ //
4056
+ // A registry's definitions live here, JS-side, because their constructors
4057
+ // and callbacks are JS functions; Ruby holds a definition object per
4058
+ // definition (Js::JsCustomElementDefinition) that runs the reactions
4059
+ // (Internal::CEReactions) and calls back in by the definition's id:
4060
+ // ceConstruct (create an element with the synchronous flag), ceUpgrade
4061
+ // (upgrade an element) and ceInvoke (a lifecycle callback).
4062
+
4063
+ // An HTML element interface's constructor ([HTMLConstructor]) is a Proxy
4064
+ // with a construct trap: a function's own [[Construct]] would read
4065
+ // NewTarget.prototype before the steps below run (to make `this`), where
4066
+ // HTML reads it once, after its checks. Anything but a defined custom
4067
+ // element's constructor as NewTarget is a TypeError.
4068
+ function isHTMLElementInterface(name) {
4069
+ return name.startsWith("HTML") && name.endsWith("Element");
4070
+ }
4071
+ function htmlElementConstructor(target, name) {
4072
+ const proxy = new Proxy(target, {
4073
+ construct(_target, _args, newTarget) {
4074
+ if (newTarget !== proxy) {
4075
+ const built = constructCustomElement(name, newTarget);
4076
+ if (built !== undefined) return built;
4077
+ }
4078
+ throw new TypeError("Illegal constructor");
4079
+ },
4080
+ });
4081
+ return proxy;
4082
+ }
2806
4083
 
2807
- // Run a JS custom element's constructor against an existing Dommy-backed proxy
2808
- // (the construction-stack adoption proven by the Step 0 spike), making the
2809
- // proxy an instance of the registered class with its constructor side effects.
2810
- // Reverse of ceRegistry: the registered tag name for a constructor (the
2811
- // active new.target of a direct `new MyElement()`), or undefined. Iterates —
2812
- // a page defines a handful of elements, so a map's bookkeeping isn't worth it.
2813
- function ceNameForCtor(ctor) {
2814
- for (const [name, c] of ceRegistry) if (c === ctor) return name;
2815
- return undefined;
4084
+ // The HTML element constructor steps for a custom element's `super()`
4085
+ // (HTML §3.2.3), `activeName` being the interface whose constructor runs.
4086
+ // Undefined when NewTarget is no defined constructor (the caller then
4087
+ // throws "Illegal constructor", as for any interface without one).
4088
+ function constructCustomElement(activeName, nt) {
4089
+ let registry = ceActiveRegistries.get(nt);
4090
+ if (registry === undefined) registry = ceWindowRegistry;
4091
+ let def = isProxy(registry) ? ceStateOf(registry).byCtor.get(nt) : undefined;
4092
+ if (!def && !ceActiveRegistries.has(nt)) def = ceDefsByCtor.get(nt);
4093
+ if (!def) return undefined;
4094
+ if (def.localName === def.name) {
4095
+ if (activeName !== "HTMLElement") {
4096
+ throw new TypeError("Illegal constructor: an autonomous custom element must extend HTMLElement");
4097
+ }
4098
+ } else if (activeName !== def.baseInterface) {
4099
+ throw new TypeError("Illegal constructor: " + activeName + " is not the interface of <" + def.localName + ">");
4100
+ }
4101
+ let proto = nt.prototype;
4102
+ if (proto === null || (typeof proto !== "object" && typeof proto !== "function")) {
4103
+ proto = protoNamed(activeName) || Object.prototype;
4104
+ }
4105
+ const stack = def.constructionStack;
4106
+ if (stack.length === 0) {
4107
+ // `new MyElement()`: a fresh element, custom from the start.
4108
+ const el = rehydrate(__rb_create_custom_element(def.id));
4109
+ if (el === null || typeof el !== "object") throw new TypeError("Illegal constructor");
4110
+ Object.setPrototypeOf(el, proto);
4111
+ return el;
4112
+ }
4113
+ const el = stack[stack.length - 1];
4114
+ if (el === CE_ALREADY_CONSTRUCTED) {
4115
+ throw new TypeError("Failed to construct '" + activeName + "': this element was already constructed");
4116
+ }
4117
+ Object.setPrototypeOf(el, proto);
4118
+ stack[stack.length - 1] = CE_ALREADY_CONSTRUCTED;
4119
+ return el;
2816
4120
  }
2817
4121
 
2818
- function upgradeElement(proxy, name) {
2819
- const ctor = ceRegistry.get(name);
2820
- if (!ctor) return;
2821
- constructionStack.push(proxy);
2822
- try { Reflect.construct(ctor, [], ctor); }
2823
- finally { constructionStack.pop(); }
4122
+ // Ruby -> JS: construct the definition's constructor with no arguments
4123
+ // (DOM "create an element" with the synchronous custom elements flag). The
4124
+ // result crosses back as is — Ruby checks it is a fitting element — or
4125
+ // what it threw, tagged.
4126
+ function withActiveRegistry(def, registry, fn) {
4127
+ const had = ceActiveRegistries.has(def.ctor);
4128
+ const previous = ceActiveRegistries.get(def.ctor);
4129
+ ceActiveRegistries.set(def.ctor, registry);
4130
+ try {
4131
+ return fn();
4132
+ } finally {
4133
+ if (had) ceActiveRegistries.set(def.ctor, previous); else ceActiveRegistries.delete(def.ctor);
4134
+ }
2824
4135
  }
2825
4136
 
2826
- // Ruby re-wrapped an element its definition now applies to and moved the
2827
- // element's handle onto the new wrapper (HostBridge#upgrade_in_place). The
2828
- // proxy a script already holds is upgraded where it stands, and recorded under
2829
- // the new interface so a later crossing tagged with it keeps the same object.
2830
- function upgradeInPlace(handle, name, iface) {
4137
+ function ceConstruct(id) {
2831
4138
  bumpDomEpoch(); // Ruby -> JS entry: see invokeCallback
2832
- const ref = cache.get(handle);
2833
- const proxy = ref && ref.deref();
2834
- if (!proxy) return;
2835
- if (iface != null) proxyInterfaces.set(proxy, iface);
2836
- upgradeElement(proxy, name);
4139
+ const def = ceDefsById.get(id);
4140
+ try {
4141
+ return dehydrateReturn(withActiveRegistry(def, def.registry, () => Reflect.construct(def.ctor, [])));
4142
+ } catch (e) {
4143
+ return tagThrow(e);
4144
+ }
2837
4145
  }
2838
4146
 
2839
- // Ruby calls this when a registered custom element fires a lifecycle reaction.
2840
- // makeProxy upgrades on first crossing, so the constructor has already run.
2841
- function invokeLifecycle(handle, callback, args) {
2842
- bumpDomEpoch(); // Ruby -> JS entry: see invokeCallback
2843
- const p = makeProxy(handle);
2844
- const fn = p[callback];
2845
- if (typeof fn !== "function") {
2846
- // HTML "enqueue a custom element callback reaction": without a
2847
- // connectedMoveCallback, a move runs disconnectedCallback and then
2848
- // connectedCallback in its place.
2849
- if (callback === "connectedMoveCallback") {
2850
- invokeLifecycle(handle, "disconnectedCallback", []);
2851
- invokeLifecycle(handle, "connectedCallback", []);
4147
+ // Ruby -> JS: HTML "upgrade an element" steps 5-8 for the element `handle`
4148
+ // names — construct the definition's constructor with the element on its
4149
+ // construction stack, so `super()` hands the element itself back.
4150
+ function ceUpgrade(id, handle) {
4151
+ bumpDomEpoch();
4152
+ const def = ceDefsById.get(id);
4153
+ const el = makeProxy(handle);
4154
+ def.constructionStack.push(el);
4155
+ try {
4156
+ const result = withActiveRegistry(def, def.registry, () => Reflect.construct(def.ctor, []));
4157
+ if (result !== el) {
4158
+ throw new TypeError("Failed to upgrade <" + def.name + ">: the constructor did not return the element being upgraded");
2852
4159
  }
2853
4160
  return undefined;
4161
+ } catch (e) {
4162
+ return tagThrow(e);
4163
+ } finally {
4164
+ def.constructionStack.pop();
4165
+ }
4166
+ }
4167
+
4168
+ // Ruby -> JS: invoke one of the definition's lifecycle callbacks (as the
4169
+ // definition read them at define() time) with `this` the element.
4170
+ function ceInvoke(id, handle, callbackName, args) {
4171
+ bumpDomEpoch();
4172
+ const def = ceDefsById.get(id);
4173
+ const fn = def && def.callbacks[callbackName];
4174
+ if (typeof fn !== "function") return undefined;
4175
+ try {
4176
+ fn.apply(makeProxy(handle), rehydrate(args || []));
4177
+ return undefined;
4178
+ } catch (e) {
4179
+ return tagThrow(e);
2854
4180
  }
2855
- return dehydrateTop(fn.apply(p, rehydrate(args || [])));
2856
4181
  }
2857
4182
 
2858
4183
  // Hyphenated names the HTML spec reserves (SVG / MathML) — not valid custom
@@ -2861,21 +4186,15 @@ globalThis.__rbHost = (function () {
2861
4186
  "annotation-xml", "color-profile", "font-face", "font-face-src",
2862
4187
  "font-face-uri", "font-face-format", "font-face-name", "missing-glyph"
2863
4188
  ]);
2864
- // https://html.spec.whatwg.org/#valid-custom-element-name — an ASCII-lower
2865
- // start, a PCENChar run, and at least one "-".
2866
- const CE_PCEN =
2867
- "-._0-9a-z\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF" +
2868
- "\\u200C-\\u200D\\u203F-\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF" +
2869
- "\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u{10000}-\\u{EFFFF}";
2870
- const CE_NAME_RE = new RegExp("^[a-z][" + CE_PCEN + "]*-[" + CE_PCEN + "]*$", "u");
4189
+ // https://html.spec.whatwg.org/#valid-custom-element-name — a valid element
4190
+ // local name (DOM) starting with an ASCII lower alpha (which leaves only
4191
+ // ASCII whitespace, NULL, "/" and ">" out of the rest), with no ASCII upper
4192
+ // alpha and at least one "-".
4193
+ const CE_NAME_RE = /^[a-z][^\t\n\f\r \0\/>A-Z]*$/;
2871
4194
  function isValidCustomElementName(name) {
2872
- return typeof name === "string" && CE_NAME_RE.test(name) && !CE_RESERVED.has(name);
4195
+ return typeof name === "string" && CE_NAME_RE.test(name) && name.includes("-") && !CE_RESERVED.has(name);
2873
4196
  }
2874
4197
 
2875
- // "element definition is running" flag — a define() reentered while running
2876
- // (e.g. from a constructor-property getter) is a NotSupportedError.
2877
- let ceDefinitionRunning = false;
2878
-
2879
4198
  // WebIDL `sequence<DOMString>` conversion: the value must be iterable (a
2880
4199
  // non-iterable like a number throws a TypeError — unlike Array.from, which
2881
4200
  // returns []); each item is stringified. Exceptions from the iterator / items
@@ -2890,125 +4209,286 @@ globalThis.__rbHost = (function () {
2890
4209
  return result;
2891
4210
  }
2892
4211
 
2893
- // customElements.define(name, JSClass): validate + read the constructor's
2894
- // definition per WHATWG, register JS-side, and ask Ruby to wire a Dommy custom
2895
- // element whose reactions route back through invokeLifecycle. Check order:
2896
- // IsConstructor, name, running-flag, duplicate name, duplicate constructor;
2897
- // then (flag set) prototype → callbacks → observedAttributes → disabledFeatures
2898
- // → formAssociated.
2899
- function defineCustomElement(name, ctor) {
2900
- if (typeof ctor !== "function") {
2901
- throw new TypeError("The custom element constructor must be a constructor");
4212
+ // ECMAScript IsConstructor, without touching the function: a Proxy over a
4213
+ // non-constructor has no [[Construct]], so `new` on it throws before any
4214
+ // trap — and the trap keeps a real constructor from running.
4215
+ const CE_CONSTRUCT_PROBE = { construct() { return {}; } };
4216
+ function isConstructor(value) {
4217
+ if (typeof value !== "function") return false;
4218
+ try {
4219
+ new (new Proxy(value, CE_CONSTRUCT_PROBE))();
4220
+ return true;
4221
+ } catch (_) {
4222
+ return false;
4223
+ }
4224
+ }
4225
+
4226
+ // The JS half of a CustomElementRegistry: its definitions by name, its
4227
+ // when-defined promises and its "element definition is running" flag.
4228
+ function ceStateOf(registry) {
4229
+ if (!isProxy(registry) || proxyInterfaces.get(registry) !== "CustomElementRegistry") {
4230
+ throw new TypeError("Illegal invocation: not a CustomElementRegistry");
4231
+ }
4232
+ let state = ceStates.get(registry);
4233
+ if (!state) {
4234
+ state = { defs: new Map(), byCtor: new Map(), pending: new Map(), running: false, scoped: false };
4235
+ ceStates.set(registry, state);
4236
+ }
4237
+ return state;
4238
+ }
4239
+
4240
+ // The interface of the HTML element `localName` names, as Ruby's element
4241
+ // class table has it ("HTMLUnknownElement" for none).
4242
+ function htmlInterfaceFor(localName) {
4243
+ return __rb_html_interface_for(localName);
4244
+ }
4245
+
4246
+ // customElements.define(name, constructor, options) — HTML §4.13.4.
4247
+ function defineCustomElement(registry, name, ctor, options) {
4248
+ const state = ceStateOf(registry);
4249
+ if (!isConstructor(ctor)) {
4250
+ throw new TypeError("Failed to execute 'define' on 'CustomElementRegistry': The provided value is not a constructor");
2902
4251
  }
4252
+ name = String(name);
2903
4253
  if (!isValidCustomElementName(name)) {
2904
4254
  throw new DOMException("'" + name + "' is not a valid custom element name", "SyntaxError");
2905
4255
  }
2906
- if (ceDefinitionRunning) {
2907
- throw new DOMException("A custom element definition is already being processed", "NotSupportedError");
2908
- }
2909
- if (ceRegistry.has(name)) {
4256
+ if (state.defs.has(name)) {
2910
4257
  throw new DOMException("An element with name '" + name + "' is already defined", "NotSupportedError");
2911
4258
  }
2912
- for (const existing of ceRegistry.values()) {
2913
- if (existing === ctor) {
4259
+ for (const existing of state.defs.values()) {
4260
+ if (existing.ctor === ctor) {
2914
4261
  throw new DOMException("This constructor has already been registered", "NotSupportedError");
2915
4262
  }
2916
4263
  }
4264
+ let localName = name;
4265
+ let baseInterface = "HTMLElement";
4266
+ // ElementDefinitionOptions: a dictionary — undefined/null is {}, anything
4267
+ // else that is not an object a TypeError.
4268
+ if (options !== undefined && options !== null && typeof options !== "object" && typeof options !== "function") {
4269
+ throw new TypeError("Failed to execute 'define' on 'CustomElementRegistry': The provided value is not of type 'ElementDefinitionOptions'");
4270
+ }
4271
+ const ext = (options === undefined || options === null) ? undefined : options.extends;
4272
+ if (ext !== undefined) {
4273
+ const extName = String(ext);
4274
+ if (state.scoped) {
4275
+ throw new DOMException("A scoped registry cannot define a customized built-in element", "NotSupportedError");
4276
+ }
4277
+ if (isValidCustomElementName(extName)) {
4278
+ throw new DOMException("'" + extName + "' is a valid custom element name, so it cannot be extended", "NotSupportedError");
4279
+ }
4280
+ baseInterface = htmlInterfaceFor(extName);
4281
+ if (baseInterface === "HTMLUnknownElement") {
4282
+ throw new DOMException("'" + extName + "' is not an HTML element that can be extended", "NotSupportedError");
4283
+ }
4284
+ localName = extName;
4285
+ }
4286
+ if (state.running) {
4287
+ throw new DOMException("A custom element definition is already being processed", "NotSupportedError");
4288
+ }
2917
4289
 
2918
- ceDefinitionRunning = true;
4290
+ state.running = true;
2919
4291
  let observed = [];
4292
+ let disabled = [];
4293
+ let formAssociated = false;
4294
+ const callbacks = {};
2920
4295
  try {
2921
4296
  const proto = ctor.prototype;
2922
- if (typeof proto !== "object" || proto === null) {
4297
+ if (proto === null || (typeof proto !== "object" && typeof proto !== "function")) {
2923
4298
  throw new TypeError("The custom element constructor's prototype is not an object");
2924
4299
  }
2925
- // Read each lifecycle reaction callback off the prototype, in spec order;
2926
- // each must be undefined or a function. connectedMoveCallback is read here
2927
- // like the rest, though Dommy's moveBefore does not enqueue custom element
2928
- // reactions yet.
4300
+ // Each lifecycle callback, read off the prototype once, in spec order;
4301
+ // each must be undefined or a function (a WebIDL Function).
2929
4302
  const readCallback = (cb) => {
2930
4303
  const fn = proto[cb];
2931
- if (fn !== undefined && typeof fn !== "function") {
2932
- throw new TypeError("The " + cb + " callback is not a function");
2933
- }
2934
- return fn;
4304
+ if (fn === undefined) return;
4305
+ if (typeof fn !== "function") throw new TypeError("The " + cb + " callback is not a function");
4306
+ callbacks[cb] = fn;
2935
4307
  };
2936
- readCallback("connectedCallback");
2937
- readCallback("disconnectedCallback");
2938
- readCallback("connectedMoveCallback");
2939
- readCallback("adoptedCallback");
2940
- const attributeChanged = readCallback("attributeChangedCallback");
2941
- if (attributeChanged !== undefined) {
4308
+ ["connectedCallback", "disconnectedCallback", "connectedMoveCallback", "adoptedCallback",
4309
+ "attributeChangedCallback"].forEach(readCallback);
4310
+ if (callbacks.attributeChangedCallback !== undefined) {
2942
4311
  const oa = ctor.observedAttributes;
2943
4312
  if (oa !== undefined) observed = toDOMStringSequence(oa);
2944
4313
  }
2945
- // disabledFeatures / formAssociated are converted for their observable side
2946
- // effects (Symbol.iterator access, iteration, ToBoolean); values unmodeled.
2947
4314
  const df = ctor.disabledFeatures;
2948
- if (df !== undefined) toDOMStringSequence(df);
2949
- if (ctor.formAssociated) {
2950
- readCallback("formAssociatedCallback");
2951
- readCallback("formResetCallback");
2952
- readCallback("formDisabledCallback");
2953
- readCallback("formStateRestoreCallback");
4315
+ if (df !== undefined) disabled = toDOMStringSequence(df);
4316
+ formAssociated = !!ctor.formAssociated;
4317
+ if (formAssociated) {
4318
+ ["formAssociatedCallback", "formResetCallback", "formDisabledCallback",
4319
+ "formStateRestoreCallback"].forEach(readCallback);
2954
4320
  }
2955
4321
  } finally {
2956
- ceDefinitionRunning = false;
4322
+ state.running = false;
2957
4323
  }
2958
4324
 
2959
- ceRegistry.set(name, ctor);
2960
- __rb_define_custom_element(name, observed);
2961
- const waiter = cePending.get(name);
2962
- if (waiter) { cePending.delete(name); waiter.resolve(ctor); }
2963
- }
2964
-
2965
- // whenDefined stays pending until the name is defined (spec semantics), so
2966
- // `await customElements.whenDefined(x)` before define() doesn't resolve early.
2967
- // The SAME promise is returned for a given still-undefined name each call
2968
- // ([SameObject]-ish per spec), and define() resolves it.
2969
- function whenDefinedCustomElement(name) {
2970
- const ctor = ceRegistry.get(name);
2971
- if (ctor) return Promise.resolve(ctor);
2972
- let entry = cePending.get(name);
2973
- if (!entry) {
2974
- let resolve;
2975
- const promise = new Promise((r) => { resolve = r; });
2976
- entry = { promise, resolve };
2977
- cePending.set(name, entry);
2978
- }
2979
- return entry.promise;
4325
+ const def = {
4326
+ id: ++ceNextId, name, localName, ctor, callbacks, baseInterface,
4327
+ observed, formAssociated, constructionStack: [], registry
4328
+ };
4329
+ state.defs.set(name, def);
4330
+ state.byCtor.set(ctor, def);
4331
+ ceDefsById.set(def.id, def);
4332
+ if (!state.scoped) ceDefsByCtor.set(ctor, def);
4333
+ // Ruby appends the definition, upgrades the document's elements it
4334
+ // applies to (their constructors have run when this returns) — then the
4335
+ // when-defined promise resolves.
4336
+ const raised = __rb_define_custom_element(registry[HKEY], def.id, name, localName, observed,
4337
+ Object.keys(callbacks), disabled, formAssociated);
4338
+ if (raised && typeof raised === "object" && raised.__rb_exception__) throw makeHostError(raised.__rb_exception__);
4339
+ const waiter = state.pending.get(name);
4340
+ if (waiter) { state.pending.delete(name); waiter.resolve(ctor); }
2980
4341
  }
2981
4342
 
2982
4343
  // Expose CustomElementRegistry as a real interface object with its operations
2983
- // on the prototype (so `'define' in CustomElementRegistry.prototype`,
2984
- // `customElements instanceof CustomElementRegistry`, and prototype reflection
2985
- // work); `customElements` is its sole instance. The operations close over the
2986
- // JS-side registry, so they ignore `this` (no host handle to route through).
2987
- function CustomElementRegistry() { throw new TypeError("Illegal constructor"); }
4344
+ // on the prototype; every registry (a window's `customElements`, an
4345
+ // iframe's) is a host object of this interface, and the operations find the
4346
+ // registry's definitions from `this`.
4347
+ // `new CustomElementRegistry()`: a scoped registry (HTML "is scoped").
4348
+ function CustomElementRegistry() {
4349
+ if (new.target === undefined) throw new TypeError("Constructor CustomElementRegistry requires 'new'");
4350
+ const registry = rehydrate(__rb_new_custom_element_registry());
4351
+ ceStateOf(registry).scoped = true;
4352
+ if (new.target !== CustomElementRegistry) Object.setPrototypeOf(registry, new.target.prototype);
4353
+ return registry;
4354
+ }
2988
4355
  const cerProto = CustomElementRegistry.prototype;
2989
4356
  Object.defineProperty(cerProto, Symbol.toStringTag, { value: "CustomElementRegistry", configurable: true });
2990
- const cerMethod = (key, fn) =>
4357
+ protos.set("CustomElementRegistry", cerProto);
4358
+ const cerMethod = (key, fn, length) => {
4359
+ Object.defineProperty(fn, "length", { value: length, configurable: true });
2991
4360
  Object.defineProperty(cerProto, key, { value: fn, writable: true, enumerable: true, configurable: true });
2992
- cerMethod("define", function (name, ctor) { return defineCustomElement(name, ctor); });
2993
- cerMethod("get", function (name) { return ceRegistry.get(name); });
2994
- cerMethod("getName", function (ctor) {
4361
+ };
4362
+ cerMethod("define", function define(name, ctor, options) {
4363
+ if (arguments.length < 2) {
4364
+ throw new TypeError("Failed to execute 'define' on 'CustomElementRegistry': 2 arguments required, but only " + arguments.length + " present.");
4365
+ }
4366
+ return defineCustomElement(this, name, ctor, options);
4367
+ }, 2);
4368
+ cerMethod("get", function get(name) {
4369
+ const def = ceStateOf(this).defs.get(String(name));
4370
+ return def ? def.ctor : undefined;
4371
+ }, 1);
4372
+ cerMethod("getName", function getName(ctor) {
4373
+ const state = ceStateOf(this);
2995
4374
  if (typeof ctor !== "function") {
2996
- throw new TypeError("The custom element constructor is not a constructor");
4375
+ throw new TypeError("Failed to execute 'getName' on 'CustomElementRegistry': parameter 1 is not of type 'Function'.");
2997
4376
  }
2998
- for (const [n, c] of ceRegistry) if (c === ctor) return n;
4377
+ for (const [n, def] of state.defs) if (def.ctor === ctor) return n;
2999
4378
  return null;
3000
- });
3001
- cerMethod("whenDefined", function (name) {
4379
+ }, 1);
4380
+ cerMethod("whenDefined", function whenDefined(name) {
4381
+ let state;
4382
+ try { state = ceStateOf(this); } catch (e) { return Promise.reject(e); }
4383
+ name = String(name);
3002
4384
  if (!isValidCustomElementName(name)) {
3003
4385
  return Promise.reject(new DOMException("'" + name + "' is not a valid custom element name", "SyntaxError"));
3004
4386
  }
3005
- return whenDefinedCustomElement(name);
3006
- });
3007
- // Delegate manual upgrades to Dommy's registry (define() already upgrades
3008
- // existing nodes; this covers subtrees attached without reactions).
3009
- cerMethod("upgrade", function (root) { if (isProxy(root)) __rb_upgrade_custom_elements(root[HKEY]); });
4387
+ const def = state.defs.get(name);
4388
+ if (def) return Promise.resolve(def.ctor);
4389
+ let entry = state.pending.get(name);
4390
+ if (!entry) {
4391
+ let resolve;
4392
+ const promise = new Promise((r) => { resolve = r; });
4393
+ entry = { promise, resolve };
4394
+ state.pending.set(name, entry);
4395
+ }
4396
+ return entry.promise;
4397
+ }, 1);
4398
+ cerMethod("initialize", function initialize(root) {
4399
+ ceStateOf(this);
4400
+ if (!isProxy(root) || !interfaceChainOf(root).includes("Node")) {
4401
+ throw new TypeError("Failed to execute 'initialize' on 'CustomElementRegistry': parameter 1 is not of type 'Node'.");
4402
+ }
4403
+ const raised = __rb_initialize_custom_element_registry(this[HKEY], root[HKEY]);
4404
+ if (raised && typeof raised === "object" && raised.__rb_exception__) throw makeHostError(raised.__rb_exception__);
4405
+ }, 1);
4406
+ cerMethod("upgrade", function upgrade(root) {
4407
+ ceStateOf(this);
4408
+ if (!isProxy(root) || !interfaceChainOf(root).includes("Node")) {
4409
+ throw new TypeError("Failed to execute 'upgrade' on 'CustomElementRegistry': parameter 1 is not of type 'Node'.");
4410
+ }
4411
+ const raised = __rb_upgrade_custom_elements(this[HKEY], root[HKEY]);
4412
+ if (raised && typeof raised === "object" && raised.__rb_exception__) throw makeHostError(raised.__rb_exception__);
4413
+ }, 1);
3010
4414
  globalThis.CustomElementRegistry = CustomElementRegistry;
3011
- globalThis.customElements = Object.create(cerProto);
4415
+
4416
+ // CustomStateSet (HTML §4.13.7.5): ElementInternals' `states`, a setlike of
4417
+ // the element's custom states. The Set lives here; each change is mirrored
4418
+ // to the host ElementInternals, which `:state()` matches against.
4419
+ const customStateSetData = new WeakMap();
4420
+ const internalsStates = new WeakMap();
4421
+ function CustomStateSet() { throw new TypeError("Illegal constructor"); }
4422
+ const cssProto = CustomStateSet.prototype;
4423
+ Object.defineProperty(cssProto, Symbol.toStringTag, { value: "CustomStateSet", configurable: true });
4424
+ function customStateSetOf(object) {
4425
+ const data = customStateSetData.get(object);
4426
+ if (!data) throw new TypeError("Illegal invocation: not a CustomStateSet");
4427
+ return data;
4428
+ }
4429
+ function syncCustomStates(data) {
4430
+ bumpDomEpoch();
4431
+ const raised = __rb_host_call(data.internals[HKEY], "__setStates", dehydrateArgs([Array.from(data.set)]));
4432
+ bumpDomEpoch();
4433
+ if (raised && typeof raised === "object" && raised.__rb_exception__) throw makeHostError(raised.__rb_exception__);
4434
+ }
4435
+ const cssMethod = (key, fn, length) => {
4436
+ Object.defineProperty(fn, "length", { value: length, configurable: true });
4437
+ Object.defineProperty(cssProto, key, { value: fn, writable: true, enumerable: true, configurable: true });
4438
+ };
4439
+ cssMethod("add", function add(value) {
4440
+ const data = customStateSetOf(this);
4441
+ value = String(value);
4442
+ if (!data.set.has(value)) { data.set.add(value); syncCustomStates(data); }
4443
+ return this;
4444
+ }, 1);
4445
+ cssMethod("delete", function (value) {
4446
+ const data = customStateSetOf(this);
4447
+ const removed = data.set.delete(String(value));
4448
+ if (removed) syncCustomStates(data);
4449
+ return removed;
4450
+ }, 1);
4451
+ cssMethod("has", function has(value) { return customStateSetOf(this).set.has(String(value)); }, 1);
4452
+ cssMethod("clear", function clear() {
4453
+ const data = customStateSetOf(this);
4454
+ if (data.set.size) { data.set.clear(); syncCustomStates(data); }
4455
+ }, 0);
4456
+ cssMethod("forEach", function forEach(callback, thisArg) {
4457
+ const data = customStateSetOf(this);
4458
+ if (typeof callback !== "function") throw new TypeError("CustomStateSet.forEach: the callback is not a function");
4459
+ data.set.forEach((value) => callback.call(thisArg, value, value, this));
4460
+ }, 1);
4461
+ cssMethod("entries", function entries() { return customStateSetOf(this).set.entries(); }, 0);
4462
+ const cssValues = function values() { return customStateSetOf(this).set.values(); };
4463
+ cssMethod("values", cssValues, 0);
4464
+ Object.defineProperty(cssProto, "keys", { value: cssValues, writable: true, enumerable: true, configurable: true });
4465
+ Object.defineProperty(cssProto, Symbol.iterator, { value: cssValues, writable: true, configurable: true });
4466
+ Object.defineProperty(cssProto, "size", {
4467
+ get: function size() { return customStateSetOf(this).set.size; }, enumerable: true, configurable: true,
4468
+ });
4469
+ globalThis.CustomStateSet = CustomStateSet;
4470
+
4471
+ // ElementInternals.prototype.states ([SameObject]).
4472
+ function installElementInternalsStates(proto) {
4473
+ Object.defineProperty(proto, "states", {
4474
+ get: function states() {
4475
+ checkReceiver(this, "ElementInternals", "states");
4476
+ let set = internalsStates.get(this);
4477
+ if (!set) {
4478
+ // The host keeps the states too, so a set made again for a proxy
4479
+ // that was collected (and its set with it) starts from them.
4480
+ const current = rehydrate(__rb_host_get(this[HKEY], "__states")) || [];
4481
+ set = Object.create(cssProto);
4482
+ customStateSetData.set(set, { set: new Set(current), internals: this });
4483
+ internalsStates.set(this, set);
4484
+ }
4485
+ return set;
4486
+ },
4487
+ enumerable: true, configurable: true,
4488
+ });
4489
+ }
4490
+ // The bare `customElements` global is the window's registry (bound once the
4491
+ // window is: see exposeConstructorsOnWindow).
3012
4492
 
3013
4493
  // ===== Unhandled-rejection detail capture (opt-in diagnostics) =====
3014
4494
  //
@@ -3085,10 +4565,12 @@ globalThis.__rbHost = (function () {
3085
4565
  installRejectionTracker,
3086
4566
  // The engine's promise-rejection hook (see onPromiseRejection).
3087
4567
  onPromiseRejection,
3088
- seedInterfaces, invokeLifecycle, upgradeInPlace, attachStatics, exposeConstructorsOnWindow,
4568
+ // Structured serialization records Ruby holds (Dommy::Js::SerializedRecord).
4569
+ deserializeRecord, releaseRecord,
4570
+ seedInterfaces, ceConstruct, ceUpgrade, ceInvoke, attachStatics, exposeConstructorsOnWindow,
3089
4571
  // Realm wiring the Ruby bridge drives, kept here rather than as JS built in
3090
4572
  // Ruby strings (see defineGlobal / defineLegacyEventAccessor).
3091
- defineGlobal, exposeConstructorsOnSubWindow, defineLegacyEventAccessor, wireInlineHandlers,
4573
+ defineGlobal, exposeConstructorsOnSubWindow, defineLegacyEventAccessor, compileEventHandler,
3092
4574
  // wasm host bridge (handle-oriented access for a wasm guest)
3093
4575
  wasmGlobalRef, wasmEval, wasmGet, wasmSet, wasmCall, wasmApply, wasmNew,
3094
4576
  wasmTypeof, wasmToString, wasmStrictEqual, wasmIsNull, wasmInstanceof,