All files / lib/internal event_target.js

100% Statements 1106/1106
98.27% Branches 285/290
100% Functions 73/73
100% Lines 1106/1106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 110737x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 6x 6x 37x 37x 68206x 68206x 68206x 37x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 34084x 34084x 34081x 34081x 34081x 34081x 34081x 34081x 34081x 34084x 633x 633x 34072x 34072x 34072x 34072x 34072x 34072x 34072x 34072x 34072x 34072x 34084x 3x 3x 4x 4x 4x 4x 4x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 9x 9x 7x 9x 3x 3x 18x 18x 16x 18x 3x 3x 3x 3x 3x 25x 25x 23x 25x 3x 3x 3x 3x 3x 6x 6x 4x 6x 3x 3x 3x 3x 3x 6x 6x 4x 6x 3x 3x 3x 3x 3x 34010x 34010x 34008x 34010x 3x 3x 3x 3x 3x 20x 20x 18x 20x 3x 3x 3x 3x 3x 33964x 33964x 33964x 33964x 3x 3x 3x 3x 3x 6x 6x 4x 6x 3x 3x 3x 3x 3x 3x 3x 3x 3x 14x 14x 14x 14x 3x 3x 3x 3x 3x 6x 6x 4x 6x 3x 3x 3x 3x 3x 19x 19x 17x 19x 3x 3x 3x 3x 3x 4x 4x 2x 4x 3x 3x 3x 3x 3x 23x 23x 23x 23x 3x 3x 3x 3x 3x 28x 28x 26x 28x 3x 3x 3x 3x 3x 8x 8x 8x 8x 8x 8x 3x 3x 14x 14x 12x 14x 3x 3x 3x 3x 3x 3x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 22x 22x 22x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 42x 42x 41x 42x 42x 37x 37x 37x 37x 37x 22x 22x 21x 22x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 2x 2x 2x 2x 2x 37x 37x 37x 37x 37x 37x 37x 37x 85x 85x 85x 85x 85x 85x 85x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 114557x 30x 30x 30x 30x 30x 114557x 114512x 114512x 114527x 15x 13x 13x 15x 15x 15x 114557x 37x 37x 76189x 76189x 37x 40537x 40537x 37x 76203x 76203x 37x 152316x 152316x 37x 252081x 252081x 37x 76197x 76197x 37x 155086x 155086x 114557x 114557x 155086x 37x 37x 20806x 20806x 20806x 37x 37x 40529x 40529x 40529x 40529x 40529x 40529x 40529x 40529x 37x 37x 13113x 13113x 13113x 13113x 13113x 13113x 37x 37x 37x 37x 37x 37x 37x 37x 851x 851x 37x 37x 114559x 114559x 114559x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 114559x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 114589x 114589x 114588x 114588x 114586x 114586x 114586x 114586x 114586x 114586x 114586x 114586x 114586x 114586x 114586x 114586x 114588x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 114567x 114567x 114588x 26x 2x 2x 24x 24x 24x 20x 24x 24x 114565x 114565x 114565x 114584x 104350x 104350x 104350x 104350x 104350x 104350x 104350x 104350x 104350x 104350x 104350x 104350x 104350x 104350x 104350x 10215x 10215x 10215x 10215x 10215x 114589x 356x 356x 356x 10215x 80828x 8x 8x 10207x 10207x 10207x 10207x 10207x 114589x 37x 37x 37x 37x 37x 37x 37x 37x 37x 20426x 20426x 20425x 20425x 20415x 20415x 20426x 20426x 20426x 20426x 20426x 20357x 20357x 20369x 20442x 20357x 20357x 20357x 20357x 20357x 20357x 20357x 85x 85x 20426x 37x 37x 37x 37x 37x 33942x 33942x 33932x 33932x 33941x 33927x 33927x 33941x 33926x 33926x 33926x 33926x 33942x 37x 37x 109731x 431x 80x 80x 80x 80x 431x 109731x 109731x 33926x 33926x 33926x 109731x 109731x 109731x 33596x 33596x 33596x 33596x 76135x 76135x 76135x 76135x 109662x 109731x 76197x 76197x 76197x 76197x 8x 8x 8x 8x 8x 76192x 20169x 20169x 20169x 20169x 20169x 76189x 76189x 76189x 76197x 75758x 76193x 431x 431x 76197x 76197x 76197x 76197x 76188x 76188x 429x 429x 76188x 76197x 76197x 76197x 33x 33x 76161x 76161x 76161x 76107x 76107x 109230x 109731x 37x 37x 2x 2x 37x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 34708x 34708x 34708x 37x 37x 37x 37x 37x 37x 13x 13x 13x 37x 37x 37x 37x 37x 2x 2x 1x 2x 37x 37x 37x 37x 37x 2x 2x 1x 2x 37x 37x 37x 37x 37x 8x 8x 7x 8x 37x 37x 37x 37x 37x 37x 28x 28x 27x 28x 28x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 104x 104x 103x 103x 104x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 20010x 20010x 20009x 20009x 20010x 37x 37x 37x 37x 37x 37x 37x 73193x 73193x 73192x 73192x 73193x 37x 37x 37x 37x 37x 37x 37x 4x 4x 3x 3x 4x 37x 37x 37x 37x 37x 37x 37x 4x 4x 3x 3x 3x 3x 4x 37x 37x 37x 37x 37x 37x 37x 40063x 40063x 40062x 40062x 40062x 40063x 37x 37x 37x 37x 37x 37x 3x 3x 2x 1x 1x 1x 1x 2x 2x 3x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 135011x 135011x 135011x 134973x 134973x 38x 38x 104x 18x 77x 9x 9x 9x 9x 9x 135011x 37x 114586x 114586x 114586x 114582x 114582x 114586x 114581x 114581x 114581x 114581x 114581x 114581x 114581x 114581x 114581x 114581x 114581x 114586x 37x 37x 37x 37x 37x 37x 169016x 169016x 169016x 37x 133421x 133421x 133421x 37x 29943x 29943x 29943x 15x 3x 3x 3x 15x 15x 29943x 37x 36x 36x 36x 37x 150x 150x 150x 150x 116x 1x 1x 115x 116x 150x 150x 150x 37x 4440x 4440x 4440x 4440x 6x 6x 6x 4440x 4440x 4440x 4440x 4440x 4440x 157x 157x 157x 6x 6x 6x 6x 6x 6x 6x 2x 2x 2x 2x 156x 150x 150x 150x 156x 157x 4440x 4440x 4440x 4440x 4440x 4440x 4440x 4440x 4440x 4440x 4440x 4440x 4440x 37x 37x 6241x 6241x 1062x 1062x 1062x 1062x 6241x 6241x 6241x 6241x 6241x 112338x 112338x 112338x 112338x 6241x 6241x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x  
'use strict';
 
