Fix EventEmitter prototype-key event types (#58229)

Summary:
The shared EventEmitter uses an ordinary object registry, so event types such as `constructor` and `__proto__` resolve inherited values and throw during registration. Initialize and reset the internal registry without a prototype, and cover registration, emission, counting, and full reset for both keys.

Fixes https://github.com/react/react-native/issues/58228.

## Changelog:

[GENERAL] [FIXED] - Support EventEmitter event names that overlap Object prototype properties.

Pull Request resolved: https://github.com/react/react-native/pull/58229

Test Plan:
- Exact upstream regression: 20 passed / 1 failed at `registrations.add`.
- Fixed Fantom suite: 21/21 passed.
- Fresh `yarn flow-check`: 0 errors.
- Targeted no-ignore ESLint, Prettier, and `git diff --check` passed.

No UI change; screenshots are not applicable.

Reviewed By: cortinico

Differential Revision: D118267117

Pulled By: javache

fbshipit-source-id: 12c3aab577ec13dabe475409ae6e21f5e6853135
This commit is contained in:
Oskar Eichler authored and meta-codesync[bot] committed 2026-09-01 08:57:59 -07:00
1 parent 621ced78e9
commit 790289c1d6
2 files changed
+23 -2

No files matched your search

@@ -84,7 +84,7 @@ export default class EventEmitter<
constructor() {
// $FlowFixMe[incompatible-type]
this.#registry = {};
this.#registry = Object.create(null);
}
/**
@@ -147,7 +147,7 @@ export default class EventEmitter<
): void {
if (eventType == null) {
// $FlowFixMe[incompatible-type]
this.#registry = {};
this.#registry = Object.create(null);
} else {
// $FlowFixMe[cannot-write]
delete this.#registry[eventType];
@@ -57,6 +57,27 @@ describe('listeners', () => {
expect(listenerB).toHaveBeenCalledTimes(1);
});
it('supports event types that match Object prototype keys', () => {
const emitter = new EventEmitter<Readonly<Record<string, []>>>();
const constructorListener = jest.fn();
const protoListener = jest.fn();
emitter.addListener('constructor', constructorListener);
emitter.addListener('__proto__', protoListener);
emitter.emit('constructor');
emitter.emit('__proto__');
expect(constructorListener).toHaveBeenCalledTimes(1);
expect(protoListener).toHaveBeenCalledTimes(1);
expect(emitter.listenerCount('constructor')).toBe(1);
expect(emitter.listenerCount('__proto__')).toBe(1);
emitter.removeAllListeners();
expect(emitter.listenerCount('constructor')).toBe(0);
expect(emitter.listenerCount('__proto__')).toBe(0);
});
it('invokes listeners in registration order', () => {
const emitter = new EventEmitter<{A: []}>();