All files / lib/internal/webstreams writablestream.js

100% Statements 1330/1330
99.28% Branches 274/276
96.83% Functions 61/63
100% Lines 1330/1330

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 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 608x 608x 608x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 605x 608x 608x 608x 608x 608x 608x 608x 608x 608x 608x 608x 608x 150x 150x 150x 150x 150x 150x 56x 56x 53x 56x 150x 150x 150x 150x 150x 150x 31x 31x 28x 2x 2x 2x 26x 31x 150x 150x 150x 150x 150x 17x 17x 14x 3x 3x 3x 13x 1x 1x 1x 10x 17x 150x 150x 150x 150x 150x 412x 412x 409x 412x 150x 150x 11x 11x 11x 11x 11x 150x 150x 10x 10x 9x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 10x 150x 150x 8x 8x 8x 8x 8x 150x 150x 8x 8x 8x 8x 8x 8x 8x 150x 150x 150x 150x 150x 150x 150x 150x 150x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 609x 609x 607x 607x 607x 607x 607x 607x 607x 607x 607x 607x 607x 607x 607x 607x 609x 150x 150x 150x 150x 150x 150x 194x 194x 191x 194x 150x 150x 150x 150x 150x 150x 77x 77x 77x 1x 1x 1x 73x 77x 150x 150x 150x 150x 150x 150x 105x 105x 102x 105x 150x 150x 150x 150x 150x 150x 73x 73x 71x 1x 1x 1x 1x 69x 73x 150x 150x 150x 150x 150x 157x 157x 154x 154x 154x 157x 1x 1x 1x 1x 155x 2x 2x 2x 151x 157x 150x 150x 79x 79x 76x 76x 76x 76x 79x 75x 75x 79x 150x 150x 150x 150x 150x 150x 1287x 1287x 1287x 1x 1x 1x 1x 1283x 1287x 150x 150x 3x 3x 3x 3x 3x 3x 3x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 3x 3x 150x 150x 105x 105x 105x 105x 150x 150x 244x 244x 150x 150x 150x 150x 150x 5x 5x 4x 5x 150x 150x 150x 150x 150x 13x 13x 12x 13x 150x 150x 150x 150x 150x 63x 63x 60x 60x 49x 63x 150x 150x 3x 3x 3x 3x 150x 150x 150x 150x 150x 150x 150x 150x 598x 598x 598x 598x 598x 598x 598x 150x 150x 150x 150x 150x 150x 150x 150x 2244x 2244x 2244x 150x 607x 607x 607x 604x 604x 604x 605x 505x 505x 22x 504x 483x 483x 483x 483x 483x 483x 505x 505x 607x 25x 25x 25x 25x 25x 25x 25x 25x 607x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 607x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 607x 607x 607x 530x 530x 607x 150x 133x 133x 133x 133x 133x 133x 133x 128x 128x 128x 128x 128x 133x 125x 133x 133x 133x 133x 8x 8x 8x 125x 125x 125x 125x 125x 125x 125x 125x 125x 125x 133x 125x 125x 133x 150x 208x 208x 208x 208x 208x 208x 208x 208x 3x 3x 3x 208x 208x 208x 208x 208x 208x 205x 205x 208x 150x 3115x 3115x 3115x 3115x 3115x 3115x 3115x 362x 249x 298x 113x 113x 362x 3115x 3115x 150x 264x 264x 264x 264x 264x 264x 264x 264x 264x 264x 264x 206x 206x 264x 264x 104x 104x 264x 150x 244x 244x 244x 16x 16x 16x 16x 16x 16x 16x 16x 244x 244x 244x 244x 208x 208x 208x 244x 150x 1334x 1334x 1334x 1334x 1334x 1334x 150x 188x 188x 188x 188x 188x 188x 188x 188x 188x 188x 150x 508x 508x 508x 508x 508x 508x 508x 448x 448x 60x 508x 150x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x 150x 1274x 1274x 1274x 1274x 1274x 1274x 1274x 1274x 1274x 150x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 14x 14x 150x 170x 170x 170x 170x 170x 170x 170x 170x 170x 12x 12x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 12x 170x 170x 170x 170x 170x 170x 150x 244x 244x 244x 244x 244x 244x 244x 244x 244x 244x 244x 132x 132x 132x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 112x 244x 7x 7x 7x 7x 105x 105x 105x 105x 105x 105x 92x 92x 105x 105x 13x 13x 105x 244x 150x 73x 73x 73x 73x 73x 49x 49x 49x 24x 24x 24x 73x 150x 8356x 8356x 8356x 8206x 8206x 150x 8356x 150x 1360x 1360x 1360x 1360x 1360x 1360x 1360x 1360x 1360x 1360x 1360x 1360x 1360x 1360x 1360x 1360x 1360x 150x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 2x 2x 2x 1379x 1379x 1379x 1379x 1379x 1381x 1374x 1381x 1x 1x 1x 1373x 1373x 1381x 1360x 1360x 1360x 1360x 1360x 1360x 1381x 150x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 265x 150x 73x 73x 73x 73x 73x 73x 73x 73x 4x 73x 2x 73x 67x 67x 73x 150x 471x 471x 88x 458x 383x 383x 383x 383x 383x 383x 471x 471x 150x 265x 265x 88x 265x 177x 177x 177x 177x 177x 177x 265x 265x 150x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 47x 47x 48x 47x 48x 48x 48x 48x 150x 198x 198x 198x 198x 198x 198x 198x 150x 69x 69x 69x 69x 69x 69x 69x 150x 1360x 1360x 1360x 1360x 5x 5x 5x 1355x 1355x 1355x 1355x 1360x 1355x 1355x 1355x 1355x 1355x 1360x 150x 1334x 1334x 1334x 1334x 1334x 1334x 1334x 1334x 1334x 1334x 1274x 1274x 1274x 1274x 1274x 1274x 1274x 1274x 1172x 1172x 1172x 1172x 1274x 1334x 1334x 50x 50x 50x 1334x 1334x 1334x 150x 188x 188x 188x 188x 188x 188x 188x 188x 188x 188x 188x 188x 188x 188x 188x 188x 150x 3182x 3182x 3182x 3182x 3182x 3182x 3182x 150x 1381x 1381x 1381x 1381x 1381x 1381x 1381x 9x 9x 9x 1381x 150x 80x 80x 80x 80x 80x 80x 80x 150x 98x 98x 98x 98x 98x 98x 98x 98x 150x 205x 205x 205x 205x 150x 414x 414x 414x 414x 414x 414x 150x 3115x 3115x 3115x 150x 3408x 3408x 3408x 3408x 3408x 3408x 3408x 3408x 2063x 3408x 116x 116x 116x 1947x 1947x 3403x 1522x 1522x 1522x 3402x 1334x 1334x 3408x 150x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 598x 150x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 588x 574x 574x 574x 574x 588x 588x 9x 9x 9x 9x 588x 588x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x 150x  
'use strict';
 