const {
  ArrayFrom,
  Boolean,
  Error,
  FunctionPrototypeCall,
  NumberIsInteger,
  ObjectAssign,
  ObjectDefineProperties,
  ObjectDefineProperty,
  ObjectGetOwnPropertyDescriptor,
  ObjectGetOwnPropertyDescriptors,
  ObjectSetPrototypeOf,
  ObjectValues,
  ReflectApply,
  SafeArrayIterator,
  SafeFinalizationRegistry,
  SafeMap,
  SafeWeakMap,
  SafeWeakRef,
  SafeWeakSet,
  String,
  Symbol,
  SymbolFor,
  SymbolToStringTag,
} = primordials;
 
const {
  codes: {
    ERR_INVALID_ARG_TYPE,
    ERR_EVENT_RECURSION,
    ERR_MISSING_ARGS,
    ERR_INVALID_THIS,
  }
} = require('internal/errors');
const { validateObject, validateString, validateInternalField } = require('internal/validators');
 
const {
  customInspectSymbol,
  kEmptyObject,
  kEnumerableProperty,
} = require('internal/util');
const { inspect } = require('util');
 
const kIsEventTarget = SymbolFor('nodejs.event_target');
const kIsNodeEventTarget = Symbol('kIsNodeEventTarget');
 
const EventEmitter = require('events');
const {
  kMaxEventTargetListeners,
  kMaxEventTargetListenersWarned,
} = EventEmitter;
 
const kEvents = Symbol('kEvents');
const kIsBeingDispatched = Symbol('kIsBeingDispatched');
const kStop = Symbol('kStop');
const kTarget = Symbol('kTarget');
const kHandlers = Symbol('khandlers');
const kWeakHandler = Symbol('kWeak');
 
const kHybridDispatch = SymbolFor('nodejs.internal.kHybridDispatch');
const kCreateEvent = Symbol('kCreateEvent');
const kNewListener = Symbol('kNewListener');
const kRemoveListener = Symbol('kRemoveListener');
const kIsNodeStyleListener = Symbol('kIsNodeStyleListener');
const kTrustEvent = Symbol('kTrustEvent');
 
const { now } = require('internal/perf/utils');
 
const kType = Symbol('type');
const kDetail = Symbol('detail');
 
