Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[pull] master from nodejs:master #973

Merged
merged 7 commits into from
Nov 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion common.gypi
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@

# Reset this number to 0 on major V8 upgrades.
# Increment by one for each non-official patch applied to deps/v8.
'v8_embedder_string': '-node.16',
'v8_embedder_string': '-node.17',

##### V8 defaults for Node.js #####

Expand Down
7 changes: 7 additions & 0 deletions deps/v8/include/v8.h
Original file line number Diff line number Diff line change
Expand Up @@ -5020,6 +5020,13 @@ class V8_EXPORT BackingStore : public v8::internal::BackingStoreBase {
*/
bool IsShared() const;

/**
* Prevent implicit instantiation of operator delete with size_t argument.
* The size_t argument would be incorrect because ptr points to the
* internal BackingStore object.
*/
void operator delete(void* ptr) { ::operator delete(ptr); }

/**
* Wrapper around ArrayBuffer::Allocator::Reallocate that preserves IsShared.
* Assumes that the backing_store was allocated by the ArrayBuffer allocator
Expand Down
34 changes: 34 additions & 0 deletions doc/api/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,40 @@ class MyClass extends EventEmitter {
}
```

## `events.getEventListeners(emitterOrTarget, eventName)`
<!-- YAML
added:
- REPLACEME
-->
* `emitterOrTarget` {EventEmitter|EventTarget}
* `eventName` {string|symbol}
* Returns: {Function[]}

Returns a copy of the array of listeners for the event named `eventName`.

For `EventEmitter`s this behaves exactly the same as calling `.listeners` on
the emitter.

For `EventTarget`s this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.

```js
const { getEventListeners, EventEmitter } = require('events');

{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
ee.addEventListener('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
```

## `events.once(emitter, name[, options])`
<!-- YAML
added:
Expand Down
4 changes: 1 addition & 3 deletions lib/.eslintrc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,8 @@ rules:
- name: Date
- name: Error
ignore:
- stackTraceLimit
- captureStackTrace
- prepareStackTrace
- isPrototypeOf
- stackTraceLimit
- name: EvalError
- name: Float32Array
- name: Float64Array
Expand Down
26 changes: 25 additions & 1 deletion lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
'use strict';

const {
ArrayPrototypePush,
Boolean,
Error,
ErrorCaptureStackTrace,
Expand Down Expand Up @@ -74,13 +75,14 @@ const lazyDOMException = hideStackFrames((message, name) => {
return new DOMException(message, name);
});


function EventEmitter(opts) {
EventEmitter.init.call(this, opts);
}
module.exports = EventEmitter;
module.exports.once = once;
module.exports.on = on;

module.exports.getEventListeners = getEventListeners;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

Expand Down Expand Up @@ -634,6 +636,28 @@ function unwrapListeners(arr) {
return ret;
}

function getEventListeners(emitterOrTarget, type) {
// First check if EventEmitter
if (typeof emitterOrTarget.listeners === 'function') {
return emitterOrTarget.listeners(type);
}
// Require event target lazily to avoid always loading it
const { isEventTarget, kEvents } = require('internal/event_target');
if (isEventTarget(emitterOrTarget)) {
const root = emitterOrTarget[kEvents].get(type);
const listeners = [];
let handler = root?.next;
while (handler?.listener !== undefined) {
ArrayPrototypePush(listeners, handler.listener);
handler = handler.next;
}
return listeners;
}
throw new ERR_INVALID_ARG_TYPE('emitter',
['EventEmitter', 'EventTarget'],
emitterOrTarget);
}

async function once(emitter, name, options = {}) {
const signal = options ? options.signal : undefined;
validateAbortSignal(signal, 'options.signal');
Expand Down
2 changes: 2 additions & 0 deletions lib/internal/event_target.js
Original file line number Diff line number Diff line change
Expand Up @@ -636,4 +636,6 @@ module.exports = {
kNewListener,
kTrustEvent,
kRemoveListener,
kEvents,
isEventTarget,
};
6 changes: 4 additions & 2 deletions lib/internal/freeze_intrinsics.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ const {
SymbolIterator,
SyntaxError,
TypeError,
TypedArray,
TypedArrayPrototype,
Uint16Array,
Uint32Array,
Uint8Array,
Expand Down Expand Up @@ -105,7 +107,7 @@ module.exports = function() {
// AsyncGeneratorFunction
ObjectGetPrototypeOf(async function* () {}),
// TypedArray
ObjectGetPrototypeOf(Uint8Array),
TypedArrayPrototype,

// 19 Fundamental Objects
Object.prototype, // 19.1
Expand Down Expand Up @@ -189,7 +191,7 @@ module.exports = function() {
// AsyncGeneratorFunction
ObjectGetPrototypeOf(async function* () {}),
// TypedArray
ObjectGetPrototypeOf(Uint8Array),
TypedArray,

// 18 The Global Object
eval,
Expand Down
13 changes: 13 additions & 0 deletions lib/internal/per_context/primordials.js
Original file line number Diff line number Diff line change
Expand Up @@ -175,5 +175,18 @@ primordials.SafePromise = makeSafe(
copyPrototype(original.prototype, primordials, `${name}Prototype`);
});

// Create copies of abstract intrinsic objects that are not directly exposed
// on the global object.
// Refs: https://tc39.es/ecma262/#sec-%typedarray%-intrinsic-object
[
{ name: 'TypedArray', original: Reflect.getPrototypeOf(Uint8Array) },
].forEach(({ name, original }) => {
primordials[name] = original;
// The static %TypedArray% methods require a valid `this`, but can't be bound,
// as they need a subclass constructor as the receiver:
copyPrototype(original, primordials, name);
copyPrototype(original.prototype, primordials, `${name}Prototype`);
});

Object.setPrototypeOf(primordials, null);
Object.freeze(primordials);
20 changes: 11 additions & 9 deletions lib/internal/streams/pipeline.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@

const {
ArrayIsArray,
ReflectApply,
SymbolAsyncIterator,
SymbolIterator
SymbolIterator,
} = primordials;

let eos;
Expand Down Expand Up @@ -77,10 +78,6 @@ function popCallback(streams) {
return streams.pop();
}

function isPromise(obj) {
return !!(obj && typeof obj.then === 'function');
}

function isReadable(obj) {
return !!(obj && typeof obj.pipe === 'function');
}
Expand Down Expand Up @@ -222,14 +219,19 @@ function pipeline(...streams) {
const pt = new PassThrough({
objectMode: true
});
if (isPromise(ret)) {
ret
.then((val) => {

// Handle Promises/A+ spec, `then` could be a getter that throws on
// second use.
const then = ret?.then;
if (typeof then === 'function') {
ReflectApply(then, ret, [
(val) => {
value = val;
pt.end(val);
}, (err) => {
pt.destroy(err);
});
}
]);
} else if (isIterable(ret, true)) {
finishCount++;
pump(ret, pt, finish);
Expand Down
5 changes: 2 additions & 3 deletions lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@ const {
SymbolPrototypeValueOf,
SymbolIterator,
SymbolToStringTag,
TypedArrayPrototype,
Uint16Array,
Uint32Array,
Uint8Array,
Uint8ArrayPrototype,
Uint8ClampedArray,
uncurryThis,
} = primordials;
Expand Down Expand Up @@ -141,8 +141,7 @@ const setSizeGetter = uncurryThis(
const mapSizeGetter = uncurryThis(
ObjectGetOwnPropertyDescriptor(MapPrototype, 'size').get);
const typedArraySizeGetter = uncurryThis(
ObjectGetOwnPropertyDescriptor(
ObjectGetPrototypeOf(Uint8ArrayPrototype), 'length').get);
ObjectGetOwnPropertyDescriptor(TypedArrayPrototype, 'length').get);

let hexSlice;

Expand Down
5 changes: 1 addition & 4 deletions lib/internal/util/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
const {
ArrayBufferIsView,
ObjectGetOwnPropertyDescriptor,
ObjectGetPrototypeOf,
SymbolToStringTag,
Uint8ArrayPrototype,
TypedArrayPrototype,
uncurryThis,
} = primordials;

const TypedArrayPrototype = ObjectGetPrototypeOf(Uint8ArrayPrototype);

const TypedArrayProto_toStringTag =
uncurryThis(
ObjectGetOwnPropertyDescriptor(TypedArrayPrototype,
Expand Down
42 changes: 26 additions & 16 deletions lib/timers/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const {
Promise,
PromisePrototypeFinally,
PromiseReject,
} = primordials;

Expand All @@ -24,6 +25,13 @@ const lazyDOMException = hideStackFrames((message, name) => {
return new DOMException(message, name);
});

function cancelListenerHandler(clear, reject) {
if (!this._destroyed) {
clear(this);
reject(lazyDOMException('The operation was aborted', 'AbortError'));
}
}

function setTimeout(after, value, options = {}) {
const args = value !== undefined ? [value] : value;
if (options == null || typeof options !== 'object') {
Expand Down Expand Up @@ -58,20 +66,21 @@ function setTimeout(after, value, options = {}) {
return PromiseReject(
lazyDOMException('The operation was aborted', 'AbortError'));
}
return new Promise((resolve, reject) => {
let oncancel;
const ret = new Promise((resolve, reject) => {
const timeout = new Timeout(resolve, after, args, false, true);
if (!ref) timeout.unref();
insert(timeout, timeout._idleTimeout);
if (signal) {
signal.addEventListener('abort', () => {
if (!timeout._destroyed) {
// eslint-disable-next-line no-undef
clearTimeout(timeout);
reject(lazyDOMException('The operation was aborted', 'AbortError'));
}
}, { once: true });
// eslint-disable-next-line no-undef
oncancel = cancelListenerHandler.bind(timeout, clearTimeout, reject);
signal.addEventListener('abort', oncancel);
}
});
return oncancel !== undefined ?
PromisePrototypeFinally(
ret,
() => signal.removeEventListener('abort', oncancel)) : ret;
}

function setImmediate(value, options = {}) {
Expand Down Expand Up @@ -107,19 +116,20 @@ function setImmediate(value, options = {}) {
return PromiseReject(
lazyDOMException('The operation was aborted', 'AbortError'));
}
return new Promise((resolve, reject) => {
let oncancel;
const ret = new Promise((resolve, reject) => {
const immediate = new Immediate(resolve, [value]);
if (!ref) immediate.unref();
if (signal) {
signal.addEventListener('abort', () => {
if (!immediate._destroyed) {
// eslint-disable-next-line no-undef
clearImmediate(immediate);
reject(lazyDOMException('The operation was aborted', 'AbortError'));
}
}, { once: true });
// eslint-disable-next-line no-undef
oncancel = cancelListenerHandler.bind(immediate, clearImmediate, reject);
signal.addEventListener('abort', oncancel);
}
});
return oncancel !== undefined ?
PromisePrototypeFinally(
ret,
() => signal.removeEventListener('abort', oncancel)) : ret;
}

module.exports = {
Expand Down
2 changes: 1 addition & 1 deletion src/cares_wrap.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1493,7 +1493,7 @@ class QueryAaaaWrap: public QueryWrap {
class QueryCaaWrap: public QueryWrap {
public:
QueryCaaWrap(ChannelWrap* channel, Local<Object> req_wrap_obj)
: QueryWrap(channel, req_wrap_obj, "resolve6") {
: QueryWrap(channel, req_wrap_obj, "resolveCaa") {
}

int Send(const char* name) override {
Expand Down
36 changes: 36 additions & 0 deletions test/parallel/test-events-static-geteventlisteners.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
'use strict';

const common = require('../common');

const {
deepStrictEqual,
} = require('assert');

const { getEventListeners, EventEmitter } = require('events');

// Test getEventListeners on EventEmitter
{
const fn1 = common.mustNotCall();
const fn2 = common.mustNotCall();
const emitter = new EventEmitter();
emitter.on('foo', fn1);
emitter.on('foo', fn2);
emitter.on('baz', fn1);
emitter.on('baz', fn1);
deepStrictEqual(getEventListeners(emitter, 'foo'), [fn1, fn2]);
deepStrictEqual(getEventListeners(emitter, 'bar'), []);
deepStrictEqual(getEventListeners(emitter, 'baz'), [fn1, fn1]);
}
// Test getEventListeners on EventTarget
{
const fn1 = common.mustNotCall();
const fn2 = common.mustNotCall();
const target = new EventTarget();
target.addEventListener('foo', fn1);
target.addEventListener('foo', fn2);
target.addEventListener('baz', fn1);
target.addEventListener('baz', fn1);
deepStrictEqual(getEventListeners(target, 'foo'), [fn1, fn2]);
deepStrictEqual(getEventListeners(target, 'bar'), []);
deepStrictEqual(getEventListeners(target, 'baz'), [fn1]);
}
Loading