/* eslint-disable no-use-before-define */
 
const {
  ArrayPrototypePush,
  ArrayPrototypeShift,
  FunctionPrototypeBind,
  FunctionPrototypeCall,
  ObjectDefineProperties,
  PromisePrototypeThen,
  PromiseResolve,
  PromiseReject,
  ReflectConstruct,
  Symbol,
  SymbolToStringTag,
} = primordials;
 
const {
  codes: {
    ERR_ILLEGAL_CONSTRUCTOR,
    ERR_INVALID_ARG_VALUE,
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_STATE,
    ERR_INVALID_THIS,
  },
} = require('internal/errors');
 
const {
  DOMException,
} = internalBinding('messaging');
 
const {
  createDeferredPromise,
  customInspectSymbol: kInspect,
} = require('internal/util');
 
const {
  MessageChannel,
} = require('internal/worker/io');
 
const {
  kDeserialize,
  kTransfer,
  kTransferList,
  makeTransferable,
} = require('internal/worker/js_transferable');
 
const {
  customInspect,
  dequeueValue,
  ensureIsPromise,
  enqueueValueWithSize,
  extractHighWaterMark,
  extractSizeAlgorithm,
  lazyTransfer,
  isBrandCheck,
  isPromisePending,
  peekQueueValue,
  resetQueue,
  setPromiseHandled,
  nonOpCancel,
  nonOpStart,
  nonOpWrite,
  kType,
  kState,
  kEnumerableProperty,
} = require('internal/webstreams/util');
 
const {
  AbortController,
} = require('internal/abort_controller');
 
const assert = require('internal/assert');
 
const kAbort = Symbol('kAbort');
const kCloseSentinel = Symbol('kCloseSentinel');
const kError = Symbol('kError');
 
/**
 * @typedef {import('../abort_controller').AbortSignal} AbortSignal
 * @typedef {import('./queuingstrategies').QueuingStrategy
 * } QueuingStrategy
 * @typedef {import('./queuingstrategies').QueuingStrategySize
 * } QueuingStrategySize
 *
 * @callback UnderlyingSinkStartCallback
 * @param {WritableStreamDefaultController} controller
 *
 * @callback UnderlyingSinkWriteCallback
 * @param {any} chunk
 * @param {WritableStreamDefaultController} controller
 * @returns {Promise<void>}
 *
 * @callback UnderlyingSinkCloseCallback
 * @returns {Promise<void>}
 *
 * @callback UnderlyingSinkAbortCallback
 * @param {any} reason
 * @returns {Promise<void>}
 *
 * @typedef {{
 *   start? : UnderlyingSinkStartCallback,
 *   write? : UnderlyingSinkWriteCallback,
 *   close? : UnderlyingSinkCloseCallback,
 *   abort? : UnderlyingSinkAbortCallback,
 *   type? : any,
 * }} UnderlyingSink
 */
 
class WritableStream {
  [kType] = 'WritableStream';
 
  get [SymbolToStringTag]() { return this[kType]; }
 
  /**
   * @param {UnderlyingSink} [sink]
   * @param {QueuingStrategy} [strategy]
   */
  constructor(sink = null, strategy = {}) {
    const type = sink?.type;
    if (type !== undefined)
      throw new ERR_INVALID_ARG_VALUE.RangeError('type', type);
 
    this[kState] = {
      close: createDeferredPromise(),
      closeRequest: {
        promise: undefined,
        resolve: undefined,
        reject: undefined,
      },
      inFlightWriteRequest: {
        promise: undefined,
        resolve: undefined,
        reject: undefined,
      },
      inFlightCloseRequest: {
        promise: undefined,
        resolve: undefined,
        reject: undefined,
      },
      pendingAbortRequest: {
        abort: {
          promise: undefined,
          resolve: undefined,
          reject: undefined,
        },
        reason: undefined,
        wasAlreadyErroring: false,
      },
      backpressure: false,
      controller: undefined,
      state: 'writable',
      storedError: undefined,
      writeRequests: [],
      writer: undefined,
      transfer: {
        readable: undefined,
        port1: undefined,
        port2: undefined,
        promise: undefined,
      }
    };
 
    const size = extractSizeAlgorithm(strategy?.size);
    const highWaterMark = extractHighWaterMark(strategy?.highWaterMark, 1);
 
    setupWritableStreamDefaultControllerFromSink(
      this,
      sink,
      highWaterMark,
      size);
 
    // eslint-disable-next-line no-constructor-return
    return makeTransferable(this);
  }
 