const isTrustedSet = new SafeWeakSet();
const isTrusted = ObjectGetOwnPropertyDescriptor({
  get isTrusted() {
    return isTrustedSet.has(this);
  }
}, 'isTrusted').get;
 
function isEvent(value) {
  return typeof value?.[kType] === 'string';
}
 
class Event {
  #cancelable = false;
  #bubbles = false;
  #composed = false;
  #defaultPrevented = false;
  #timestamp = now();
  #propagationStopped = false;
 
  /**
   * @param {string} type
   * @param {{
   *   bubbles?: boolean,
   *   cancelable?: boolean,
   *   composed?: boolean,
   * }} [options]
   */
  constructor(type, options = kEmptyObject) {
    if (arguments.length === 0)
      throw new ERR_MISSING_ARGS('type');
    validateObject(options, 'options');
    const { bubbles, cancelable, composed } = options;
    this.#cancelable = !!cancelable;
    this.#bubbles = !!bubbles;
    this.#composed = !!composed;
 
    this[kType] = `${type}`;
    if (options?.[kTrustEvent]) {
      isTrustedSet.add(this);
    }
 
    // isTrusted is special (LegacyUnforgeable)
    ObjectDefineProperty(this, 'isTrusted', {
      __proto__: null,
      get: isTrusted,
      enumerable: true,
      configurable: false
    });
    this[kTarget] = null;
    this[kIsBeingDispatched] = false;
  }
 
  [customInspectSymbol](depth, options) {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    const name = this.constructor.name;
    if (depth < 0)
      return name;
 
    const opts = ObjectAssign({}, options, {
      depth: NumberIsInteger(options.depth) ? options.depth - 1 : options.depth
    });
 
    return `${name} ${inspect({
      type: this[kType],
      defaultPrevented: this.#defaultPrevented,
      cancelable: this.#cancelable,
      timeStamp: this.#timestamp,
    }, opts)}`;
  }
 
  stopImmediatePropagation() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    this[kStop] = true;
  }
 
  preventDefault() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    this.#defaultPrevented = true;
  }
 
  /**
   * @type {EventTarget}
   */
  get target() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this[kTarget];
  }
 
  /**
   * @type {EventTarget}
   */
  get currentTarget() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this[kTarget];
  }
 
  /**
   * @type {EventTarget}
   */
  get srcElement() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this[kTarget];
  }
 
  /**
   * @type {string}
   */
  get type() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this[kType];
  }
 
  /**
   * @type {boolean}
   */
  get cancelable() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this.#cancelable;
  }
 
  /**
   * @type {boolean}
   */
  get defaultPrevented() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this.#cancelable && this.#defaultPrevented;
  }
 
  /**
   * @type {number}
   */
  get timeStamp() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this.#timestamp;
  }
 
 
  // The following are non-op and unused properties/methods from Web API Event.
  // These are not supported in Node.js and are provided purely for
  // API completeness.
  /**
   * @returns {EventTarget[]}
   */
  composedPath() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this[kIsBeingDispatched] ? [this[kTarget]] : [];
  }
 
  /**
   * @type {boolean}
   */
  get returnValue() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return !this.defaultPrevented;
  }
 
  /**
   * @type {boolean}
   */
  get bubbles() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this.#bubbles;
  }
 
  /**
   * @type {boolean}
   */
  get composed() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this.#composed;
  }
 
  /**
   * @type {number}
   */
  get eventPhase() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this[kIsBeingDispatched] ? Event.AT_TARGET : Event.NONE;
  }
 
  /**
   * @type {boolean}
   */
  get cancelBubble() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    return this.#propagationStopped;
  }
 
  /**
   * @type {boolean}
   */
  set cancelBubble(value) {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    if (value) {
      this.stopPropagation();
    }
  }
 
  stopPropagation() {
    if (!isEvent(this))
      throw new ERR_INVALID_THIS('Event');
    this.#propagationStopped = true;
  }
 
  static NONE = 0;
  static CAPTURING_PHASE = 1;
  static AT_TARGET = 2;
  static BUBBLING_PHASE = 3;
}
 
