Skip to content

Truly independent web browser

LibWeb: Resolve WebIDL promises without running script

Tim Ledbetter81f9fff5ab61
diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs
index ce3b2c9aada..2b25969ddfe 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs
@@ -728,8 +728,6 @@ impl Animation {
// resolved Promise with the animation itself as its value and created in the relevant Realm of the animation.
// NB: A promise the procedures replaced, which script did not ask for yet, is pending while the animation has
// a pending play or pause task.
- // NB: Resolving the promise with the animation reads its "then" property, which script can observe, so the
- // promise is the current one before it is resolved.
let promise = create_promise(vm, self.realm);
self.current_ready_promise.set(Some(promise));
if !self.record.pending() {
@@ -746,7 +744,6 @@ impl Animation {
// The current finished promise is initially a pending Promise object.
// NB: A promise the procedures resolved, which script did not ask for yet, is resolved while the animation is
// finished.
- // NB: As with the current ready promise, the promise is the current one before it is resolved.
let promise = create_promise(vm, self.realm);
self.current_finished_promise.set(Some(promise));
if self.record.playback().is_finished {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
index de02c2204fc..2bcfa3abccf 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
@@ -14,6 +14,7 @@ use core::ptr::NonNull;
use libjs_rust::api::{
Array, EmbedderCell, EmbedderClass, EmbedderValue, Gc, Must, NativeFunction, Object, Promise, PromiseCapability,
PromiseState, PropertyKey, Realm, RejectionOperation, Trace, Value, Visitor, Vm, call, new_promise_capability,
+ safe_promise_resolve,
};
use crate::bindings::interface::{with_temporary_execution_context, with_temporary_execution_context_and_callbacks};
@@ -174,13 +175,9 @@ pub(crate) fn resolve_promise(vm: &Vm, promise: WebIdlPromise, value: Value) {
// 1. If x is not given, then let it be the undefined value.
// 2. Let value be the result of converting x to an ECMAScript value.
// 3. Perform ! Call(p.[[Resolve]], undefined, « value »).
- call(
- vm,
- Value::from_object(promise.resolve().upcast::<Object>()),
- Value::UNDEFINED,
- &[value],
- )
- .must();
+ // AD-HOC: We perform SafePromiseResolve instead, which never runs script.
+ // See https://github.com/whatwg/webidl/pull/1645
+ safe_promise_resolve(vm, promise, value).must();
}
/// Rejects the promise with the reason, https://webidl.spec.whatwg.org/#reject
diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs
index 06cfe0cf52d..98379b74aae 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/css/font_face_set.rs
@@ -28,8 +28,8 @@ use crate::bindings::interface::{
with_temporary_execution_context_and_callbacks,
};
use crate::bindings::promise::{
- TaskSource, WebIdlPromise, create_promise, get_promise_for_wait_for_all, is_promise_fulfilled, promise_from_abi,
- queue_a_task, react_to_promise, reject_promise, reject_promise_with_exception, resolve_promise,
+ TaskSource, WebIdlPromise, create_promise, get_promise_for_wait_for_all, promise_from_abi, queue_a_task,
+ react_to_promise, reject_promise, reject_promise_with_exception, resolve_promise,
};
use crate::bindings::setlike::context_of_set;
use crate::bindings::setlike::{Setlike, WorldEntries};
@@ -198,6 +198,7 @@ pub(crate) struct FontFaceSet {
#[gc(untraced)]
status: Cell<FontFaceSetLoadStatus>,
is_pending_on_the_environment: Cell<bool>,
+ ready_promise_is_resolved: Cell<bool>,
}
impl Wrappable for FontFaceSet {
@@ -232,6 +233,7 @@ impl FontFaceSet {
failed_fonts: GcRefCell::new(Vec::new()),
status: Cell::new(FontFaceSetLoadStatus::Loaded),
is_pending_on_the_environment: Cell::new(true),
+ ready_promise_is_resolved: Cell::new(false),
});
object.this.set(Some(object));
object.event_target.set_owner(object);
@@ -658,7 +660,7 @@ impl FontFaceSet {
pub(crate) fn ready(&self, _: &mut CallContext) -> WebIdlResult<WebIdlPromise> {
// Pending style or layout changes can start a deferred font load. Flush them before returning an already
// fulfilled promise so switching the FontFaceSet to loading can replace it with a new pending promise.
- if is_promise_fulfilled(self.ready_promise()) {
+ if self.ready_promise_is_resolved.get() {
// SAFETY: The set is live.
unsafe { web_css_font_face_set_update_layout(self.as_abi(), false) };
}
@@ -726,7 +728,9 @@ impl FontFaceSet {
// 3. If font face set’s [[ReadyPromise]] slot currently holds a fulfilled promise, replace it with a fresh
// pending promise.
- if is_promise_fulfilled(self.ready_promise()) {
+ // AD-HOC: A promise that was resolved with a set whose "then" lookup may run script is fulfilled later, so
+ // we check whether the promise was resolved instead.
+ if self.ready_promise_is_resolved.replace(false) {
let realm = self.realm;
self.ready_promise.set(Some(with_temporary_execution_context(realm, || {
create_promise(vm, realm)
@@ -763,6 +767,7 @@ impl FontFaceSet {
// 4. Fulfill font face set’s [[ReadyPromise]] attribute’s value with font face set.
let realm = self.realm;
+ self.ready_promise_is_resolved.set(true);
with_temporary_execution_context_and_callbacks(realm, || {
let cx = CallContext::new(vm, realm);
let value = self.this().to_js(&cx).expect("wrapping a FontFaceSet can't throw");
diff --git a/Libraries/LibWeb/WebIDL/Promise.cpp b/Libraries/LibWeb/WebIDL/Promise.cpp
index ae6c7cb43e4..ae405195ac8 100644
--- a/Libraries/LibWeb/WebIDL/Promise.cpp
+++ b/Libraries/LibWeb/WebIDL/Promise.cpp
@@ -68,7 +68,9 @@ GC::Ref<Promise> create_resolved_promise(JS::Realm& realm, JS::Value value)
auto promise_capability = MUST(JS::new_promise_capability(vm, constructor));
// 4. Perform ! Call(promiseCapability.[[Resolve]], undefined, « value »).
- MUST(JS::call(vm, *promise_capability->resolve(), JS::js_undefined(), value));
+ // AD-HOC: We perform SafePromiseResolve instead, which never runs script.
+ // See https://github.com/whatwg/webidl/pull/1645
+ MUST(JS::safe_promise_resolve(vm, promise_capability, value));
// 5. Return promiseCapability.
return promise_capability;
@@ -148,7 +150,9 @@ void resolve_promise(JS::Realm& realm, Promise const& promise, JS::Value value)
// 2. Let value be the result of converting x to an ECMAScript value.
// 3. Perform ! Call(p.[[Resolve]], undefined, « value »).
- MUST(JS::call(vm, *promise.resolve(), JS::js_undefined(), value));
+ // AD-HOC: We perform SafePromiseResolve instead, which never runs script.
+ // See https://github.com/whatwg/webidl/pull/1645
+ MUST(JS::safe_promise_resolve(vm, promise, value));
}
void resolve_promise(Promise const& promise, JS::Value value)
diff --git a/Meta/Generators/libweb_bindings/to_idl_value.py b/Meta/Generators/libweb_bindings/to_idl_value.py
index 7071d5150e1..4687dd19145 100644
--- a/Meta/Generators/libweb_bindings/to_idl_value.py
+++ b/Meta/Generators/libweb_bindings/to_idl_value.py
@@ -973,7 +973,9 @@ def promise_to_idl_value(
auto promise_capability0 = TRY(JS::new_promise_capability(vm, realm.intrinsics().promise_constructor()));
// 2. Perform ? Call(promiseCapability.[[Resolve]], undefined, « V »).
- TRY(JS::call(vm, *promise_capability0->resolve(), JS::js_undefined(), {value_name}));
+ // AD-HOC: We perform SafePromiseResolve instead, which never runs script.
+ // See https://github.com/whatwg/webidl/pull/1645
+ TRY(JS::safe_promise_resolve(vm, *promise_capability0, {value_name}));
// 3. Return promiseCapability.
return promise_capability0;
diff --git a/Tests/LibWeb/Crash/Animations/then-getter-of-animation-resolved-in-style-update.html b/Tests/LibWeb/Crash/Animations/then-getter-of-animation-resolved-in-style-update.html
new file mode 100644
index 00000000000..4650a2938e8
--- /dev/null
+++ b/Tests/LibWeb/Crash/Animations/then-getter-of-animation-resolved-in-style-update.html
@@ -0,0 +1,47 @@
+<!DOCTYPE html>
+<html class="test-wait">
+<style>
+ @keyframes fade {
+ from { opacity: 0; }
+ to { opacity: 1; }
+ }
+ #scroller {
+ width: 100px;
+ height: 100px;
+ overflow: scroll;
+ }
+ #content {
+ height: 1000px;
+ }
+ #target {
+ animation: fade 1s linear;
+ animation-timeline: scroll();
+ }
+</style>
+<div id="scroller"><div id="content"><div id="target"></div></div></div>
+<script>
+ function animationFrame() {
+ return new Promise(resolve => requestAnimationFrame(resolve));
+ }
+
+ (async () => {
+ scroller.scrollTop = 300;
+ await animationFrame();
+ await animationFrame();
+ const animation = target.getAnimations()[0];
+ Object.defineProperty(animation, "then", {
+ get() {
+ target.style.display = "none";
+ document.body.offsetWidth;
+ return undefined;
+ },
+ });
+ target.style.animationPlayState = "paused";
+ getComputedStyle(target).opacity;
+ target.style.animationTimeline = "auto";
+ getComputedStyle(target).color;
+ await animationFrame();
+ document.documentElement.classList.remove("test-wait");
+ })();
+</script>
+</html>
diff --git a/Tests/LibWeb/Crash/CSS/font-face-set-then-getter-resolved-in-style-update.html b/Tests/LibWeb/Crash/CSS/font-face-set-then-getter-resolved-in-style-update.html
new file mode 100644
index 00000000000..78661a7e823
--- /dev/null
+++ b/Tests/LibWeb/Crash/CSS/font-face-set-then-getter-resolved-in-style-update.html
@@ -0,0 +1,34 @@
+<!DOCTYPE html>
+<html class="test-wait">
+<iframe id="frame" style="width: 300px; height: 100px"></iframe>
+<script>
+ function animationFrame() {
+ return new Promise(resolve => requestAnimationFrame(resolve));
+ }
+
+ (async () => {
+ await animationFrame();
+ await animationFrame();
+ const doc = frame.contentDocument;
+ await doc.fonts.ready;
+ const style = doc.createElement("style");
+ style.textContent = "@media (min-width: 200px) { @font-face { font-family: test; src: url(data:font/woff;base64,AAAA) } }";
+ doc.head.append(style);
+ doc.body.innerHTML = '<div id="target" style="font-family: test">Hello</div>';
+ const target = doc.getElementById("target");
+ frame.contentWindow.getComputedStyle(target).fontFamily;
+ target.offsetWidth;
+ Object.defineProperty(doc.fonts, "then", {
+ get() {
+ target.style.display = "none";
+ doc.body.offsetWidth;
+ return undefined;
+ },
+ });
+ frame.style.width = "100px";
+ frame.contentWindow.getComputedStyle(target).fontFamily;
+ await animationFrame();
+ document.documentElement.classList.remove("test-wait");
+ })();
+</script>
+</html>
diff --git a/Tests/LibWeb/Text/expected/Streams/stream-steps-after-script-changed-the-stream.txt b/Tests/LibWeb/Text/expected/Streams/stream-steps-after-script-changed-the-stream.txt
index 6c978c932b9..1becced2a34 100644
--- a/Tests/LibWeb/Text/expected/Streams/stream-steps-after-script-changed-the-stream.txt
+++ b/Tests/LibWeb/Text/expected/Streams/stream-steps-after-script-changed-the-stream.txt
@@ -2,4 +2,3 @@ abort after terminate: survived
write while closing: TypeError
write after cancel: undefined
cancel during transform: TypeError
-release between requests: fulfilled rejected
diff --git a/Tests/LibWeb/Text/expected/WebAnimations/animation-ready-then-method-called-outside-script.txt b/Tests/LibWeb/Text/expected/WebAnimations/animation-ready-then-method-called-outside-script.txt
new file mode 100644
index 00000000000..58d7ec5c8cf
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebAnimations/animation-ready-then-method-called-outside-script.txt
@@ -0,0 +1 @@
+then method of the animation called: true
diff --git a/Tests/LibWeb/Text/expected/WebAnimations/ready-promise-read-while-resolving.txt b/Tests/LibWeb/Text/expected/WebAnimations/ready-promise-read-while-resolving.txt
deleted file mode 100644
index 6a89623d591..00000000000
--- a/Tests/LibWeb/Text/expected/WebAnimations/ready-promise-read-while-resolving.txt
+++ /dev/null
@@ -1 +0,0 @@
-ready: read while resolving is the same promise: true, later read too: true
diff --git a/Tests/LibWeb/Text/expected/WebIDL/promise-resolution-defers-user-code.txt b/Tests/LibWeb/Text/expected/WebIDL/promise-resolution-defers-user-code.txt
new file mode 100644
index 00000000000..3a0cb1520fc
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/WebIDL/promise-resolution-defers-user-code.txt
@@ -0,0 +1,15 @@
+a promise resolved with a value that has a then getter: operation returned, then getter ran, fulfilled with the value: true
+resolve with a value that has a then getter: operation returned, then getter ran, fulfilled with the value: true
+resolve with a value that inherits a then getter from Object.prototype: operation returned, then getter ran, fulfilled with the value: true
+resolve with a value whose then getter throws: operation returned, rejected with the exception of the getter: true
+resolve with a value that has a then method: operation returned, then method called on the value: true, arguments: function,function, fulfilled with the value passed by the then method
+resolve with a value that has a then method, and a microtask queued afterwards: then method called, microtask ran
+resolve with a value that has no then property, and a microtask queued afterwards: promise reaction ran, microtask ran
+resolve with a proxy: operation returned, proxy get trap ran, fulfilled with the value: true
+resolve with a value that has a proxy on its prototype chain: operation returned, proxy get trap ran, fulfilled with the value: true
+resolve the promise of a pending read() while Object.prototype has a then getter: then getter calls before enqueue() returned: 0, then getter ran on the result of read()
+resolve the promise of a pending read(), and a microtask queued afterwards: promise reaction ran, microtask ran
+convert a callback return value that has a then getter to a promise: cancel() method called, operation returned, then getter ran
+convert a callback return value whose prototype chain is too deep to walk to a promise: cancel() method called, operation returned, promise settled
+convert an HTMLCollection that has an element named then to a promise: cancel() method called, proxy traps that ran before the operation returned: 0, proxy traps ran afterwards: true
+resolve with an animation that has an HTMLCollection on its prototype chain: proxy traps that ran before the operation returned: 0, proxy traps ran afterwards: true
diff --git a/Tests/LibWeb/Text/expected/wpt-import/streams/readable-byte-streams/patched-global.any.txt b/Tests/LibWeb/Text/expected/wpt-import/streams/readable-byte-streams/patched-global.any.txt
index 5d77fec2af1..3bb60b8346f 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/streams/readable-byte-streams/patched-global.any.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/streams/readable-byte-streams/patched-global.any.txt
@@ -2,5 +2,5 @@ Harness status: OK
Found 1 tests
-1 Pass
-Pass Patched then() sees byobRequest after filling all pending pull-into descriptors
\ No newline at end of file
+1 Fail
+Fail Patched then() sees byobRequest after filling all pending pull-into descriptors
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/Streams/stream-steps-after-script-changed-the-stream.html b/Tests/LibWeb/Text/input/Streams/stream-steps-after-script-changed-the-stream.html
index 57074d7e337..0e98af06f0c 100644
--- a/Tests/LibWeb/Text/input/Streams/stream-steps-after-script-changed-the-stream.html
+++ b/Tests/LibWeb/Text/input/Streams/stream-steps-after-script-changed-the-stream.html
@@ -61,29 +61,10 @@
println(`cancel during transform: ${await writer.write(chunk).catch(error => error.name)}`);
}
- async function releaseBetweenRequests() {
- let controller;
- const stream = new ReadableStream({ type: "bytes", start: c => (controller = c) });
- const reader = stream.getReader({ mode: "byob" });
- const reads = [reader.read(new Uint8Array(1)), reader.read(new Uint8Array(1))];
- Object.defineProperty(Object.prototype, "then", {
- configurable: true,
- get() {
- delete Object.prototype.then;
- reader.releaseLock();
- },
- });
- controller.enqueue(new Uint8Array([1, 2]));
- delete Object.prototype.then;
- const results = await Promise.allSettled(reads);
- println(`release between requests: ${results.map(result => result.status).join(" ")}`);
- }
-
promiseTest(async () => {
await abortAfterTerminate();
await writeWhileClosing();
await writeAfterCancel();
await cancelDuringTransform();
- await releaseBetweenRequests();
});
</script>
diff --git a/Tests/LibWeb/Text/input/WebAnimations/animation-ready-then-method-called-outside-script.html b/Tests/LibWeb/Text/input/WebAnimations/animation-ready-then-method-called-outside-script.html
new file mode 100644
index 00000000000..f639e6c1e94
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebAnimations/animation-ready-then-method-called-outside-script.html
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<div id="target"></div>
+<script>
+ promiseTest(async () => {
+ const effect = new KeyframeEffect(target, [{ opacity: 0 }, { opacity: 1 }], { duration: 100000 });
+ const animation = new Animation(effect, document.timeline);
+ let thenCalled = false;
+ animation.then = function (resolve) {
+ thenCalled = true;
+ delete animation.then;
+ resolve();
+ };
+ animation.play();
+ await animationFrame();
+ await animationFrame();
+ println(`then method of the animation called: ${thenCalled}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/WebAnimations/ready-promise-read-while-resolving.html b/Tests/LibWeb/Text/input/WebAnimations/ready-promise-read-while-resolving.html
deleted file mode 100644
index bcea745e027..00000000000
--- a/Tests/LibWeb/Text/input/WebAnimations/ready-promise-read-while-resolving.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<!DOCTYPE html>
-<script src="../include.js"></script>
-<script>
- function readWhileResolving(animation, name) {
- let inner;
- Object.defineProperty(animation, "then", {
- configurable: true,
- get() {
- delete animation.then;
- inner = animation[name];
- return undefined;
- },
- });
- const outer = animation[name];
- println(`${name}: read while resolving is the same promise: ${inner === outer}, later read too: ${animation[name] === outer}`);
- }
-
- test(() => {
- readWhileResolving(new Animation(), "ready");
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/WebIDL/promise-resolution-defers-user-code.html b/Tests/LibWeb/Text/input/WebIDL/promise-resolution-defers-user-code.html
new file mode 100644
index 00000000000..c72d31345b1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/WebIDL/promise-resolution-defers-user-code.html
@@ -0,0 +1,250 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<!-- FIXME: Import the tests of https://github.com/web-platform-tests/wpt/pull/64001 in place of this one once they are merged. -->
+<script>
+ let elementNameCount = 0;
+
+ function promiseResolvedWith(constructor) {
+ const name = `x-promise-resolution-${elementNameCount++}`;
+ customElements.define(name, constructor);
+ return customElements.whenDefined(name);
+ }
+
+ function resolvePromiseWith(constructor) {
+ const name = `x-promise-resolution-${elementNameCount++}`;
+ const promise = customElements.whenDefined(name);
+ customElements.define(name, constructor);
+ return promise;
+ }
+
+ function convertToPromise(value, log) {
+ const stream = new ReadableStream({
+ cancel() {
+ log.push("cancel() method called");
+ return value;
+ },
+ });
+ return stream.cancel();
+ }
+
+ function proxyLoggingThenLookups(target, log) {
+ const logThenLookup = trap => (...args) => {
+ if (args[1] === "then")
+ log.push(`proxy ${trap} trap ran`);
+ return Reflect[trap](...args);
+ };
+ return new Proxy(target, {
+ get: logThenLookup("get"),
+ has: logThenLookup("has"),
+ getOwnPropertyDescriptor: logThenLookup("getOwnPropertyDescriptor"),
+ });
+ }
+
+ async function withPrototypeOf(object, prototype, callback) {
+ const originalPrototype = Object.getPrototypeOf(object);
+ Object.setPrototypeOf(object, prototype);
+ try {
+ return await callback();
+ } finally {
+ Object.setPrototypeOf(object, originalPrototype);
+ }
+ }
+
+ const cases = {
+ "a promise resolved with a value that has a then getter": async log => {
+ class Element extends HTMLElement {
+ static get then() {
+ log.push("then getter ran");
+ }
+ }
+ const promise = promiseResolvedWith(Element);
+ log.push("operation returned");
+ log.push(`fulfilled with the value: ${(await promise) === Element}`);
+ },
+
+ "resolve with a value that has a then getter": async log => {
+ class Element extends HTMLElement {
+ static get then() {
+ log.push("then getter ran");
+ }
+ }
+ const promise = resolvePromiseWith(Element);
+ log.push("operation returned");
+ log.push(`fulfilled with the value: ${(await promise) === Element}`);
+ },
+
+ "resolve with a value that inherits a then getter from Object.prototype": async log => {
+ class Element extends HTMLElement {}
+ Object.defineProperty(Object.prototype, "then", {
+ configurable: true,
+ get() {
+ if (this === Element)
+ log.push("then getter ran");
+ },
+ });
+ try {
+ const promise = resolvePromiseWith(Element);
+ log.push("operation returned");
+ log.push(`fulfilled with the value: ${(await promise) === Element}`);
+ } finally {
+ delete Object.prototype.then;
+ }
+ },
+
+ "resolve with a value whose then getter throws": async log => {
+ const error = new Error();
+ class Element extends HTMLElement {
+ static get then() {
+ throw error;
+ }
+ }
+ const promise = resolvePromiseWith(Element);
+ log.push("operation returned");
+ await promise.then(
+ () => log.push("fulfilled"),
+ reason => log.push(`rejected with the exception of the getter: ${reason === error}`)
+ );
+ },
+
+ "resolve with a value that has a then method": async log => {
+ class Element extends HTMLElement {
+ static then(...args) {
+ log.push(`then method called on the value: ${this === Element}`);
+ log.push(`arguments: ${args.map(argument => typeof argument)}`);
+ args[0]("the value passed by the then method");
+ }
+ }
+ const promise = resolvePromiseWith(Element);
+ log.push("operation returned");
+ log.push(`fulfilled with ${await promise}`);
+ },
+
+ "resolve with a value that has a then method, and a microtask queued afterwards": async log => {
+ class Element extends HTMLElement {
+ static then(resolve) {
+ log.push("then method called");
+ resolve();
+ }
+ }
+ const promise = resolvePromiseWith(Element);
+ Promise.resolve().then(() => log.push("microtask ran"));
+ await promise;
+ },
+
+ "resolve with a value that has no then property, and a microtask queued afterwards": async log => {
+ const name = `x-promise-resolution-${elementNameCount++}`;
+ const promise = customElements.whenDefined(name);
+ promise.then(() => log.push("promise reaction ran"));
+ customElements.define(name, class extends HTMLElement {});
+ Promise.resolve().then(() => log.push("microtask ran"));
+ await promise;
+ },
+
+ "resolve with a proxy": async log => {
+ const proxy = proxyLoggingThenLookups(class extends HTMLElement {}, log);
+ const promise = resolvePromiseWith(proxy);
+ log.push("operation returned");
+ log.push(`fulfilled with the value: ${(await promise) === proxy}`);
+ },
+
+ "resolve with a value that has a proxy on its prototype chain": async log => {
+ class Element extends HTMLElement {}
+ Object.setPrototypeOf(Element, proxyLoggingThenLookups(HTMLElement, log));
+ const promise = resolvePromiseWith(Element);
+ log.push("operation returned");
+ log.push(`fulfilled with the value: ${(await promise) === Element}`);
+ },
+
+ "resolve the promise of a pending read() while Object.prototype has a then getter": async log => {
+ let controller;
+ const reader = new ReadableStream({ start: c => (controller = c) }).getReader();
+ const read = reader.read();
+ const chunk = {};
+ let lookupCount = 0;
+ Object.defineProperty(Object.prototype, "then", {
+ configurable: true,
+ get() {
+ ++lookupCount;
+ if (this.value === chunk)
+ log.push("then getter ran on the result of read()");
+ },
+ });
+ try {
+ controller.enqueue(chunk);
+ log.push(`then getter calls before enqueue() returned: ${lookupCount}`);
+ await read;
+ } finally {
+ delete Object.prototype.then;
+ }
+ },
+
+ "resolve the promise of a pending read(), and a microtask queued afterwards": async log => {
+ let controller;
+ const reader = new ReadableStream({ start: c => (controller = c) }).getReader();
+ const read = reader.read();
+ read.then(() => log.push("promise reaction ran"));
+ controller.enqueue("chunk");
+ Promise.resolve().then(() => log.push("microtask ran"));
+ await read;
+ },
+
+ "convert a callback return value that has a then getter to a promise": async log => {
+ const value = {
+ get then() {
+ log.push("then getter ran");
+ },
+ };
+ const promise = convertToPromise(value, log);
+ log.push("operation returned");
+ await promise;
+ },
+
+ "convert a callback return value whose prototype chain is too deep to walk to a promise": async log => {
+ let value = {};
+ for (let i = 0; i < 200000; ++i)
+ value = Object.create(value);
+ const promise = convertToPromise(value, log);
+ log.push("operation returned");
+ await promise.catch(() => {});
+ log.push("promise settled");
+ },
+
+ "convert an HTMLCollection that has an element named then to a promise": async log => {
+ const form = document.createElement("form");
+ form.name = "then";
+ document.body.append(form);
+ const traps = [];
+ const prototype = proxyLoggingThenLookups(Object.getPrototypeOf(HTMLCollection.prototype), traps);
+ await withPrototypeOf(HTMLCollection.prototype, prototype, async () => {
+ const promise = convertToPromise(document.forms, log);
+ log.push(`proxy traps that ran before the operation returned: ${traps.length}`);
+ await promise;
+ });
+ log.push(`proxy traps ran afterwards: ${traps.length > 0}`);
+ form.remove();
+ },
+
+ "resolve with an animation that has an HTMLCollection on its prototype chain": async log => {
+ const animation = new Animation();
+ const finished = animation.finished;
+ const traps = [];
+ const prototype = proxyLoggingThenLookups(Object.getPrototypeOf(HTMLCollection.prototype), traps);
+ await withPrototypeOf(HTMLCollection.prototype, prototype, () =>
+ withPrototypeOf(Animation.prototype, document.forms, async () => {
+ animation.finish();
+ log.push(`proxy traps that ran before the operation returned: ${traps.length}`);
+ await finished;
+ })
+ );
+ log.push(`proxy traps ran afterwards: ${traps.length > 0}`);
+ },
+ };
+
+ promiseTest(async () => {
+ for (const [name, run] of Object.entries(cases)) {
+ const log = [];
+ await run(log);
+ println(`${name}: ${log.join(", ")}`);
+ }
+ });
+</script>