  /**
   * @readonly
   * @type {boolean}
   */
  get locked() {
    if (!isWritableStream(this))
      throw new ERR_INVALID_THIS('WritableStream');
    return isWritableStreamLocked(this);
  }
 
  /**
   * @param {any} reason
   * @returns {Promise<vois>}
   */
  abort(reason = undefined) {
    if (!isWritableStream(this))
      return PromiseReject(new ERR_INVALID_THIS('WritableStream'));
    if (isWritableStreamLocked(this)) {
      return PromiseReject(
        new ERR_INVALID_STATE.TypeError('WritableStream is locked'));
    }
    return writableStreamAbort(this, reason);
  }
 
  /**
   * @returns {Promise<void>}
   */
  close() {
    if (!isWritableStream(this))
      return PromiseReject(new ERR_INVALID_THIS('WritableStream'));
    if (isWritableStreamLocked(this)) {
      return PromiseReject(
        new ERR_INVALID_STATE.TypeError('WritableStream is locked'));
    }
    if (writableStreamCloseQueuedOrInFlight(this)) {
      return PromiseReject(
        new ERR_INVALID_STATE.TypeError('Failure closing WritableStream'));
    }
    return writableStreamClose(this);
  }
 
  /**
   * @returns {WritableStreamDefaultWriter}
   */
  getWriter() {
    if (!isWritableStream(this))
      throw new ERR_INVALID_THIS('WritableStream');
    return new WritableStreamDefaultWriter(this);
  }
 
  [kInspect](depth, options) {
    return customInspect(depth, options, this[kType], {
      locked: this.locked,
      state: this[kState].state,
    });
  }
 
  [kTransfer]() {
    if (!isWritableStream(this))
      throw new ERR_INVALID_THIS('WritableStream');
    if (this.locked) {
      this[kState].transfer.port1?.close();
      this[kState].transfer.port1 = undefined;
      this[kState].transfer.port2 = undefined;
      throw new DOMException(
        'Cannot transfer a locked WritableStream',
        'DataCloneError');
    }
 
    const {
      readable,
      promise,
    } = lazyTransfer().newCrossRealmReadableStream(
      this,
      this[kState].transfer.port1);
 
    this[kState].transfer.readable = readable;
    this[kState].transfer.promise = promise;
 
    setPromiseHandled(this[kState].transfer.promise);
 
    return {
      data: { port: this[kState].transfer.port2 },
      deserializeInfo:
        'internal/webstreams/writablestream:TransferredWritableStream'
    };
  }
 
  [kTransferList]() {
    const { port1, port2 } = new MessageChannel();
    this[kState].transfer.port1 = port1;
    this[kState].transfer.port2 = port2;
    return [ port2 ];
  }
 
  [kDeserialize]({ port }) {
    const transfer = lazyTransfer();
    setupWritableStreamDefaultControllerFromSink(
      this,
      new transfer.CrossRealmTransformWritableSink(port),
      1,
      () => 1);
  }
}
 
ObjectDefineProperties(WritableStream.prototype, {
  locked: kEnumerableProperty,
  abort: kEnumerableProperty,
  close: kEnumerableProperty,
  getWriter: kEnumerableProperty,
});
 
function TransferredWritableStream() {
  return makeTransferable(ReflectConstruct(
    function() {
      this[kType] = 'WritableStream';
      this[kState] = {
        close: createDeferredPromise(),
        closeRequest: {
          promise: undefined,
          resolve: undefined,
          reject: undefined,
        },
        inFlightWriteRequest: {
          promise: undefined,
          resolve: undefined,
          reject: undefined,
        },
        inFlightCloseRequest: {
          promise: undefined,
          resolve: undefined,
          reject: undefined,
        },
        pendingAbortRequest: {
          abort: {
            promise: undefined,
            resolve: undefined,
            reject: undefined,
          },
          reason: undefined,
          wasAlreadyErroring: false,
        },
        backpressure: false,
        controller: undefined,
        state: 'writable',
        storedError: undefined,
        writeRequests: [],
        writer: undefined,
        transfer: {
          promise: undefined,
          port1: undefined,
          port2: undefined,
          readable: undefined,
        },
      };
    },
    [], WritableStream));
}
TransferredWritableStream.prototype[kDeserialize] = () => {};
 
class WritableStreamDefaultWriter {
  [kType] = 'WritableStreamDefaultWriter';
 
  get [SymbolToStringTag]() { return this[kType]; }
 
  /**
   * @param {WritableStream} stream
   */
  constructor(stream) {
    if (!isWritableStream(stream))
      throw new ERR_INVALID_ARG_TYPE('stream', 'WritableStream', stream);
    this[kState] = {
      stream: undefined,
      close: {
        promise: undefined,
        resolve: undefined,
        reject: undefined,
      },
      ready: {
        promise: undefined,
        resolve: undefined,
        reject: undefined,
      }
    };
    setupWritableStreamDefaultWriter(this, stream);
  }
 
  /**
   * @readonly
   * @type {Promise<void>}
   */
  get closed() {
    if (!isWritableStreamDefaultWriter(this))
      return PromiseReject(new ERR_INVALID_THIS('WritableStreamDefaultWriter'));
    return this[kState].close.promise;
  }
 
  /**
   * @readonly
   * @type {number}
   */
  get desiredSize() {
    if (!isWritableStreamDefaultWriter(this))
      throw new ERR_INVALID_THIS('WritableStreamDefaultWriter');
    if (this[kState].stream === undefined) {
      throw new ERR_INVALID_STATE.TypeError(
        'Writer is not bound to a WritableStream');
    }
    return writableStreamDefaultWriterGetDesiredSize(this);
  }
 