ObjectDefineProperties(
  Event.prototype, {
    [SymbolToStringTag]: {
      __proto__: null,
      writable: false,
      enumerable: false,
      configurable: true,
      value: 'Event',
    },
    stopImmediatePropagation: kEnumerableProperty,
    preventDefault: kEnumerableProperty,
    target: kEnumerableProperty,
    currentTarget: kEnumerableProperty,
    srcElement: kEnumerableProperty,
    type: kEnumerableProperty,
    cancelable: kEnumerableProperty,
    defaultPrevented: kEnumerableProperty,
    timeStamp: kEnumerableProperty,
    composedPath: kEnumerableProperty,
    returnValue: kEnumerableProperty,
    bubbles: kEnumerableProperty,
    composed: kEnumerableProperty,
    eventPhase: kEnumerableProperty,
    cancelBubble: kEnumerableProperty,
    stopPropagation: kEnumerableProperty,
  });
 
function isCustomEvent(value) {
  return isEvent(value) && (value?.[kDetail] !== undefined);
}
 
class CustomEvent extends Event {
  /**
   * @constructor
   * @param {string} type
   * @param {{
   *   bubbles?: boolean,
   *   cancelable?: boolean,
   *   composed?: boolean,
   *   detail?: any,
   * }} [options]
   */
  constructor(type, options = kEmptyObject) {
    if (arguments.length === 0)
      throw new ERR_MISSING_ARGS('type');
    super(type, options);
    this[kDetail] = options?.detail ?? null;
  }
 
  /**
   * @type {any}
   */
  get detail() {
    if (!isCustomEvent(this))
      throw new ERR_INVALID_THIS('CustomEvent');
    return this[kDetail];
  }
}
 
ObjectDefineProperties(CustomEvent.prototype, {
  [SymbolToStringTag]: {
    __proto__: null,
    writable: false,
    enumerable: false,
    configurable: true,
    value: 'CustomEvent',
  },
  detail: kEnumerableProperty,
});
 
class NodeCustomEvent extends Event {
  constructor(type, options) {
    super(type, options);
    if (options?.detail) {
      this.detail = options.detail;
    }
  }
}
 
// Weak listener cleanup
// This has to be lazy for snapshots to work
let weakListenersState = null;
// The resource needs to retain the callback so that it doesn't
// get garbage collected now that it's weak.
let objectToWeakListenerMap = null;
function weakListeners() {
  weakListenersState ??= new SafeFinalizationRegistry(
    (listener) => listener.remove()
  );
  objectToWeakListenerMap ??= new SafeWeakMap();
  return { registry: weakListenersState, map: objectToWeakListenerMap };
}
 
const kFlagOnce = 1 << 0;
const kFlagCapture = 1 << 1;
const kFlagPassive = 1 << 2;
const kFlagNodeStyle = 1 << 3;
const kFlagWeak = 1 << 4;
const kFlagRemoved = 1 << 5;
 
// The listeners for an EventTarget are maintained as a linked list.
// Unfortunately, the way EventTarget is defined, listeners are accounted
// using the tuple [handler,capture], and even if we don't actually make
// use of capture or bubbling, in order to be spec compliant we have to
// take on the additional complexity of supporting it. Fortunately, using
// the linked list makes dispatching faster, even if adding/removing is
// slower.
class Listener {
  constructor(previous, listener, once, capture, passive,
              isNodeStyleListener, weak) {
    this.next = undefined;
    if (previous !== undefined)
      previous.next = this;
    this.previous = previous;
    this.listener = listener;
 
    let flags = 0b0;
    if (once)
      flags |= kFlagOnce;
    if (capture)
      flags |= kFlagCapture;
    if (passive)
      flags |= kFlagPassive;
    if (isNodeStyleListener)
      flags |= kFlagNodeStyle;
    if (weak)
      flags |= kFlagWeak;
    this.flags = flags;
 
    this.removed = false;
 
    if (this.weak) {
      this.callback = new SafeWeakRef(listener);
      weakListeners().registry.register(listener, this, this);
      // Make the retainer retain the listener in a WeakMap
      weakListeners().map.set(weak, listener);
      this.listener = this.callback;
    } else if (typeof listener === 'function') {
      this.callback = listener;
      this.listener = listener;
    } else {
      this.callback = async (...args) => {
        if (listener.handleEvent)
          await ReflectApply(listener.handleEvent, listener, args);
      };
      this.listener = listener;
    }
  }
 
  get once() {
    return Boolean(this.flags & kFlagOnce);
  }
  get capture() {
    return Boolean(this.flags & kFlagCapture);
  }
  get passive() {
    return Boolean(this.flags & kFlagPassive);
  }
  get isNodeStyleListener() {
    return Boolean(this.flags & kFlagNodeStyle);
  }
  get weak() {
    return Boolean(this.flags & kFlagWeak);
  }
  get removed() {
    return Boolean(this.flags & kFlagRemoved);
  }
  set removed(value) {
    if (value)
      this.flags |= kFlagRemoved;
    else
      this.flags &= ~kFlagRemoved;
  }
 
