All files / lib/internal/debugger inspect_repl.js

92.92% Statements 1130/1216
89.04% Branches 260/292
87.05% Functions 74/85
92.92% Lines 1130/1216

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 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 121738x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 8x 8x 8x 8x 8x 38x 38x 38x 38x 38x 7065x 7065x 7065x 7065x 7065x 7065x 7065x 38x 287x 287x 287x 287x 287x 287x 287x 287x 91x 91x 196x 287x 38x 38x 38x 343x 343x 343x 343x 343x 343x 343x 38x 84x 84x 80x 80x 80x 80x 80x 80x       80x 80x 80x 84x 38x           38x               38x 38x 38x 31x 31x 38x 38x 31x 31x 31x 22x 31x 31x 8x 31x 31x 1x     1x     1x 31x   31x 31x 38x 38x 38x 38x 27x 27x 38x 38x 27x 27x 21x 21x   21x   21x   21x 4x 2x 2x 2x 2x 2x 2x 21x 2x 1x 1x 1x 2x 2x 2x 1x 1x 1x 21x 21x 15x 2x 2x 13x 31x 31x 13x 13x 15x 2x 2x 13x 15x 15x 15x 21x   21x 21x 27x 6x 27x 27x 38x 38x 38x 38x 48x 48x 5x 5x 5x 48x 38x 38x 40x 40x 40x 40x 40x 9x 40x   40x 8x 8x 8x 8x 40x 23x 23x 1x 23x 1x 23x 1x 23x 23x 5x 5x 5x 23x 15x 23x 15x 14x 14x 1x 40x   40x 40x 38x 38x 40x 40x 40x 38x 38x 38x 38x 3x 3x 3x 8x 8x 8x 3x 3x 38x 38x                 38x 38x 30x 30x 30x 30x 870x 870x 30x 30x 38x 30x 30x 270x 270x 30x 30x 38x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 52x 52x 52x 52x 52x 52x 52x 35x 35x 35x 35x 83x 83x 35x 35x 194x 194x 194x 35x 35x 458x     458x 458x 35x 35x 453x 453x 35x 35x 3x 453x 453x 453x 3x 3x 3x 3x 185x 185x 185x 185x 3x 3x 35x 35x 1x 1x 35x 2x 35x 35x 35x 35x 35x     35x 35x         35x 35x         35x 35x           35x 35x 35x 35x 84x 84x 84x 84x 35x 35x 84x 84x 84x 84x 84x 84x 84x 84x 84x 330x 330x 330x 330x 330x 330x 330x 330x 330x 220x 220x 220x 28x 28x 330x 330x 330x 330x 84x 330x 9x 9x 330x 84x 84x 35x 35x 35x 85x 85x 84x 85x 35x 35x 35x 491x 491x 35x 35x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 35x 35x 76x 76x 35x 35x 35x 35x 2x 2x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 2x 2x 35x 35x 71x 71x 71x 71x 71x 491x 491x 491x 71x 71x 35x 35x 35x 141x 125x 125x 141x 25x 140x 100x 100x 125x 141x 35x 35x 41x 41x 1x     1x 1x 1x 40x 40x 39x 39x 39x 39x 39x 39x 39x 1x 1x 1x 1x 1x 41x 35x 35x 141x 141x 135x 135x 135x 141x 141x 141x 141x 141x 141x 141x 115x 115x 115x 115x 115x 140x 25x 25x 141x 1x 1x 141x 35x 35x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 35x 35x 72x 70x 70x 2x 2x 13x 2x 2x 2x 2x 2x 2x 13x 13x 13x 10x 10x 3x 2x 2x 72x 72x 35x 35x 1x 1x 35x 35x 35x 6x 1x 1x 5x     5x 6x 35x 35x 15x 15x 15x 12x 12x 15x 8x 3x 3x 3x 5x 15x 15x 12x 12x 15x 35x 35x 6x 1x 1x 1x 5x 5x 9x 9x 9x 9x 9x 5x 5x 5x 5x 5x 5x 6x 35x 35x 14x 12x 12x 9x 10x 3x 3x 3x 12x 14x 14x 14x         14x 14x 14x 5x 5x 5x 5x 5x 5x 5x 5x 9x 9x 9x 9x 12x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 12x   12x 8x 1142x 1142x 5x     5x 5x 8x 8x 8x 12x       12x       8x 10x 5x 5x 5x 5x 5x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 14x 35x 35x 3x 5x 5x 5x 5x 5x 3x 5x 3x 3x 2x 2x 2x 1x 1x 1x 1x 1x 1x 3x 35x 35x 47x 47x 47x 47x 47x 47x 47x 1x 1x 1x 1x 1x 47x 35x 35x 3x 3x 3x 3x 3x 3x 35x 35x 72x 72x 1x 1x 1x 1x 1x 71x 71x 71x 71x 71x 71x 72x 72x 72x 72x 72x 72x 72x 71x 71x 71x 71x 70x 70x 70x 70x 72x 35x 35x 35x 73x 73x 73x 35x 35x 35x 35x 35x 35x 7107x 7107x 7065x 7065x 35x 35x 35x           35x 35x 35x 30x 120x 120x 120x 120x 120x 120x 120x 30x 30x 30x 30x 1x 30x 30x 30x 5x 30x 30x 30x 2x 30x 30x 30x 12x 30x 30x 30x 22x 22x 30x 30x 30x 19x 19x 30x 30x 30x 2x 2x 30x 30x 30x     30x 30x 30x   30x 30x 30x 2x 30x 30x 30x 6x 30x 30x 30x 27x 30x 30x 30x   30x 30x 30x     30x 30x 30x   30x 30x 30x 3x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 16x 2x 16x 14x 14x 16x 2x 2x 86x 86x 86x 86x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x       2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 30x 30x 30x 1x 30x 30x 30x 7x 30x 30x 30x 1x 1x 1x 1x 1x 1x 1x 30x 30x 30x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 30x 30x 30x 1x 1x 1x 1x 1x 1x 1x 30x 30x 30x 30x 30x 30x 30x 30x 1x 30x 30x 1x 30x 30x 1x 30x 30x 30x 30x 30x 30x 35x 35x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 35x 35x 30x 17x 30x 30x 17x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 1x 1x 30x 30x 30x 35x 35x 38x  
'use strict';
 