  /**
   * @readonly
   * @type {Promise<void>}
   */
  get ready() {
    if (!isWritableStreamDefaultWriter(this))
      return PromiseReject(new ERR_INVALID_THIS('WritableStreamDefaultWriter'));
    return this[kState].ready.promise;
  }
 
  /**
   * @param {any} reason
   * @returns {Promise<void>}
   */
  abort(reason = undefined) {
    if (!isWritableStreamDefaultWriter(this))
      return PromiseReject(new ERR_INVALID_THIS('WritableStreamDefaultWriter'));
    if (this[kState].stream === undefined) {
      return PromiseReject(
        new ERR_INVALID_STATE.TypeError(
          'Writer is not bound to a WritableStream'));
    }
    return writableStreamDefaultWriterAbort(this, reason);
  }
 
  /**
   * @returns {Promise<void>}
   */
  close() {
    if (!isWritableStreamDefaultWriter(this))
      return PromiseReject(new ERR_INVALID_THIS('WritableStreamDefaultWriter'));
    const {
      stream,
    } = this[kState];
    if (stream === undefined) {
      return PromiseReject(
        new ERR_INVALID_STATE.TypeError(
          'Writer is not bound to a WritableStream'));
    }
    if (writableStreamCloseQueuedOrInFlight(stream)) {
      return PromiseReject(
        new ERR_INVALID_STATE.TypeError('Failure to close WritableStream'));
    }
    return writableStreamDefaultWriterClose(this);
  }
 
  releaseLock() {
    if (!isWritableStreamDefaultWriter(this))
      throw new ERR_INVALID_THIS('WritableStreamDefaultWriter');
    const {
      stream,
    } = this[kState];
    if (stream === undefined)
      return;
    assert(stream[kState].writer !== undefined);
    writableStreamDefaultWriterRelease(this);
  }
 
  /**
   * @param {any} chunk
   * @returns {Promise<void>}
   */
  write(chunk = undefined) {
    if (!isWritableStreamDefaultWriter(this))
      return PromiseReject(new ERR_INVALID_THIS('WritableStreamDefaultWriter'));
    if (this[kState].stream === undefined) {
      return PromiseReject(
        new ERR_INVALID_STATE.TypeError(
          'Writer is not bound to a WritableStream'));
    }
    return writableStreamDefaultWriterWrite(this, chunk);
  }
 
  [kInspect](depth, options) {
    return customInspect(depth, options, this[kType], {
      stream: this[kState].stream,
      close: this[kState].close.promise,
      ready: this[kState].ready.promise,
      desiredSize: this.desiredSize,
    });
  }
}
 
ObjectDefineProperties(WritableStreamDefaultWriter.prototype, {
  closed: kEnumerableProperty,
  ready: kEnumerableProperty,
  desiredSize: kEnumerableProperty,
  abort: kEnumerableProperty,
  close: kEnumerableProperty,
  releaseLock: kEnumerableProperty,
  write: kEnumerableProperty,
});
 
class WritableStreamDefaultController {
  [kType] = 'WritableStreamDefaultController';
 
  get [SymbolToStringTag]() { return this[kType]; }
 
  constructor() {
    throw new ERR_ILLEGAL_CONSTRUCTOR();
  }
 
  [kAbort](reason) {
    const result = this[kState].abortAlgorithm(reason);
    writableStreamDefaultControllerClearAlgorithms(this);
    return result;
  }
 
  [kError]() {
    resetQueue(this);
  }
 
  /**
   * @type {any}
   */
  get abortReason() {
    if (!isWritableStreamDefaultController(this))
      throw new ERR_INVALID_THIS('WritableStreamDefaultController');
    return this[kState].abortReason;
  }
 
  /**
   * @type {AbortSignal}
   */
  get signal() {
    if (!isWritableStreamDefaultController(this))
      throw new ERR_INVALID_THIS('WritableStreamDefaultController');
    return this[kState].abortController.signal;
  }
 
  /**
   * @param {any} error
   */
  error(error = undefined) {
    if (!isWritableStreamDefaultController(this))
      throw new ERR_INVALID_THIS('WritableStreamDefaultController');
    if (this[kState].stream[kState].state !== 'writable')
      return;
    writableStreamDefaultControllerError(this, error);
  }
 
  [kInspect](depth, options) {
    return customInspect(depth, options, this[kType], {
      stream: this[kState].stream,
    });
  }
}
 
ObjectDefineProperties(WritableStreamDefaultController.prototype, {
  abortReason: kEnumerableProperty,
  signal: kEnumerableProperty,
  error: kEnumerableProperty,
});
 
function createWritableStreamDefaultController() {
  return ReflectConstruct(
    function() {
      this[kType] = 'WritableStreamDefaultController';
    },
    [], WritableStreamDefaultController);
}
 
const isWritableStream =
  isBrandCheck('WritableStream');
const isWritableStreamDefaultWriter =
  isBrandCheck('WritableStreamDefaultWriter');
const isWritableStreamDefaultController =
  isBrandCheck('WritableStreamDefaultController');
 
function isWritableStreamLocked(stream) {
  return stream[kState].writer !== undefined;
}
 