  same(listener, capture) {
    const myListener = this.weak ? this.listener.deref() : this.listener;
    return myListener === listener && this.capture === capture;
  }
 
  remove() {
    if (this.previous !== undefined)
      this.previous.next = this.next;
    if (this.next !== undefined)
      this.next.previous = this.previous;
    this.removed = true;
    if (this.weak)
      weakListeners().registry.unregister(this);
  }
}
 
function initEventTarget(self) {
  self[kEvents] = new SafeMap();
  self[kMaxEventTargetListeners] = EventEmitter.defaultMaxListeners;
  self[kMaxEventTargetListenersWarned] = false;
  self[kHandlers] = new SafeMap();
}
 
class EventTarget {
  // Used in checking whether an object is an EventTarget. This is a well-known
  // symbol as EventTarget may be used cross-realm.
  // Ref: https://github.com/nodejs/node/pull/33661
  static [kIsEventTarget] = true;
 
  constructor() {
    initEventTarget(this);
  }
 
  [kNewListener](size, type, listener, once, capture, passive, weak) {
    if (this[kMaxEventTargetListeners] > 0 &&
        size > this[kMaxEventTargetListeners] &&
        !this[kMaxEventTargetListenersWarned]) {
      this[kMaxEventTargetListenersWarned] = true;
      // No error code for this since it is a Warning
      // eslint-disable-next-line no-restricted-syntax
      const w = new Error('Possible EventTarget memory leak detected. ' +
                          `${size} ${type} listeners ` +
                          `added to ${inspect(this, { depth: -1 })}. Use ` +
                          'events.setMaxListeners() to increase limit');
      w.name = 'MaxListenersExceededWarning';
      w.target = this;
      w.type = type;
      w.count = size;
      process.emitWarning(w);
    }
  }
  [kRemoveListener](size, type, listener, capture) {}
 
  /**
   * @callback EventTargetCallback
   * @param {Event} event
   */
 
  /**
   * @typedef {{ handleEvent: EventTargetCallback }} EventListener
   */
 
  /**
   * @param {string} type
   * @param {EventTargetCallback|EventListener} listener
   * @param {{
   *   capture?: boolean,
   *   once?: boolean,
   *   passive?: boolean,
   *   signal?: AbortSignal
   * }} [options]
   */
  addEventListener(type, listener, options = kEmptyObject) {
    if (!isEventTarget(this))
      throw new ERR_INVALID_THIS('EventTarget');
    if (arguments.length < 2)
      throw new ERR_MISSING_ARGS('type', 'listener');
 
    // We validateOptions before the validateListener check because the spec
    // requires us to hit getters.
    const {
      once,
      capture,
      passive,
      signal,
      isNodeStyleListener,
      weak,
    } = validateEventListenerOptions(options);
 
    if (!validateEventListener(listener)) {
      // The DOM silently allows passing undefined as a second argument
      // No error code for this since it is a Warning
      // eslint-disable-next-line no-restricted-syntax
      const w = new Error(`addEventListener called with ${listener}` +
                          ' which has no effect.');
      w.name = 'AddEventListenerArgumentTypeWarning';
      w.target = this;
      w.type = type;
      process.emitWarning(w);
      return;
    }
    type = String(type);
 
    if (signal) {
      if (signal.aborted) {
        return;
      }
      // TODO(benjamingr) make this weak somehow? ideally the signal would
      // not prevent the event target from GC.
      signal.addEventListener('abort', () => {
        this.removeEventListener(type, listener, options);
      }, { once: true, [kWeakHandler]: this });
    }
 
    let root = this[kEvents].get(type);
 
    if (root === undefined) {
      root = { size: 1, next: undefined };
      // This is the first handler in our linked list.
      new Listener(root, listener, once, capture, passive,
                   isNodeStyleListener, weak);
      this[kNewListener](
        root.size,
        type,
        listener,
        once,
        capture,
        passive,
        weak);
      this[kEvents].set(type, root);
      return;
    }
 
    let handler = root.next;
    let previous = root;
 
    // We have to walk the linked list to see if we have a match
    while (handler !== undefined && !handler.same(listener, capture)) {
      previous = handler;
      handler = handler.next;
    }
 
    if (handler !== undefined) { // Duplicate! Ignore
      return;
    }
 
    new Listener(previous, listener, once, capture, passive,
                 isNodeStyleListener, weak);
    root.size++;
    this[kNewListener](root.size, type, listener, once, capture, passive, weak);
  }
 
