mirror of
https://github.com/nodejs/node.git
synced 2025-08-15 13:48:44 +02:00

The AbortController abort event is trusted, currently we fire all events with isTrusted: false. Allow dispatching events internally with `isTrusted: true` and add a test for it. Co-Authored-By: ExE Boss <3889017+ExE-Boss@users.noreply.github.com> Fixes: https://github.com/nodejs/node/issues/35748 PR-URL: https://github.com/nodejs/node/pull/35811 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
90 lines
2 KiB
JavaScript
90 lines
2 KiB
JavaScript
'use strict';
|
|
|
|
// Modeled very closely on the AbortController implementation
|
|
// in https://github.com/mysticatea/abort-controller (MIT license)
|
|
|
|
const {
|
|
ObjectAssign,
|
|
ObjectDefineProperties,
|
|
Symbol,
|
|
} = primordials;
|
|
|
|
const {
|
|
EventTarget,
|
|
Event,
|
|
kTrustEvent
|
|
} = require('internal/event_target');
|
|
const {
|
|
customInspectSymbol,
|
|
emitExperimentalWarning
|
|
} = require('internal/util');
|
|
const { inspect } = require('internal/util/inspect');
|
|
|
|
const kAborted = Symbol('kAborted');
|
|
|
|
function customInspect(self, obj, depth, options) {
|
|
if (depth < 0)
|
|
return self;
|
|
|
|
const opts = ObjectAssign({}, options, {
|
|
depth: options.depth === null ? null : options.depth - 1
|
|
});
|
|
|
|
return `${self.constructor.name} ${inspect(obj, opts)}`;
|
|
}
|
|
|
|
class AbortSignal extends EventTarget {
|
|
get aborted() { return !!this[kAborted]; }
|
|
|
|
[customInspectSymbol](depth, options) {
|
|
return customInspect(this, {
|
|
aborted: this.aborted
|
|
}, depth, options);
|
|
}
|
|
}
|
|
|
|
ObjectDefineProperties(AbortSignal.prototype, {
|
|
aborted: { enumerable: true }
|
|
});
|
|
|
|
function abortSignal(signal) {
|
|
if (signal[kAborted]) return;
|
|
signal[kAborted] = true;
|
|
const event = new Event('abort', {
|
|
[kTrustEvent]: true
|
|
});
|
|
if (typeof signal.onabort === 'function') {
|
|
signal.onabort(event);
|
|
}
|
|
signal.dispatchEvent(event);
|
|
}
|
|
|
|
// TODO(joyeecheung): V8 snapshot does not support instance member
|
|
// initializers for now:
|
|
// https://bugs.chromium.org/p/v8/issues/detail?id=10704
|
|
const kSignal = Symbol('signal');
|
|
class AbortController {
|
|
constructor() {
|
|
this[kSignal] = new AbortSignal();
|
|
emitExperimentalWarning('AbortController');
|
|
}
|
|
|
|
get signal() { return this[kSignal]; }
|
|
abort() { abortSignal(this[kSignal]); }
|
|
|
|
[customInspectSymbol](depth, options) {
|
|
return customInspect(this, {
|
|
signal: this.signal
|
|
}, depth, options);
|
|
}
|
|
}
|
|
|
|
ObjectDefineProperties(AbortController.prototype, {
|
|
signal: { enumerable: true },
|
|
abort: { enumerable: true }
|
|
});
|
|
|
|
module.exports = {
|
|
AbortController,
|
|
AbortSignal,
|
|
};
|