function setupWritableStreamDefaultWriter(writer, stream) {
  if (isWritableStreamLocked(stream))
    throw new ERR_INVALID_STATE.TypeError('WritableStream is locked');
  writer[kState].stream = stream;
  stream[kState].writer = writer;
  switch (stream[kState].state) {
    case 'writable':
      if (!writableStreamCloseQueuedOrInFlight(stream) &&
          stream[kState].backpressure) {
        writer[kState].ready = createDeferredPromise();
      } else {
        writer[kState].ready = {
          promise: PromiseResolve(),
          resolve: undefined,
          reject: undefined,
        };
      }
      setClosedPromiseToNewPromise();
      break;
    case 'erroring':
      writer[kState].ready = {
        promise: PromiseReject(stream[kState].storedError),
        resolve: undefined,
        reject: undefined,
      };
      setPromiseHandled(writer[kState].ready.promise);
      setClosedPromiseToNewPromise();
      break;
    case 'closed':
      writer[kState].ready = {
        promise: PromiseResolve(),
        resolve: undefined,
        reject: undefined,
      };
      writer[kState].close = {
        promise: PromiseResolve(),
        resolve: undefined,
        reject: undefined,
      };
      break;
    default:
      writer[kState].ready = {
        promise: PromiseReject(stream[kState].storedError),
        resolve: undefined,
        reject: undefined,
      };
      writer[kState].close = {
        promise: PromiseReject(stream[kState].storedError),
        resolve: undefined,
        reject: undefined,
      };
      setPromiseHandled(writer[kState].ready.promise);
      setPromiseHandled(writer[kState].close.promise);
  }
 
  function setClosedPromiseToNewPromise() {
    writer[kState].close = createDeferredPromise();
  }
}
 
function writableStreamAbort(stream, reason) {
  const {
    state,
    controller,
  } = stream[kState];
  if (state === 'closed' || state === 'errored')
    return PromiseResolve();
 
  controller[kState].abortReason = reason;
  controller[kState].abortController.abort();
 
  if (stream[kState].pendingAbortRequest.abort.promise !== undefined)
    return stream[kState].pendingAbortRequest.abort.promise;
 
  assert(state === 'writable' || state === 'erroring');
 
  let wasAlreadyErroring = false;
  if (state === 'erroring') {
    wasAlreadyErroring = true;
    reason = undefined;
  }
 
  const abort = createDeferredPromise();
 
  stream[kState].pendingAbortRequest = {
    abort,
    reason,
    wasAlreadyErroring,
  };
 
  if (!wasAlreadyErroring)
    writableStreamStartErroring(stream, reason);
 
  return abort.promise;
}
 
function writableStreamClose(stream) {
  const {
    state,
    writer,
    backpressure,
    controller,
  } = stream[kState];
  if (state === 'closed' || state === 'errored') {
    return PromiseReject(
      new ERR_INVALID_STATE.TypeError('WritableStream is closed'));
  }
  assert(state === 'writable' || state === 'erroring');
  assert(!writableStreamCloseQueuedOrInFlight(stream));
  stream[kState].closeRequest = createDeferredPromise();
  const { promise } = stream[kState].closeRequest;
  if (writer !== undefined && backpressure && state === 'writable')
    writer[kState].ready.resolve?.();
  writableStreamDefaultControllerClose(controller);
  return promise;
}
 
function writableStreamUpdateBackpressure(stream, backpressure) {
  assert(stream[kState].state === 'writable');
  assert(!writableStreamCloseQueuedOrInFlight(stream));
  const {
    writer,
  } = stream[kState];
  if (writer !== undefined && stream[kState].backpressure !== backpressure) {
    if (backpressure) {
      writer[kState].ready = createDeferredPromise();
    } else {
      writer[kState].ready.resolve?.();
    }
  }
  stream[kState].backpressure = backpressure;
}
 
function writableStreamStartErroring(stream, reason) {
  assert(stream[kState].storedError === undefined);
  assert(stream[kState].state === 'writable');
  const {
    controller,
    writer,
  } = stream[kState];
  assert(controller !== undefined);
  stream[kState].state = 'erroring';
  stream[kState].storedError = reason;
  if (writer !== undefined) {
    writableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
  }
  if (!writableStreamHasOperationMarkedInFlight(stream) &&
      controller[kState].started) {
    writableStreamFinishErroring(stream);
  }
}
 
function writableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
  assert(stream[kState].state === 'errored');
  if (stream[kState].closeRequest.promise !== undefined) {
    assert(stream[kState].inFlightCloseRequest.promise === undefined);
    stream[kState].closeRequest.reject?.(stream[kState].storedError);
    stream[kState].closeRequest = {
      promise: undefined,
      reject: undefined,
      resolve: undefined,
    };
  }
  const {
    writer,
  } = stream[kState];
  if (writer !== undefined) {
    writer[kState].close.reject?.(stream[kState].storedError);
    setPromiseHandled(writer[kState].close.promise);
  }
}
 
function writableStreamMarkFirstWriteRequestInFlight(stream) {
  assert(stream[kState].inFlightWriteRequest.promise === undefined);
  assert(stream[kState].writeRequests.length);
  const writeRequest = ArrayPrototypeShift(stream[kState].writeRequests);
  stream[kState].inFlightWriteRequest = writeRequest;
}
 
function writableStreamMarkCloseRequestInFlight(stream) {
  assert(stream[kState].inFlightWriteRequest.promise === undefined);
  assert(stream[kState].closeRequest.promise !== undefined);
  stream[kState].inFlightCloseRequest = stream[kState].closeRequest;
  stream[kState].closeRequest = {
    promise: undefined,
    resolve: undefined,
    reject: undefined,
  };
}
 
function writableStreamHasOperationMarkedInFlight(stream) {
  const {
    inFlightWriteRequest,
    inFlightCloseRequest,
  } = stream[kState];
  if (inFlightWriteRequest.promise === undefined &&
      inFlightCloseRequest.promise === undefined) {
    return false;
  }
  return true;
}
 