  /**
   * @param {string} type
   * @param {EventTargetCallback|EventListener} listener
   * @param {{
   *   capture?: boolean,
   * }} [options]
   */
  removeEventListener(type, listener, options = kEmptyObject) {
    if (!isEventTarget(this))
      throw new ERR_INVALID_THIS('EventTarget');
    if (!validateEventListener(listener))
      return;
 
    type = String(type);
    const capture = options?.capture === true;
 
    const root = this[kEvents].get(type);
    if (root === undefined || root.next === undefined)
      return;
 
    let handler = root.next;
    while (handler !== undefined) {
      if (handler.same(listener, capture)) {
        handler.remove();
        root.size--;
        if (root.size === 0)
          this[kEvents].delete(type);
        this[kRemoveListener](root.size, type, listener, capture);
        break;
      }
      handler = handler.next;
    }
  }
 
  /**
   * @param {Event} event
   */
  dispatchEvent(event) {
    if (!isEventTarget(this))
      throw new ERR_INVALID_THIS('EventTarget');
 
    if (!(event instanceof Event))
      throw new ERR_INVALID_ARG_TYPE('event', 'Event', event);
 
    if (event[kIsBeingDispatched])
      throw new ERR_EVENT_RECURSION(event.type);
 
    this[kHybridDispatch](event, event.type, event);
 
    return event.defaultPrevented !== true;
  }
 
  [kHybridDispatch](nodeValue, type, event) {
    const createEvent = () => {
      if (event === undefined) {
        event = this[kCreateEvent](nodeValue, type);
        event[kTarget] = this;
        event[kIsBeingDispatched] = true;
      }
      return event;
    };
    if (event !== undefined) {
      event[kTarget] = this;
      event[kIsBeingDispatched] = true;
    }
 
    const root = this[kEvents].get(type);
    if (root === undefined || root.next === undefined) {
      if (event !== undefined)
        event[kIsBeingDispatched] = false;
      return true;
    }
 
    let handler = root.next;
    let next;
 
    while (handler !== undefined &&
           (handler.passive || event?.[kStop] !== true)) {
      // Cache the next item in case this iteration removes the current one
      next = handler.next;
 
      if (handler.removed) {
        // Deal with the case an event is removed while event handlers are
        // Being processed (removeEventListener called from a listener)
        handler = next;
        continue;
      }
      if (handler.once) {
        handler.remove();
        root.size--;
        const { listener, capture } = handler;
        this[kRemoveListener](root.size, type, listener, capture);
      }
 
      try {
        let arg;
        if (handler.isNodeStyleListener) {
          arg = nodeValue;
        } else {
          arg = createEvent();
        }
        const callback = handler.weak ?
          handler.callback.deref() : handler.callback;
        let result;
        if (callback) {
          result = FunctionPrototypeCall(callback, this, arg);
          if (!handler.isNodeStyleListener) {
            arg[kIsBeingDispatched] = false;
          }
        }
        if (result !== undefined && result !== null)
          addCatch(result);
      } catch (err) {
        emitUncaughtException(err);
      }
 
      handler = next;
    }
 
    if (event !== undefined)
      event[kIsBeingDispatched] = false;
  }
 
  [kCreateEvent](nodeValue, type) {
    return new NodeCustomEvent(type, { detail: nodeValue });
  }
  [customInspectSymbol](depth, options) {
    if (!isEventTarget(this))
      throw new ERR_INVALID_THIS('EventTarget');
    const name = this.constructor.name;
    if (depth < 0)
      return name;
 
    const opts = ObjectAssign({}, options, {
      depth: NumberIsInteger(options.depth) ? options.depth - 1 : options.depth
    });
 
    return `${name} ${inspect({}, opts)}`;
  }
}
 
ObjectDefineProperties(EventTarget.prototype, {
  addEventListener: kEnumerableProperty,
  removeEventListener: kEnumerableProperty,
  dispatchEvent: kEnumerableProperty,
  [SymbolToStringTag]: {
    __proto__: null,
    writable: false,
    enumerable: false,
    configurable: true,
    value: 'EventTarget',
  }
});
 
function initNodeEventTarget(self) {
  initEventTarget(self);
}
 
class NodeEventTarget extends EventTarget {
  static [kIsNodeEventTarget] = true;
  static defaultMaxListeners = 10;
 
  constructor() {
    super();
    initNodeEventTarget(this);
  }
 
  /**
   * @param {number} n
   */
  setMaxListeners(n) {
    if (!isNodeEventTarget(this))
      throw new ERR_INVALID_THIS('NodeEventTarget');
    EventEmitter.setMaxListeners(n, this);
  }
 