const {
  Array,
  ArrayFrom,
  ArrayPrototypeFilter,
  ArrayPrototypeFind,
  ArrayPrototypeForEach,
  ArrayPrototypeIncludes,
  ArrayPrototypeIndexOf,
  ArrayPrototypeJoin,
  ArrayPrototypeMap,
  ArrayPrototypePush,
  ArrayPrototypeSlice,
  ArrayPrototypeSome,
  ArrayPrototypeSplice,
  Date,
  FunctionPrototypeCall,
  JSONStringify,
  MathMax,
  ObjectAssign,
  ObjectDefineProperty,
  ObjectKeys,
  ObjectValues,
  Promise,
  PromiseAll,
  PromisePrototypeCatch,
  PromisePrototypeThen,
  PromiseResolve,
  ReflectGetOwnPropertyDescriptor,
  ReflectOwnKeys,
  RegExpPrototypeSymbolMatch,
  RegExpPrototypeSymbolReplace,
  SafeArrayIterator,
  SafeMap,
  String,
  StringFromCharCode,
  StringPrototypeEndsWith,
  StringPrototypeIncludes,
  StringPrototypeRepeat,
  StringPrototypeSlice,
  StringPrototypeSplit,
  StringPrototypeStartsWith,
  StringPrototypeToUpperCase,
  StringPrototypeTrim,
} = primordials;
 
const { ERR_DEBUGGER_ERROR } = require('internal/errors').codes;
 
const { validateString } = require('internal/validators');
 
const FS = require('fs');
const Path = require('path');
const Repl = require('repl');
const vm = require('vm');
const { fileURLToPath } = require('internal/url');
 
const { customInspectSymbol } = require('internal/util');
const { inspect: utilInspect } = require('internal/util/inspect');
const debuglog = require('internal/util/debuglog').debuglog('inspect');
 
const SHORTCUTS = {
  cont: 'c',
  next: 'n',
  step: 's',
  out: 'o',
  backtrace: 'bt',
  setBreakpoint: 'sb',
  clearBreakpoint: 'cb',
  run: 'r',
  exec: 'p'
};
 
const HELP = StringPrototypeTrim(`
run, restart, r       Run the application or reconnect
kill                  Kill a running application or disconnect
 
cont, c               Resume execution
next, n               Continue to next line in current file
step, s               Step into, potentially entering a function
out, o                Step out, leaving the current function
backtrace, bt         Print the current backtrace
list                  Print the source around the current line where execution
                      is currently paused
 
setBreakpoint, sb     Set a breakpoint
clearBreakpoint, cb   Clear a breakpoint
breakpoints           List all known breakpoints
breakOnException      Pause execution whenever an exception is thrown
breakOnUncaught       Pause execution whenever an exception isn't caught
breakOnNone           Don't pause on exceptions (this is the default)
 
watch(expr)           Start watching the given expression
unwatch(expr)         Stop watching an expression
watchers              Print all watched expressions and their current values
 
exec(expr), p(expr), exec expr, p expr
                      Evaluate the expression and print the value
repl                  Enter a debug repl that works like exec
 
scripts               List application scripts that are currently loaded
scripts(true)         List all scripts (including node-internals)
 
profile               Start CPU profiling session.
profileEnd            Stop current CPU profiling session.
profiles              Array of completed CPU profiling sessions.
profiles[n].save(filepath = 'node.cpuprofile')
                      Save CPU profiling session to disk as JSON.
 
takeHeapSnapshot(filepath = 'node.heapsnapshot')
                      Take a heap snapshot and save to disk as JSON.
`);
 