function writableStreamFinishInFlightWriteWithError(stream, error) {
  assert(stream[kState].inFlightWriteRequest.promise !== undefined);
  stream[kState].inFlightWriteRequest.reject?.(error);
  stream[kState].inFlightWriteRequest = {
    promise: undefined,
    resolve: undefined,
    reject: undefined,
  };
  assert(stream[kState].state === 'writable' ||
         stream[kState].state === 'erroring');
  writableStreamDealWithRejection(stream, error);
}
 
function writableStreamFinishInFlightWrite(stream) {
  assert(stream[kState].inFlightWriteRequest.promise !== undefined);
  stream[kState].inFlightWriteRequest.resolve?.();
  stream[kState].inFlightWriteRequest = {
    promise: undefined,
    resolve: undefined,
    reject: undefined,
  };
}
 
function writableStreamFinishInFlightCloseWithError(stream, error) {
  assert(stream[kState].inFlightCloseRequest.promise !== undefined);
  stream[kState].inFlightCloseRequest.reject?.(error);
  stream[kState].inFlightCloseRequest = {
    promise: undefined,
    resolve: undefined,
    reject: undefined,
  };
  assert(stream[kState].state === 'writable' ||
         stream[kState].state === 'erroring');
  if (stream[kState].pendingAbortRequest.abort.promise !== undefined) {
    stream[kState].pendingAbortRequest.abort.reject?.(error);
    stream[kState].pendingAbortRequest = {
      abort: {
        promise: undefined,
        resolve: undefined,
        reject: undefined,
      },
      reason: undefined,
      wasAlreadyErroring: false,
    };
  }
  writableStreamDealWithRejection(stream, error);
}
 
function writableStreamFinishInFlightClose(stream) {
  assert(stream[kState].inFlightCloseRequest.promise !== undefined);
  stream[kState].inFlightCloseRequest.resolve?.();
  stream[kState].inFlightCloseRequest = {
    promise: undefined,
    resolve: undefined,
    reject: undefined,
  };
  if (stream[kState].state === 'erroring') {
    stream[kState].storedError = undefined;
    if (stream[kState].pendingAbortRequest.abort.promise !== undefined) {
      stream[kState].pendingAbortRequest.abort.resolve?.();
      stream[kState].pendingAbortRequest = {
        abort: {
          promise: undefined,
          resolve: undefined,
          reject: undefined,
        },
        reason: undefined,
        wasAlreadyErroring: false,
      };
    }
  }
  stream[kState].state = 'closed';
  if (stream[kState].writer !== undefined)
    stream[kState].writer[kState].close.resolve?.();
  assert(stream[kState].pendingAbortRequest.abort.promise === undefined);
  assert(stream[kState].storedError === undefined);
}
 
function writableStreamFinishErroring(stream) {
  assert(stream[kState].state === 'erroring');
  assert(!writableStreamHasOperationMarkedInFlight(stream));
  stream[kState].state = 'errored';
  stream[kState].controller[kError]();
  const storedError = stream[kState].storedError;
  for (let n = 0; n < stream[kState].writeRequests.length; n++)
    stream[kState].writeRequests[n].reject?.(storedError);
  stream[kState].writeRequests = [];
 
  if (stream[kState].pendingAbortRequest.abort.promise === undefined) {
    writableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
    return;
  }
 
  const abortRequest = stream[kState].pendingAbortRequest;
  stream[kState].pendingAbortRequest = {
    abort: {
      promise: undefined,
      resolve: undefined,
      reject: undefined,
    },
    reason: undefined,
    wasAlreadyErroring: false,
  };
  if (abortRequest.wasAlreadyErroring) {
    abortRequest.abort.reject?.(storedError);
    writableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
    return;
  }
  PromisePrototypeThen(
    ensureIsPromise(
      stream[kState].controller[kAbort],
      stream[kState].controller,
      abortRequest.reason),
    () => {
      abortRequest.abort.resolve?.();
      writableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
    },
    (error) => {
      abortRequest.abort.reject?.(error);
      writableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
    });
}
 
function writableStreamDealWithRejection(stream, error) {
  const {
    state,
  } = stream[kState];
  if (state === 'writable') {
    writableStreamStartErroring(stream, error);
    return;
  }
 
  assert(state === 'erroring');
  writableStreamFinishErroring(stream);
}
 
function writableStreamCloseQueuedOrInFlight(stream) {
  if (stream[kState].closeRequest.promise === undefined &&
      stream[kState].inFlightCloseRequest.promise === undefined) {
    return false;
  }
  return true;
}
 
function writableStreamAddWriteRequest(stream) {
  assert(isWritableStreamLocked(stream));
  assert(stream[kState].state === 'writable');
  const {
    promise,
    resolve,
    reject,
  } = createDeferredPromise();
  ArrayPrototypePush(
    stream[kState].writeRequests,
    {
      promise,
      resolve,
      reject,
    });
  return promise;
}
 
function writableStreamDefaultWriterWrite(writer, chunk) {
  const {
    stream,
  } = writer[kState];
  assert(stream !== undefined);
  const {
    controller,
  } = stream[kState];
  const chunkSize = writableStreamDefaultControllerGetChunkSize(
    controller,
    chunk);
  if (stream !== writer[kState].stream) {
    return PromiseReject(
      new ERR_INVALID_STATE.TypeError('Mismatched WritableStreams'));
  }
  const {
    state,
  } = stream[kState];
 
  if (state === 'errored')
    return PromiseReject(stream[kState].storedError);
 
  if (writableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
    return PromiseReject(
      new ERR_INVALID_STATE.TypeError('WritableStream is closed'));
  }
 
  if (state === 'erroring')
    return PromiseReject(stream[kState].storedError);
 
  assert(state === 'writable');
 
  const promise = writableStreamAddWriteRequest(stream);
  writableStreamDefaultControllerWrite(controller, chunk, chunkSize);
  return promise;
}
 