  /**
   * @returns {number}
   */
  getMaxListeners() {
    if (!isNodeEventTarget(this))
      throw new ERR_INVALID_THIS('NodeEventTarget');
    return this[kMaxEventTargetListeners];
  }
 
  /**
   * @returns {string[]}
   */
  eventNames() {
    if (!isNodeEventTarget(this))
      throw new ERR_INVALID_THIS('NodeEventTarget');
    return ArrayFrom(this[kEvents].keys());
  }
 
  /**
   * @param {string} [type]
   * @returns {number}
   */
  listenerCount(type) {
    if (!isNodeEventTarget(this))
      throw new ERR_INVALID_THIS('NodeEventTarget');
    const root = this[kEvents].get(String(type));
    return root !== undefined ? root.size : 0;
  }
 
  /**
   * @param {string} type
   * @param {EventTargetCallback|EventListener} listener
   * @param {{
   *   capture?: boolean,
   * }} [options]
   * @returns {NodeEventTarget}
   */
  off(type, listener, options) {
    if (!isNodeEventTarget(this))
      throw new ERR_INVALID_THIS('NodeEventTarget');
    this.removeEventListener(type, listener, options);
    return this;
  }
 
  /**
   * @param {string} type
   * @param {EventTargetCallback|EventListener} listener
   * @param {{
   *   capture?: boolean,
   * }} [options]
   * @returns {NodeEventTarget}
   */
  removeListener(type, listener, options) {
    if (!isNodeEventTarget(this))
      throw new ERR_INVALID_THIS('NodeEventTarget');
    this.removeEventListener(type, listener, options);
    return this;
  }
 
  /**
   * @param {string} type
   * @param {EventTargetCallback|EventListener} listener
   * @returns {NodeEventTarget}
   */
  on(type, listener) {
    if (!isNodeEventTarget(this))
      throw new ERR_INVALID_THIS('NodeEventTarget');
    this.addEventListener(type, listener, { [kIsNodeStyleListener]: true });
    return this;
  }
 
  /**
   * @param {string} type
   * @param {EventTargetCallback|EventListener} listener
   * @returns {NodeEventTarget}
   */
  addListener(type, listener) {
    if (!isNodeEventTarget(this))
      throw new ERR_INVALID_THIS('NodeEventTarget');
    this.addEventListener(type, listener, { [kIsNodeStyleListener]: true });
    return this;
  }
 
  /**
   * @param {string} type
   * @param {any} arg
   * @returns {boolean}
   */
  emit(type, arg) {
    if (!isNodeEventTarget(this))
      throw new ERR_INVALID_THIS('NodeEventTarget');
    validateString(type, 'type');
    const hadListeners = this.listenerCount(type) > 0;
    this[kHybridDispatch](arg, type);
    return hadListeners;
  }
 
  /**
   * @param {string} type
   * @param {EventTargetCallback|EventListener} listener
   * @returns {NodeEventTarget}
   */
  once(type, listener) {
    if (!isNodeEventTarget(this))
      throw new ERR_INVALID_THIS('NodeEventTarget');
    this.addEventListener(type, listener,
                          { once: true, [kIsNodeStyleListener]: true });
    return this;
  }
 
  /**
   * @param {string} type
   * @returns {NodeEventTarget}
   */
  removeAllListeners(type) {
    if (!isNodeEventTarget(this))
      throw new ERR_INVALID_THIS('NodeEventTarget');
    if (type !== undefined) {
      this[kEvents].delete(String(type));
    } else {
      this[kEvents].clear();
    }
 
    return this;
  }
}
 
ObjectDefineProperties(NodeEventTarget.prototype, {
  setMaxListeners: kEnumerableProperty,
  getMaxListeners: kEnumerableProperty,
  eventNames: kEnumerableProperty,
  listenerCount: kEnumerableProperty,
  off: kEnumerableProperty,
  removeListener: kEnumerableProperty,
  on: kEnumerableProperty,
  addListener: kEnumerableProperty,
  once: kEnumerableProperty,
  emit: kEnumerableProperty,
  removeAllListeners: kEnumerableProperty,
});
 
// EventTarget API
 
function validateEventListener(listener) {
  if (typeof listener === 'function' ||
      typeof listener?.handleEvent === 'function') {
    return true;
  }
 
  if (listener == null)
    return false;
 
  if (typeof listener === 'object') {
    // Require `handleEvent` lazily.
    return true;
  }
 
  throw new ERR_INVALID_ARG_TYPE('listener', 'EventListener', listener);
}
 