const FUNCTION_NAME_PATTERN = /^(?:function\*? )?([^(\s]+)\(/;
function extractFunctionName(description) {
  const fnNameMatch =
    RegExpPrototypeSymbolMatch(FUNCTION_NAME_PATTERN, description);
  return fnNameMatch ? `: ${fnNameMatch[1]}` : '';
}
 
const {
  moduleIds: PUBLIC_BUILTINS,
} = internalBinding('native_module');
const NATIVES = internalBinding('natives');
function isNativeUrl(url) {
  url = RegExpPrototypeSymbolReplace(/\.js$/, url, '');
 
  return StringPrototypeStartsWith(url, 'node:internal/') ||
         ArrayPrototypeIncludes(PUBLIC_BUILTINS, url) ||
         url in NATIVES || url === 'bootstrap_node';
}
 
function getRelativePath(filenameOrURL) {
  const dir = StringPrototypeSlice(Path.join(Path.resolve(), 'x'), 0, -1);
 
  const filename = StringPrototypeStartsWith(filenameOrURL, 'file://') ?
    fileURLToPath(filenameOrURL) : filenameOrURL;
 
  // Change path to relative, if possible
  if (StringPrototypeStartsWith(filename, dir)) {
    return StringPrototypeSlice(filename, dir.length);
  }
  return filename;
}
 
// Adds spaces and prefix to number
// maxN is a maximum number we should have space for
function leftPad(n, prefix, maxN) {
  const s = n.toString();
  const nchars = MathMax(2, String(maxN).length);
  const nspaces = nchars - s.length;
 
  return prefix + StringPrototypeRepeat(' ', nspaces) + s;
}
 
function markSourceColumn(sourceText, position, useColors) {
  if (!sourceText) return '';
 
  const head = StringPrototypeSlice(sourceText, 0, position);
  let tail = StringPrototypeSlice(sourceText, position);
 
  // Colourize char if stdout supports colours
  if (useColors) {
    tail = RegExpPrototypeSymbolReplace(/(.+?)([^\w]|$)/, tail,
                                        '\u001b[32m$1\u001b[39m$2');
  }
 
  // Return source line with coloured char at `position`
  return head + tail;
}
 
function extractErrorMessage(stack) {
  if (!stack) return '<unknown>';
  const m = RegExpPrototypeSymbolMatch(/^\w+: ([^\n]+)/, stack);
  return m?.[1] ?? stack;
}
 
function convertResultToError(result) {
  const { className, description } = result;
  const err = new ERR_DEBUGGER_ERROR(extractErrorMessage(description));
  err.stack = description;
  ObjectDefineProperty(err, 'name', { __proto__: null, value: className });
  return err;
}
 
class PropertyPreview {
  constructor(attributes) {
    ObjectAssign(this, attributes);
  }
 
  [customInspectSymbol](depth, opts) {
    switch (this.type) {
      case 'string':
      case 'undefined':
        return utilInspect(this.value, opts);
      case 'number':
      case 'boolean':
        return opts.stylize(this.value, this.type);
      case 'object':
      case 'symbol':
        if (this.subtype === 'date') {
          return utilInspect(new Date(this.value), opts);
        }
        if (this.subtype === 'array') {
          return opts.stylize(this.value, 'special');
        }
        return opts.stylize(this.value, this.subtype || 'special');
      default:
        return this.value;
    }
  }
}
 
class ObjectPreview {
  constructor(attributes) {
    ObjectAssign(this, attributes);
  }
 
  [customInspectSymbol](depth, opts) {
    switch (this.type) {
      case 'object': {
        switch (this.subtype) {
          case 'date':
            return utilInspect(new Date(this.description), opts);
          case 'null':
            return utilInspect(null, opts);
          case 'regexp':
            return opts.stylize(this.description, 'regexp');
          case 'set': {
            if (!this.entries) {
              return `${this.description} ${this.overflow ? '{ ... }' : '{}'}`;
            }
            const values = ArrayPrototypeMap(this.entries, (entry) =>
              utilInspect(new ObjectPreview(entry.value), opts));
            return `${this.description} { ${ArrayPrototypeJoin(values, ', ')} }`;
          }
          case 'map': {
            if (!this.entries) {
              return `${this.description} ${this.overflow ? '{ ... }' : '{}'}`;
            }
            const mappings = ArrayPrototypeMap(this.entries, (entry) => {
              const key = utilInspect(new ObjectPreview(entry.key), opts);
              const value = utilInspect(new ObjectPreview(entry.value), opts);
              return `${key} => ${value}`;
            });
            return `${this.description} { ${ArrayPrototypeJoin(mappings, ', ')} }`;
          }
          case 'array':
          case undefined: {
            if (this.properties.length === 0) {
              return this.subtype === 'array' ? '[]' : '{}';
            }
            const props = ArrayPrototypeMap(this.properties, (prop, idx) => {
              const value = utilInspect(new PropertyPreview(prop));
              if (prop.name === `${idx}`) return value;
              return `${prop.name}: ${value}`;
            });
            if (this.overflow) {
              ArrayPrototypePush(props, '...');
            }
            const singleLine = ArrayPrototypeJoin(props, ', ');
            const propString = singleLine.length > 60 ? ArrayPrototypeJoin(props, ',\n  ') : singleLine;
            return this.subtype === 'array' ? `[ ${propString} ]` : `{ ${propString} }`;
          }
          default:
            return this.description;
        }
      }
      default:
        return this.description;
    }
  }
}
 
class RemoteObject {
  constructor(attributes) {
    ObjectAssign(this, attributes);
    if (this.type === 'number') {
      this.value =
        this.unserializableValue ? +this.unserializableValue : +this.value;
    }
  }
 
  [customInspectSymbol](depth, opts) {
    switch (this.type) {
      case 'boolean':
      case 'number':
      case 'string':
      case 'undefined':
        return utilInspect(this.value, opts);
      case 'symbol':
        return opts.stylize(this.description, 'special');
      case 'function': {
        const fnName = extractFunctionName(this.description);
        const formatted = `[${this.className}${fnName}]`;
        return opts.stylize(formatted, 'special');
      }
      case 'object':
        switch (this.subtype) {
          case 'date':
            return utilInspect(new Date(this.description), opts);
          case 'null':
            return utilInspect(null, opts);
          case 'regexp':
            return opts.stylize(this.description, 'regexp');
          case 'map':
          case 'set': {
            const preview = utilInspect(new ObjectPreview(this.preview), opts);
            return `${this.description} ${preview}`;
          }
          default:
            break;
        }
        if (this.preview) {
          return utilInspect(new ObjectPreview(this.preview), opts);
        }
        return this.description;
      default:
        return this.description;
    }
  }
 
  static fromEvalResult({ result, wasThrown }) {
    if (wasThrown) return convertResultToError(result);
    return new RemoteObject(result);
  }
}
 
class ScopeSnapshot {
  constructor(scope, properties) {
    ObjectAssign(this, scope);
    this.properties = new SafeMap();
    this.completionGroup = ArrayPrototypeMap(properties, (prop) => {
      const value = new RemoteObject(prop.value);
      this.properties.set(prop.name, value);
      return prop.name;
    });
  }
 
  [customInspectSymbol](depth, opts) {
    const type = StringPrototypeToUpperCase(this.type[0]) +
                 StringPrototypeSlice(this.type, 1);
    const name = this.name ? `<${this.name}>` : '';
    const prefix = `${type}${name} `;
    return RegExpPrototypeSymbolReplace(/^Map /,
                                        utilInspect(this.properties, opts),
                                        prefix);
  }
}
 
function copyOwnProperties(target, source) {
  ArrayPrototypeForEach(
    ReflectOwnKeys(source),
    (prop) => {
      const desc = ReflectGetOwnPropertyDescriptor(source, prop);
      ObjectDefineProperty(target, prop, desc);
    });
}
 
function aliasProperties(target, mapping) {
  ArrayPrototypeForEach(ObjectKeys(mapping), (key) => {
    const desc = ReflectGetOwnPropertyDescriptor(target, key);
    ObjectDefineProperty(target, mapping[key], desc);
  });
}
 
function createRepl(inspector) {
  const { Debugger, HeapProfiler, Profiler, Runtime } = inspector;
 
  let repl;
 
  // Things we want to keep around
  const history = { control: [], debug: [] };
  const watchedExpressions = [];
  const knownBreakpoints = [];
  let heapSnapshotPromise = null;
  let pauseOnExceptionState = 'none';
  let lastCommand;
 
  // Things we need to reset when the app restarts
  let knownScripts;
  let currentBacktrace;
  let selectedFrame;
  let exitDebugRepl;
 
  function resetOnStart() {
    knownScripts = {};
    currentBacktrace = null;
    selectedFrame = null;
 
    if (exitDebugRepl) exitDebugRepl();
    exitDebugRepl = null;
  }
  resetOnStart();
 
  const INSPECT_OPTIONS = { colors: inspector.stdout.isTTY };
  function inspect(value) {
    return utilInspect(value, INSPECT_OPTIONS);
  }
 
  function print(value, addNewline = true) {
    const text = typeof value === 'string' ? value : inspect(value);
    return inspector.print(text, addNewline);
  }
 
  function getCurrentLocation() {
    if (!selectedFrame) {
      throw new ERR_DEBUGGER_ERROR('Requires execution to be paused');
    }
    return selectedFrame.location;
  }
 
  function isCurrentScript(script) {
    return selectedFrame && getCurrentLocation().scriptId === script.scriptId;
  }
 
  function formatScripts(displayNatives = false) {
    function isVisible(script) {
      if (displayNatives) return true;
      return !script.isNative || isCurrentScript(script);
    }
 
    return ArrayPrototypeJoin(ArrayPrototypeMap(
      ArrayPrototypeFilter(ObjectValues(knownScripts), isVisible),
      (script) => {
        const isCurrent = isCurrentScript(script);
        const { isNative, url } = script;
        const name = `${getRelativePath(url)}${isNative ? ' <native>' : ''}`;
        return `${isCurrent ? '*' : ' '} ${script.scriptId}: ${name}`;
      }), '\n');
  }
 
  function listScripts(displayNatives = false) {
    print(formatScripts(displayNatives));
  }
  listScripts[customInspectSymbol] = function listWithoutInternal() {
    return formatScripts();
  };
 
  const profiles = [];
  class Profile {
    constructor(data) {
      this.data = data;
    }
 
    static createAndRegister({ profile }) {
      const p = new Profile(profile);
      ArrayPrototypePush(profiles, p);
      return p;
    }
 
    [customInspectSymbol](depth, { stylize }) {
      const { startTime, endTime } = this.data;
      const MU = StringFromCharCode(956);
      return stylize(`[Profile ${endTime - startTime}${MU}s]`, 'special');
    }
 
    save(filename = 'node.cpuprofile') {
      const absoluteFile = Path.resolve(filename);
      const json = JSONStringify(this.data);
      FS.writeFileSync(absoluteFile, json);
      print('Saved profile to ' + absoluteFile);
    }
  }
 
  class SourceSnippet {
    constructor(location, delta, scriptSource) {
      ObjectAssign(this, location);
      this.scriptSource = scriptSource;
      this.delta = delta;
    }
 
    [customInspectSymbol](depth, options) {
      const { scriptId, lineNumber, columnNumber, delta, scriptSource } = this;
      const start = MathMax(1, lineNumber - delta + 1);
      const end = lineNumber + delta + 1;
 
      const lines = StringPrototypeSplit(scriptSource, '\n');
      return ArrayPrototypeJoin(
        ArrayPrototypeMap(
          ArrayPrototypeSlice(lines, start - 1, end),
          (lineText, offset) => {
            const i = start + offset;
            const isCurrent = i === (lineNumber + 1);
 
            const markedLine = isCurrent ?
              markSourceColumn(lineText, columnNumber, options.colors) :
              lineText;
 
            let isBreakpoint = false;
            ArrayPrototypeForEach(knownBreakpoints, ({ location }) => {
              if (!location) return;
              if (scriptId === location.scriptId &&
              i === (location.lineNumber + 1)) {
                isBreakpoint = true;
              }
            });
 
            let prefixChar = ' ';
            if (isCurrent) {
              prefixChar = '>';
            } else if (isBreakpoint) {
              prefixChar = '*';
            }
            return `${leftPad(i, prefixChar, end)} ${markedLine}`;
          }), '\n');
    }
  }
 
  async function getSourceSnippet(location, delta = 5) {
    const { scriptId } = location;
    const { scriptSource } = await Debugger.getScriptSource({ scriptId });
    return new SourceSnippet(location, delta, scriptSource);
  }
 
  class CallFrame {
    constructor(callFrame) {
      ObjectAssign(this, callFrame);
    }
 
    loadScopes() {
      return PromiseAll(
        new SafeArrayIterator(ArrayPrototypeMap(
          ArrayPrototypeFilter(
            this.scopeChain,
            (scope) => scope.type !== 'global'
          ),
          async (scope) => {
            const { objectId } = scope.object;
            const { result } = await Runtime.getProperties({
              objectId,
              generatePreview: true,
            });
            return new ScopeSnapshot(scope, result);
          })
        )
      );
    }
 
    list(delta = 5) {
      return getSourceSnippet(this.location, delta);
    }
  }
 
  class Backtrace extends Array {
    [customInspectSymbol]() {
      return ArrayPrototypeJoin(
        ArrayPrototypeMap(this, (callFrame, idx) => {
          const {
            location: { scriptId, lineNumber, columnNumber },
            functionName
          } = callFrame;
          const name = functionName || '(anonymous)';
 
          const script = knownScripts[scriptId];
          const relativeUrl =
          (script && getRelativePath(script.url)) || '<unknown>';
          const frameLocation =
          `${relativeUrl}:${lineNumber + 1}:${columnNumber}`;
 
          return `#${idx} ${name} ${frameLocation}`;
        }), '\n');
    }
 
    static from(callFrames) {
      return FunctionPrototypeCall(
        ArrayFrom,
        this,
        callFrames,
        (callFrame) =>
          (callFrame instanceof CallFrame ?
            callFrame :
            new CallFrame(callFrame))
      );
    }
  }
 
  function prepareControlCode(input) {
    if (input === '\n') return lastCommand;
    // Add parentheses: exec process.title => exec("process.title");
    const match = RegExpPrototypeSymbolMatch(/^\s*(?:exec|p)\s+([^\n]*)/, input);
    if (match) {
      lastCommand = `exec(${JSONStringify(match[1])})`;
    } else {
      lastCommand = input;
    }
    return lastCommand;
  }
 
  async function evalInCurrentContext(code) {
    // Repl asked for scope variables
    if (code === '.scope') {
      if (!selectedFrame) {
        throw new ERR_DEBUGGER_ERROR('Requires execution to be paused');
      }
      const scopes = await selectedFrame.loadScopes();
      return ArrayPrototypeMap(scopes, (scope) => scope.completionGroup);
    }
 
    if (selectedFrame) {
      return PromisePrototypeThen(Debugger.evaluateOnCallFrame({
        callFrameId: selectedFrame.callFrameId,
        expression: code,
        objectGroup: 'node-inspect',
        generatePreview: true,
      }), RemoteObject.fromEvalResult);
    }
    return PromisePrototypeThen(Runtime.evaluate({
      expression: code,
      objectGroup: 'node-inspect',
      generatePreview: true,
    }), RemoteObject.fromEvalResult);
  }
 
  function controlEval(input, context, filename, callback) {
    debuglog('eval:', input);
    function returnToCallback(error, result) {
      debuglog('end-eval:', input, error);
      callback(error, result);
    }
 
    try {
      const code = prepareControlCode(input);
      const result = vm.runInContext(code, context, filename);
 
      const then = result?.then;
      if (typeof then === 'function') {
        FunctionPrototypeCall(
          then, result,
          (result) => returnToCallback(null, result),
          returnToCallback
        );
      } else {
        returnToCallback(null, result);
      }
    } catch (e) {
      returnToCallback(e);
    }
  }
 
  function debugEval(input, context, filename, callback) {
    debuglog('eval:', input);
    function returnToCallback(error, result) {
      debuglog('end-eval:', input, error);
      callback(error, result);
    }
 
    PromisePrototypeThen(evalInCurrentContext(input),
                         (result) => returnToCallback(null, result),
                         returnToCallback
    );
  }
 
  async function formatWatchers(verbose = false) {
    if (!watchedExpressions.length) {
      return '';
    }
 
    const inspectValue = (expr) =>
      PromisePrototypeCatch(evalInCurrentContext(expr),
                            (error) => `<${error.message}>`);
    const lastIndex = watchedExpressions.length - 1;
 
    const values = await PromiseAll(new SafeArrayIterator(
      ArrayPrototypeMap(watchedExpressions, inspectValue)));
    const lines = ArrayPrototypeMap(watchedExpressions, (expr, idx) => {
      const prefix = `${leftPad(idx, ' ', lastIndex)}: ${expr} =`;
      const value = inspect(values[idx]);
      if (!StringPrototypeIncludes(value, '\n')) {
        return `${prefix} ${value}`;
      }
      return `${prefix}\n    ${RegExpPrototypeSymbolReplace(/\n/g, value, '\n    ')}`;
    });
    const valueList = ArrayPrototypeJoin(lines, '\n');
    return verbose ? `Watchers:\n${valueList}\n` : valueList;
  }
 
  function watchers(verbose = false) {
    return PromisePrototypeThen(formatWatchers(verbose), print);
  }
 
  // List source code
  function list(delta = 5) {
    if (!selectedFrame) {
      throw new ERR_DEBUGGER_ERROR('Requires execution to be paused');
    }
    return selectedFrame.list(delta).then(null, (error) => {
      print("You can't list source code right now");
      throw error;
    });
  }
 
  function handleBreakpointResolved({ breakpointId, location }) {
    const script = knownScripts[location.scriptId];
    const scriptUrl = script && script.url;
    if (scriptUrl) {
      ObjectAssign(location, { scriptUrl });
    }
    const isExisting = ArrayPrototypeSome(knownBreakpoints, (bp) => {
      if (bp.breakpointId === breakpointId) {
        ObjectAssign(bp, { location });
        return true;
      }
      return false;
    });
    if (!isExisting) {
      ArrayPrototypePush(knownBreakpoints, { breakpointId, location });
    }
  }
 
  function listBreakpoints() {
    if (!knownBreakpoints.length) {
      print('No breakpoints yet');
      return;
    }
 
    function formatLocation(location) {
      if (!location) return '<unknown location>';
      const script = knownScripts[location.scriptId];
      const scriptUrl = script ? script.url : location.scriptUrl;
      return `${getRelativePath(scriptUrl)}:${location.lineNumber + 1}`;
    }
    const breaklist = ArrayPrototypeJoin(
      ArrayPrototypeMap(
        knownBreakpoints,
        (bp, idx) => `#${idx} ${formatLocation(bp.location)}`),
      '\n');
    print(breaklist);
  }
 
  function setBreakpoint(script, line, condition, silent) {
    function registerBreakpoint({ breakpointId, actualLocation }) {
      handleBreakpointResolved({ breakpointId, location: actualLocation });
      if (actualLocation && actualLocation.scriptId) {
        if (!silent) return getSourceSnippet(actualLocation, 5);
      } else {
        print(`Warning: script '${script}' was not loaded yet.`);
      }
      return undefined;
    }
 
    // setBreakpoint(): set breakpoint at current location
    if (script === undefined) {
      return PromisePrototypeThen(
        Debugger.setBreakpoint({ location: getCurrentLocation(), condition }),
        registerBreakpoint);
    }
 
    // setBreakpoint(line): set breakpoint in current script at specific line
    if (line === undefined && typeof script === 'number') {
      const location = {
        scriptId: getCurrentLocation().scriptId,
        lineNumber: script - 1,
      };
      return PromisePrototypeThen(
        Debugger.setBreakpoint({ location, condition }),
        registerBreakpoint);
    }
 
    validateString(script, 'script');
 
    // setBreakpoint('fn()'): Break when a function is called
    if (StringPrototypeEndsWith(script, '()')) {
      const debugExpr = `debug(${script.slice(0, -2)})`;
      const debugCall = selectedFrame ?
        Debugger.evaluateOnCallFrame({
          callFrameId: selectedFrame.callFrameId,
          expression: debugExpr,
          includeCommandLineAPI: true,
        }) :
        Runtime.evaluate({
          expression: debugExpr,
          includeCommandLineAPI: true,
        });
      return PromisePrototypeThen(debugCall, ({ result, wasThrown }) => {
        if (wasThrown) return convertResultToError(result);
        return undefined; // This breakpoint can't be removed the same way
      });
    }
 
    // setBreakpoint('scriptname')
    let scriptId = null;
    let ambiguous = false;
    if (knownScripts[script]) {
      scriptId = script;
    } else {
      ArrayPrototypeForEach(ObjectKeys(knownScripts), (id) => {
        const scriptUrl = knownScripts[id].url;
        if (scriptUrl && StringPrototypeIncludes(scriptUrl, script)) {
          if (scriptId !== null) {
            ambiguous = true;
          }
          scriptId = id;
        }
      });
    }
 
    if (ambiguous) {
      print('Script name is ambiguous');
      return undefined;
    }
    if (line <= 0) {
      print('Line should be a positive value');
      return undefined;
    }
 
    if (scriptId !== null) {
      const location = { scriptId, lineNumber: line - 1 };
      return PromisePrototypeThen(
        Debugger.setBreakpoint({ location, condition }),
        registerBreakpoint);
    }
 
    const escapedPath = RegExpPrototypeSymbolReplace(/([/\\.?*()^${}|[\]])/g,
                                                     script, '\\$1');
    const urlRegex = `^(.*[\\/\\\\])?${escapedPath}$`;
 
    return PromisePrototypeThen(
      Debugger.setBreakpointByUrl({
        urlRegex,
        lineNumber: line - 1,
        condition,
      }),
      (bp) => {
        // TODO: handle bp.locations in case the regex matches existing files
        if (!bp.location) { // Fake it for now.
          ObjectAssign(bp, {
            actualLocation: {
              scriptUrl: `.*/${script}$`,
              lineNumber: line - 1,
            },
          });
        }
        return registerBreakpoint(bp);
      });
  }
 
  function clearBreakpoint(url, line) {
    const breakpoint = ArrayPrototypeFind(knownBreakpoints, ({ location }) => {
      if (!location) return false;
      const script = knownScripts[location.scriptId];
      if (!script) return false;
      return (
        StringPrototypeIncludes(script.url, url) &&
        (location.lineNumber + 1) === line
      );
    });
    if (!breakpoint) {
      print(`Could not find breakpoint at ${url}:${line}`);
      return PromiseResolve();
    }
    return PromisePrototypeThen(
      Debugger.removeBreakpoint({ breakpointId: breakpoint.breakpointId }),
      () => {
        const idx = ArrayPrototypeIndexOf(knownBreakpoints, breakpoint);
        ArrayPrototypeSplice(knownBreakpoints, idx, 1);
      });
  }
 
  function restoreBreakpoints() {
    const lastBreakpoints = ArrayPrototypeSplice(knownBreakpoints, 0);
    const newBreakpoints = ArrayPrototypeMap(
      ArrayPrototypeFilter(lastBreakpoints,
                           ({ location }) => !!location.scriptUrl),
      ({ location }) => setBreakpoint(location.scriptUrl,
                                      location.lineNumber + 1));
    if (!newBreakpoints.length) return PromiseResolve();
    return PromisePrototypeThen(
      PromiseAll(new SafeArrayIterator(newBreakpoints)),
      (results) => {
        print(`${results.length} breakpoints restored.`);
      });
  }
 
  function setPauseOnExceptions(state) {
    return PromisePrototypeThen(
      Debugger.setPauseOnExceptions({ state }),
      () => {
        pauseOnExceptionState = state;
      });
  }
 
  Debugger.on('paused', ({ callFrames, reason /* , hitBreakpoints */ }) => {
    if (process.env.NODE_INSPECT_RESUME_ON_START === '1' &&
        reason === 'Break on start') {
      debuglog('Paused on start, but NODE_INSPECT_RESUME_ON_START' +
              ' environment variable is set to 1, resuming');
      inspector.client.callMethod('Debugger.resume');
      return;
    }
 
    // Save execution context's data
    currentBacktrace = Backtrace.from(callFrames);
    selectedFrame = currentBacktrace[0];
    const { scriptId, lineNumber } = selectedFrame.location;
 
    const breakType = reason === 'other' ? 'break' : reason;
    const script = knownScripts[scriptId];
    const scriptUrl = script ? getRelativePath(script.url) : '[unknown]';
 
    const header = `${breakType} in ${scriptUrl}:${lineNumber + 1}`;
 
    inspector.suspendReplWhile(() =>
      PromisePrototypeThen(
        PromiseAll(new SafeArrayIterator(
          [formatWatchers(true), selectedFrame.list(2)])),
        ({ 0: watcherList, 1: context }) => {
          const breakContext = watcherList ?
            `${watcherList}\n${inspect(context)}` :
            inspect(context);
          print(`${header}\n${breakContext}`);
        }));
  });
 
  function handleResumed() {
    currentBacktrace = null;
    selectedFrame = null;
  }
 
  Debugger.on('resumed', handleResumed);
 
  Debugger.on('breakpointResolved', handleBreakpointResolved);
 
  Debugger.on('scriptParsed', (script) => {
    const { scriptId, url } = script;
    if (url) {
      knownScripts[scriptId] = { isNative: isNativeUrl(url), ...script };
    }
  });
 
  Profiler.on('consoleProfileFinished', ({ profile }) => {
    Profile.createAndRegister({ profile });
    print(
      'Captured new CPU profile.\n' +
      `Access it with profiles[${profiles.length - 1}]`
    );
  });
 
  function initializeContext(context) {
    ArrayPrototypeForEach(inspector.domainNames, (domain) => {
      ObjectDefineProperty(context, domain, {
        __proto__: null,
        value: inspector[domain],
        enumerable: true,
        configurable: true,
        writeable: false,
      });
    });
 
    copyOwnProperties(context, {
      get help() {
        return print(HELP);
      },
 
      get run() {
        return inspector.run();
      },
 
      get kill() {
        return inspector.killChild();
      },
 
      get restart() {
        return inspector.run();
      },
 
      get cont() {
        handleResumed();
        return Debugger.resume();
      },
 
      get next() {
        handleResumed();
        return Debugger.stepOver();
      },
 
      get step() {
        handleResumed();
        return Debugger.stepInto();
      },
 
      get out() {
        handleResumed();
        return Debugger.stepOut();
      },
 
      get pause() {
        return Debugger.pause();
      },
 
      get backtrace() {
        return currentBacktrace;
      },
 
      get breakpoints() {
        return listBreakpoints();
      },
 
      exec(expr) {
        return evalInCurrentContext(expr);
      },
 
      get profile() {
        return Profiler.start();
      },
 
      get profileEnd() {
        return PromisePrototypeThen(Profiler.stop(),
                                    Profile.createAndRegister);
      },
 
      get profiles() {
        return profiles;
      },
 
      takeHeapSnapshot(filename = 'node.heapsnapshot') {
        if (heapSnapshotPromise) {
          print(
            'Cannot take heap snapshot because another snapshot is in progress.'
          );
          return heapSnapshotPromise;
        }
        heapSnapshotPromise = new Promise((resolve, reject) => {
          const absoluteFile = Path.resolve(filename);
          const writer = FS.createWriteStream(absoluteFile);
          let sizeWritten = 0;
          function onProgress({ done, total, finished }) {
            if (finished) {
              print('Heap snapshot prepared.');
            } else {
              print(`Heap snapshot: ${done}/${total}`, false);
            }
          }
 
          function onChunk({ chunk }) {
            sizeWritten += chunk.length;
            writer.write(chunk);
            print(`Writing snapshot: ${sizeWritten}`, false);
          }
 
          function onResolve() {
            writer.end(() => {
              teardown();
              print(`Wrote snapshot: ${absoluteFile}`);
              heapSnapshotPromise = null;
              resolve();
            });
          }
 
          function onReject(error) {
            teardown();
            reject(error);
          }
 
          function teardown() {
            HeapProfiler.removeListener(
              'reportHeapSnapshotProgress', onProgress);
            HeapProfiler.removeListener('addHeapSnapshotChunk', onChunk);
          }
 
          HeapProfiler.on('reportHeapSnapshotProgress', onProgress);
          HeapProfiler.on('addHeapSnapshotChunk', onChunk);
 
          print('Heap snapshot: 0/0', false);
          PromisePrototypeThen(
            HeapProfiler.takeHeapSnapshot({ reportProgress: true }),
            onResolve, onReject);
        });
        return heapSnapshotPromise;
      },
 
      get watchers() {
        return watchers();
      },
 
      watch(expr) {
        ArrayPrototypePush(watchedExpressions, expr);
      },
 
      unwatch(expr) {
        const index = ArrayPrototypeIndexOf(watchedExpressions, expr);
 
        // Unwatch by expression
        // or
        // Unwatch by watcher number
        ArrayPrototypeSplice(watchedExpressions,
                             index !== -1 ? index : +expr, 1);
      },
 
      get repl() {
        // Don't display any default messages
        const listeners = ArrayPrototypeSlice(repl.listeners('SIGINT'));
        repl.removeAllListeners('SIGINT');
 
        const oldContext = repl.context;
 
        exitDebugRepl = () => {
          // Restore all listeners
          process.nextTick(() => {
            ArrayPrototypeForEach(listeners, (listener) => {
              repl.on('SIGINT', listener);
            });
          });
 
          // Exit debug repl
          repl.eval = controlEval;
 
          // Swap history
          history.debug = repl.history;
          repl.history = history.control;
 
          repl.context = oldContext;
          repl.setPrompt('debug> ');
          repl.displayPrompt();
 
          repl.removeListener('SIGINT', exitDebugRepl);
          repl.removeListener('exit', exitDebugRepl);
 
          exitDebugRepl = null;
        };
 
        // Exit debug repl on SIGINT
        repl.on('SIGINT', exitDebugRepl);
 
        // Exit debug repl on repl exit
        repl.on('exit', exitDebugRepl);
 
        // Set new
        repl.eval = debugEval;
        repl.context = {};
 
        // Swap history
        history.control = repl.history;
        repl.history = history.debug;
 
        repl.setPrompt('> ');
 
        print('Press Ctrl+C to leave debug repl');
        return repl.displayPrompt();
      },
 
      get version() {
        return PromisePrototypeThen(Runtime.evaluate({
          expression: 'process.versions.v8',
          contextId: 1,
          returnByValue: true,
        }), ({ result }) => {
          print(result.value);
        });
      },
 
      scripts: listScripts,
 
      setBreakpoint,
      clearBreakpoint,
      setPauseOnExceptions,
      get breakOnException() {
        return setPauseOnExceptions('all');
      },
      get breakOnUncaught() {
        return setPauseOnExceptions('uncaught');
      },
      get breakOnNone() {
        return setPauseOnExceptions('none');
      },
 
      list,
    });
    aliasProperties(context, SHORTCUTS);
  }
 
  async function initAfterStart() {
    await Runtime.enable();
    await Profiler.enable();
    await Profiler.setSamplingInterval({ interval: 100 });
    await Debugger.enable();
    await Debugger.setAsyncCallStackDepth({ maxDepth: 0 });
    await Debugger.setBlackboxPatterns({ patterns: [] });
    await Debugger.setPauseOnExceptions({ state: pauseOnExceptionState });
    await restoreBreakpoints();
    return Runtime.runIfWaitingForDebugger();
  }
 
  return async function startRepl() {
    inspector.client.on('close', () => {
      resetOnStart();
    });
    inspector.client.on('ready', () => {
      initAfterStart();
    });
 
    // Init once for the initial connection
    await initAfterStart();
 
    const replOptions = {
      prompt: 'debug> ',
      input: inspector.stdin,
      output: inspector.stdout,
      eval: controlEval,
      useGlobal: false,
      ignoreUndefined: true,
    };
 
    repl = Repl.start(replOptions);
    initializeContext(repl.context);
    repl.on('reset', initializeContext);
 
    repl.defineCommand('interrupt', () => {
      // We want this for testing purposes where sending Ctrl+C can be tricky.
      repl.emit('SIGINT');
    });
 
    return repl;
  };
}
module.exports = createRepl;