function writableStreamDefaultWriterRelease(writer) {
  const {
    stream,
  } = writer[kState];
  assert(stream !== undefined);
  assert(stream[kState].writer === writer);
  const releasedError =
    new ERR_INVALID_STATE.TypeError('Writer has been released');
  writableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
  writableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
  stream[kState].writer = undefined;
  writer[kState].stream = undefined;
}
 
function writableStreamDefaultWriterGetDesiredSize(writer) {
  const {
    stream,
  } = writer[kState];
  switch (stream[kState].state) {
    case 'errored':
      // Fall through
    case 'erroring':
      return null;
    case 'closed':
      return 0;
  }
  return writableStreamDefaultControllerGetDesiredSize(
    stream[kState].controller);
}
 
function writableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
  if (isPromisePending(writer[kState].ready.promise)) {
    writer[kState].ready.reject?.(error);
  } else {
    writer[kState].ready = {
      promise: PromiseReject(error),
      resolve: undefined,
      reject: undefined,
    };
  }
  setPromiseHandled(writer[kState].ready.promise);
}
 
function writableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
  if (isPromisePending(writer[kState].close.promise)) {
    writer[kState].close.reject?.(error);
  } else {
    writer[kState].close = {
      promise: PromiseReject(error),
      resolve: undefined,
      reject: undefined,
    };
  }
  setPromiseHandled(writer[kState].close.promise);
}
 
function writableStreamDefaultWriterCloseWithErrorPropagation(writer) {
  const {
    stream,
  } = writer[kState];
  assert(stream !== undefined);
  const {
    state,
  } = stream[kState];
  if (writableStreamCloseQueuedOrInFlight(stream) || state === 'closed')
    return PromiseResolve();
 
  if (state === 'errored')
    return PromiseReject(stream[kState].storedError);
 
  assert(state === 'writable' || state === 'erroring');
 
  return writableStreamDefaultWriterClose(writer);
}
 
function writableStreamDefaultWriterClose(writer) {
  const {
    stream,
  } = writer[kState];
  assert(stream !== undefined);
  return writableStreamClose(stream);
}
 
function writableStreamDefaultWriterAbort(writer, reason) {
  const {
    stream,
  } = writer[kState];
  assert(stream !== undefined);
  return writableStreamAbort(stream, reason);
}
 
function writableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
  try {
    enqueueValueWithSize(controller, chunk, chunkSize);
  } catch (error) {
    writableStreamDefaultControllerErrorIfNeeded(controller, error);
    return;
  }
  const {
    stream,
  } = controller[kState];
  if (!writableStreamCloseQueuedOrInFlight(stream) &&
      stream[kState].state === 'writable') {
    writableStreamUpdateBackpressure(
      stream,
      writableStreamDefaultControllerGetBackpressure(controller));
  }
  writableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
}
 
function writableStreamDefaultControllerProcessWrite(controller, chunk) {
  const {
    stream,
    writeAlgorithm,
  } = controller[kState];
  writableStreamMarkFirstWriteRequestInFlight(stream);
 
  PromisePrototypeThen(
    ensureIsPromise(writeAlgorithm, controller, chunk, controller),
    () => {
      writableStreamFinishInFlightWrite(stream);
      const {
        state,
      } = stream[kState];
      assert(state === 'writable' || state === 'erroring');
      dequeueValue(controller);
      if (!writableStreamCloseQueuedOrInFlight(stream) &&
          state === 'writable') {
        writableStreamUpdateBackpressure(
          stream,
          writableStreamDefaultControllerGetBackpressure(controller));
      }
      writableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
    },
    (error) => {
      if (stream[kState].state === 'writable')
        writableStreamDefaultControllerClearAlgorithms(controller);
      writableStreamFinishInFlightWriteWithError(stream, error);
    });
 
}
 
function writableStreamDefaultControllerProcessClose(controller) {
  const {
    closeAlgorithm,
    queue,
    stream,
  } = controller[kState];
  writableStreamMarkCloseRequestInFlight(stream);
  dequeueValue(controller);
  assert(!queue.length);
  const sinkClosePromise = ensureIsPromise(closeAlgorithm, controller);
  writableStreamDefaultControllerClearAlgorithms(controller);
  PromisePrototypeThen(
    sinkClosePromise,
    () => writableStreamFinishInFlightClose(stream),
    (error) => writableStreamFinishInFlightCloseWithError(stream, error));
}
 
function writableStreamDefaultControllerGetDesiredSize(controller) {
  const {
    highWaterMark,
    queueTotalSize,
  } = controller[kState];
  return highWaterMark - queueTotalSize;
}
 
function writableStreamDefaultControllerGetChunkSize(controller, chunk) {
  try {
    return FunctionPrototypeCall(
      controller[kState].sizeAlgorithm,
      undefined,
      chunk);
  } catch (error) {
    writableStreamDefaultControllerErrorIfNeeded(controller, error);
    return 1;
  }
}
 
function writableStreamDefaultControllerErrorIfNeeded(controller, error) {
  const {
    stream,
  } = controller[kState];
  if (stream[kState].state === 'writable')
    writableStreamDefaultControllerError(controller, error);
}
 
function writableStreamDefaultControllerError(controller, error) {
  const {
    stream,
  } = controller[kState];
  assert(stream[kState].state === 'writable');
  writableStreamDefaultControllerClearAlgorithms(controller);
  writableStreamStartErroring(stream, error);
}
 