function validateEventListenerOptions(options) {
  if (typeof options === 'boolean')
    return { capture: options };
 
  if (options === null)
    return kEmptyObject;
  validateObject(options, 'options', {
    allowArray: true, allowFunction: true,
  });
  return {
    once: Boolean(options.once),
    capture: Boolean(options.capture),
    passive: Boolean(options.passive),
    signal: options.signal,
    weak: options[kWeakHandler],
    isNodeStyleListener: Boolean(options[kIsNodeStyleListener])
  };
}
 
// Test whether the argument is an event object. This is far from a fool-proof
// test, for example this input will result in a false positive:
// > isEventTarget({ constructor: EventTarget })
// It stands in its current implementation as a compromise.
// Ref: https://github.com/nodejs/node/pull/33661
function isEventTarget(obj) {
  return obj?.constructor?.[kIsEventTarget];
}
 
function isNodeEventTarget(obj) {
  return obj?.constructor?.[kIsNodeEventTarget];
}
 
function addCatch(promise) {
  const then = promise.then;
  if (typeof then === 'function') {
    FunctionPrototypeCall(then, promise, undefined, function(err) {
      // The callback is called with nextTick to avoid a follow-up
      // rejection from this promise.
      emitUncaughtException(err);
    });
  }
}
 
function emitUncaughtException(err) {
  process.nextTick(() => { throw err; });
}
 
function makeEventHandler(handler) {
  // Event handlers are dispatched in the order they were first set
  // See https://github.com/nodejs/node/pull/35949#issuecomment-722496598
  function eventHandler(...args) {
    if (typeof eventHandler.handler !== 'function') {
      return;
    }
    return ReflectApply(eventHandler.handler, this, args);
  }
  eventHandler.handler = handler;
  return eventHandler;
}
 
function defineEventHandler(emitter, name) {
  // 8.1.5.1 Event handlers - basically `on[eventName]` attributes
  const propName = `on${name}`;
  function get() {
    validateInternalField(this, kHandlers, 'EventTarget');
    return this[kHandlers]?.get(name)?.handler ?? null;
  }
  ObjectDefineProperty(get, 'name', {
    __proto__: null,
    value: `get ${propName}`,
  });
 
  function set(value) {
    validateInternalField(this, kHandlers, 'EventTarget');
    let wrappedHandler = this[kHandlers]?.get(name);
    if (wrappedHandler) {
      if (typeof wrappedHandler.handler === 'function') {
        this[kEvents].get(name).size--;
        const size = this[kEvents].get(name).size;
        this[kRemoveListener](size, name, wrappedHandler.handler, false);
      }
      wrappedHandler.handler = value;
      if (typeof wrappedHandler.handler === 'function') {
        this[kEvents].get(name).size++;
        const size = this[kEvents].get(name).size;
        this[kNewListener](size, name, value, false, false, false, false);
      }
    } else {
      wrappedHandler = makeEventHandler(value);
      this.addEventListener(name, wrappedHandler);
    }
    this[kHandlers].set(name, wrappedHandler);
  }
  ObjectDefineProperty(set, 'name', {
    __proto__: null,
    value: `set ${propName}`,
  });
 
  ObjectDefineProperty(emitter, propName, {
    __proto__: null,
    get,
    set,
    configurable: true,
    enumerable: true
  });
}
 
const EventEmitterMixin = (Superclass) => {
  class MixedEventEmitter extends Superclass {
    constructor(...args) {
      args = new SafeArrayIterator(args);
      super(...args);
      FunctionPrototypeCall(EventEmitter, this);
    }
  }
  const protoProps = ObjectGetOwnPropertyDescriptors(EventEmitter.prototype);
  delete protoProps.constructor;
  const propertiesValues = ObjectValues(protoProps);
  for (let i = 0; i < propertiesValues.length; i++) {
    // We want to use null-prototype objects to not rely on globally mutable
    // %Object.prototype%.
    ObjectSetPrototypeOf(propertiesValues[i], null);
  }
  ObjectDefineProperties(MixedEventEmitter.prototype, protoProps);
  return MixedEventEmitter;
};
 
module.exports = {
  Event,
  CustomEvent,
  EventEmitterMixin,
  EventTarget,
  NodeEventTarget,
  defineEventHandler,
  initEventTarget,
  initNodeEventTarget,
  kCreateEvent,
  kNewListener,
  kTrustEvent,
  kRemoveListener,
  kEvents,
  kWeakHandler,
  isEventTarget,
};