function writableStreamDefaultControllerClose(controller) {
  enqueueValueWithSize(controller, kCloseSentinel, 0);
  writableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
}
 
function writableStreamDefaultControllerClearAlgorithms(controller) {
  controller[kState].writeAlgorithm = undefined;
  controller[kState].closeAlgorithm = undefined;
  controller[kState].abortAlgorithm = undefined;
  controller[kState].sizeAlgorithm = undefined;
}
 
function writableStreamDefaultControllerGetBackpressure(controller) {
  return writableStreamDefaultControllerGetDesiredSize(controller) <= 0;
}
 
function writableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
  const {
    queue,
    started,
    stream,
  } = controller[kState];
  if (!started || stream[kState].inFlightWriteRequest.promise !== undefined)
    return;
 
  if (stream[kState].state === 'erroring') {
    writableStreamFinishErroring(stream);
    return;
  }
 
  if (!queue.length)
    return;
 
  const value = peekQueueValue(controller);
  if (value === kCloseSentinel)
    writableStreamDefaultControllerProcessClose(controller);
  else
    writableStreamDefaultControllerProcessWrite(controller, value);
}
 
function setupWritableStreamDefaultControllerFromSink(
  stream,
  sink,
  highWaterMark,
  sizeAlgorithm) {
  const controller = createWritableStreamDefaultController();
  const start = sink?.start;
  const write = sink?.write;
  const close = sink?.close;
  const abort = sink?.abort;
  const startAlgorithm = start ?
    FunctionPrototypeBind(start, sink, controller) :
    nonOpStart;
  const writeAlgorithm = write ?
    FunctionPrototypeBind(write, sink) :
    nonOpWrite;
  const closeAlgorithm = close ?
    FunctionPrototypeBind(close, sink) : nonOpCancel;
  const abortAlgorithm = abort ?
    FunctionPrototypeBind(abort, sink) : nonOpCancel;
  setupWritableStreamDefaultController(
    stream,
    controller,
    startAlgorithm,
    writeAlgorithm,
    closeAlgorithm,
    abortAlgorithm,
    highWaterMark,
    sizeAlgorithm);
}
 
function setupWritableStreamDefaultController(
  stream,
  controller,
  startAlgorithm,
  writeAlgorithm,
  closeAlgorithm,
  abortAlgorithm,
  highWaterMark,
  sizeAlgorithm) {
  assert(isWritableStream(stream));
  assert(stream[kState].controller === undefined);
  controller[kState] = {
    abortAlgorithm,
    abortReason: undefined,
    closeAlgorithm,
    highWaterMark,
    queue: [],
    queueTotalSize: 0,
    abortController: new AbortController(),
    sizeAlgorithm,
    started: false,
    stream,
    writeAlgorithm,
  };
  stream[kState].controller = controller;
 
  writableStreamUpdateBackpressure(
    stream,
    writableStreamDefaultControllerGetBackpressure(controller));
 
  const startResult = startAlgorithm();
 
  PromisePrototypeThen(
    PromiseResolve(startResult),
    () => {
      assert(stream[kState].state === 'writable' ||
             stream[kState].state === 'erroring');
      controller[kState].started = true;
      writableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
    },
    (error) => {
      assert(stream[kState].state === 'writable' ||
             stream[kState].state === 'erroring');
      controller[kState].started = true;
      writableStreamDealWithRejection(stream, error);
    });
}
 
module.exports = {
  WritableStream,
  WritableStreamDefaultWriter,
  WritableStreamDefaultController,
  TransferredWritableStream,
 
  // Exported Brand Checks
  isWritableStream,
  isWritableStreamDefaultController,
  isWritableStreamDefaultWriter,
 
  isWritableStreamLocked,
  setupWritableStreamDefaultWriter,
  writableStreamAbort,
  writableStreamClose,
  writableStreamUpdateBackpressure,
  writableStreamStartErroring,
  writableStreamRejectCloseAndClosedPromiseIfNeeded,
  writableStreamMarkFirstWriteRequestInFlight,
  writableStreamMarkCloseRequestInFlight,
  writableStreamHasOperationMarkedInFlight,
  writableStreamFinishInFlightWriteWithError,
  writableStreamFinishInFlightWrite,
  writableStreamFinishInFlightCloseWithError,
  writableStreamFinishInFlightClose,
  writableStreamFinishErroring,
  writableStreamDealWithRejection,
  writableStreamCloseQueuedOrInFlight,
  writableStreamAddWriteRequest,
  writableStreamDefaultWriterWrite,
  writableStreamDefaultWriterRelease,
  writableStreamDefaultWriterGetDesiredSize,
  writableStreamDefaultWriterEnsureReadyPromiseRejected,
  writableStreamDefaultWriterEnsureClosedPromiseRejected,
  writableStreamDefaultWriterCloseWithErrorPropagation,
  writableStreamDefaultWriterClose,
  writableStreamDefaultWriterAbort,
  writableStreamDefaultControllerWrite,
  writableStreamDefaultControllerProcessWrite,
  writableStreamDefaultControllerProcessClose,
  writableStreamDefaultControllerGetDesiredSize,
  writableStreamDefaultControllerGetChunkSize,
  writableStreamDefaultControllerErrorIfNeeded,
  writableStreamDefaultControllerError,
  writableStreamDefaultControllerClose,
  writableStreamDefaultControllerClearAlgorithms,
  writableStreamDefaultControllerGetBackpressure,
  writableStreamDefaultControllerAdvanceQueueIfNeeded,
  setupWritableStreamDefaultControllerFromSink,
  setupWritableStreamDefaultController,
};
 
/* eslint-enable no-use-before-define */