web-streams-polyfill 3.2.1 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +11 -14
  3. package/dist/polyfill.es2018.js +723 -197
  4. package/dist/polyfill.es2018.js.map +1 -1
  5. package/dist/polyfill.es2018.min.js +8 -1
  6. package/dist/polyfill.es2018.min.js.map +1 -1
  7. package/dist/polyfill.es2018.mjs +721 -193
  8. package/dist/polyfill.es2018.mjs.map +1 -1
  9. package/dist/polyfill.es6.js +789 -197
  10. package/dist/polyfill.es6.js.map +1 -1
  11. package/dist/polyfill.es6.min.js +8 -1
  12. package/dist/polyfill.es6.min.js.map +1 -1
  13. package/dist/polyfill.es6.mjs +787 -193
  14. package/dist/polyfill.es6.mjs.map +1 -1
  15. package/dist/polyfill.js +873 -243
  16. package/dist/polyfill.js.map +1 -1
  17. package/dist/polyfill.min.js +8 -1
  18. package/dist/polyfill.min.js.map +1 -1
  19. package/dist/polyfill.mjs +871 -239
  20. package/dist/polyfill.mjs.map +1 -1
  21. package/dist/ponyfill.es2018.js +723 -197
  22. package/dist/ponyfill.es2018.js.map +1 -1
  23. package/dist/ponyfill.es2018.mjs +721 -193
  24. package/dist/ponyfill.es2018.mjs.map +1 -1
  25. package/dist/ponyfill.es6.js +789 -197
  26. package/dist/ponyfill.es6.js.map +1 -1
  27. package/dist/ponyfill.es6.mjs +787 -193
  28. package/dist/ponyfill.es6.mjs.map +1 -1
  29. package/dist/ponyfill.js +873 -243
  30. package/dist/ponyfill.js.map +1 -1
  31. package/dist/ponyfill.mjs +871 -239
  32. package/dist/ponyfill.mjs.map +1 -1
  33. package/dist/types/{polyfill.d.ts → ponyfill.d.ts} +780 -771
  34. package/dist/types/ts3.6/{polyfill.d.ts → ponyfill.d.ts} +57 -7
  35. package/dist/types/tsdoc-metadata.json +1 -1
  36. package/es2018/package.json +8 -1
  37. package/es6/package.json +8 -1
  38. package/package.json +28 -21
  39. package/ponyfill/es2018/package.json +8 -1
  40. package/ponyfill/es6/package.json +8 -1
  41. package/ponyfill/package.json +8 -1
@@ -1,44 +1,48 @@
1
1
  /**
2
- * web-streams-polyfill v3.2.1
2
+ * @license
3
+ * web-streams-polyfill v3.3.1
4
+ * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors.
5
+ * This code is released under the MIT license.
6
+ * SPDX-License-Identifier: MIT
3
7
  */
4
8
  /// <reference lib="es2015.symbol" />
5
9
  const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
6
10
  Symbol :
7
11
  description => `Symbol(${description})`;
8
12
 
9
- /// <reference lib="dom" />
10
13
  function noop() {
11
14
  return undefined;
12
15
  }
13
- function getGlobals() {
14
- if (typeof self !== 'undefined') {
15
- return self;
16
- }
17
- else if (typeof window !== 'undefined') {
18
- return window;
19
- }
20
- else if (typeof global !== 'undefined') {
21
- return global;
22
- }
23
- return undefined;
24
- }
25
- const globals = getGlobals();
26
16
 
27
17
  function typeIsObject(x) {
28
18
  return (typeof x === 'object' && x !== null) || typeof x === 'function';
29
19
  }
30
20
  const rethrowAssertionErrorRejection = noop;
21
+ function setFunctionName(fn, name) {
22
+ try {
23
+ Object.defineProperty(fn, 'name', {
24
+ value: name,
25
+ configurable: true
26
+ });
27
+ }
28
+ catch (_a) {
29
+ // This property is non-configurable in older browsers, so ignore if this throws.
30
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
31
+ }
32
+ }
31
33
 
32
34
  const originalPromise = Promise;
33
35
  const originalPromiseThen = Promise.prototype.then;
34
- const originalPromiseResolve = Promise.resolve.bind(originalPromise);
35
36
  const originalPromiseReject = Promise.reject.bind(originalPromise);
37
+ // https://webidl.spec.whatwg.org/#a-new-promise
36
38
  function newPromise(executor) {
37
39
  return new originalPromise(executor);
38
40
  }
41
+ // https://webidl.spec.whatwg.org/#a-promise-resolved-with
39
42
  function promiseResolvedWith(value) {
40
- return originalPromiseResolve(value);
43
+ return newPromise(resolve => resolve(value));
41
44
  }
45
+ // https://webidl.spec.whatwg.org/#a-promise-rejected-with
42
46
  function promiseRejectedWith(reason) {
43
47
  return originalPromiseReject(reason);
44
48
  }
@@ -47,6 +51,9 @@ function PerformPromiseThen(promise, onFulfilled, onRejected) {
47
51
  // approximation.
48
52
  return originalPromiseThen.call(promise, onFulfilled, onRejected);
49
53
  }
54
+ // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned
55
+ // from that handler. To prevent this, return null instead of void from all handlers.
56
+ // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it
50
57
  function uponPromise(promise, onFulfilled, onRejected) {
51
58
  PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
52
59
  }
@@ -62,14 +69,16 @@ function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
62
69
  function setPromiseIsHandledToTrue(promise) {
63
70
  PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
64
71
  }
65
- const queueMicrotask = (() => {
66
- const globalQueueMicrotask = globals && globals.queueMicrotask;
67
- if (typeof globalQueueMicrotask === 'function') {
68
- return globalQueueMicrotask;
72
+ let _queueMicrotask = callback => {
73
+ if (typeof queueMicrotask === 'function') {
74
+ _queueMicrotask = queueMicrotask;
69
75
  }
70
- const resolvedPromise = promiseResolvedWith(undefined);
71
- return (fn) => PerformPromiseThen(resolvedPromise, fn);
72
- })();
76
+ else {
77
+ const resolvedPromise = promiseResolvedWith(undefined);
78
+ _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);
79
+ }
80
+ return _queueMicrotask(callback);
81
+ };
73
82
  function reflectCall(F, V, args) {
74
83
  if (typeof F !== 'function') {
75
84
  throw new TypeError('Argument is not a function');
@@ -193,6 +202,12 @@ class SimpleQueue {
193
202
  }
194
203
  }
195
204
 
205
+ const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
206
+ const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
207
+ const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
208
+ const PullSteps = SymbolPolyfill('[[PullSteps]]');
209
+ const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]');
210
+
196
211
  function ReadableStreamReaderGenericInitialize(reader, stream) {
197
212
  reader._ownerReadableStream = stream;
198
213
  stream._reader = reader;
@@ -213,13 +228,15 @@ function ReadableStreamReaderGenericCancel(reader, reason) {
213
228
  return ReadableStreamCancel(stream, reason);
214
229
  }
215
230
  function ReadableStreamReaderGenericRelease(reader) {
216
- if (reader._ownerReadableStream._state === 'readable') {
231
+ const stream = reader._ownerReadableStream;
232
+ if (stream._state === 'readable') {
217
233
  defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
218
234
  }
219
235
  else {
220
236
  defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
221
237
  }
222
- reader._ownerReadableStream._reader = undefined;
238
+ stream._readableStreamController[ReleaseSteps]();
239
+ stream._reader = undefined;
223
240
  reader._ownerReadableStream = undefined;
224
241
  }
225
242
  // Helper functions for the readers.
@@ -262,11 +279,6 @@ function defaultReaderClosedPromiseResolve(reader) {
262
279
  reader._closedPromise_reject = undefined;
263
280
  }
264
281
 
265
- const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
266
- const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
267
- const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
268
- const PullSteps = SymbolPolyfill('[[PullSteps]]');
269
-
270
282
  /// <reference lib="es2015.core" />
271
283
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
272
284
  const NumberIsFinite = Number.isFinite || function (x) {
@@ -462,10 +474,7 @@ class ReadableStreamDefaultReader {
462
474
  if (this._ownerReadableStream === undefined) {
463
475
  return;
464
476
  }
465
- if (this._readRequests.length > 0) {
466
- throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
467
- }
468
- ReadableStreamReaderGenericRelease(this);
477
+ ReadableStreamDefaultReaderRelease(this);
469
478
  }
470
479
  }
471
480
  Object.defineProperties(ReadableStreamDefaultReader.prototype, {
@@ -474,6 +483,9 @@ Object.defineProperties(ReadableStreamDefaultReader.prototype, {
474
483
  releaseLock: { enumerable: true },
475
484
  closed: { enumerable: true }
476
485
  });
486
+ setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');
487
+ setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');
488
+ setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');
477
489
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
478
490
  Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
479
491
  value: 'ReadableStreamDefaultReader',
@@ -503,6 +515,18 @@ function ReadableStreamDefaultReaderRead(reader, readRequest) {
503
515
  stream._readableStreamController[PullSteps](readRequest);
504
516
  }
505
517
  }
518
+ function ReadableStreamDefaultReaderRelease(reader) {
519
+ ReadableStreamReaderGenericRelease(reader);
520
+ const e = new TypeError('Reader was released');
521
+ ReadableStreamDefaultReaderErrorReadRequests(reader, e);
522
+ }
523
+ function ReadableStreamDefaultReaderErrorReadRequests(reader, e) {
524
+ const readRequests = reader._readRequests;
525
+ reader._readRequests = new SimpleQueue();
526
+ readRequests.forEach(readRequest => {
527
+ readRequest._errorSteps(e);
528
+ });
529
+ }
506
530
  // Helper functions for the ReadableStreamDefaultReader.
507
531
  function defaultReaderBrandCheckException(name) {
508
532
  return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
@@ -538,9 +562,6 @@ class ReadableStreamAsyncIteratorImpl {
538
562
  return Promise.resolve({ value: undefined, done: true });
539
563
  }
540
564
  const reader = this._reader;
541
- if (reader._ownerReadableStream === undefined) {
542
- return promiseRejectedWith(readerLockException('iterate'));
543
- }
544
565
  let resolvePromise;
545
566
  let rejectPromise;
546
567
  const promise = newPromise((resolve, reject) => {
@@ -552,7 +573,7 @@ class ReadableStreamAsyncIteratorImpl {
552
573
  this._ongoingPromise = undefined;
553
574
  // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
554
575
  // FIXME Is this a bug in the specification, or in the test?
555
- queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
576
+ _queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
556
577
  },
557
578
  _closeSteps: () => {
558
579
  this._ongoingPromise = undefined;
@@ -576,9 +597,6 @@ class ReadableStreamAsyncIteratorImpl {
576
597
  }
577
598
  this._isFinished = true;
578
599
  const reader = this._reader;
579
- if (reader._ownerReadableStream === undefined) {
580
- return promiseRejectedWith(readerLockException('finish iterating'));
581
- }
582
600
  if (!this._preventCancel) {
583
601
  const result = ReadableStreamReaderGenericCancel(reader, value);
584
602
  ReadableStreamReaderGenericRelease(reader);
@@ -649,15 +667,29 @@ function CreateArrayFromList(elements) {
649
667
  function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
650
668
  new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
651
669
  }
652
- // Not implemented correctly
653
- function TransferArrayBuffer(O) {
654
- return O;
655
- }
656
- // Not implemented correctly
657
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
658
- function IsDetachedBuffer(O) {
659
- return false;
660
- }
670
+ let TransferArrayBuffer = (O) => {
671
+ if (typeof O.transfer === 'function') {
672
+ TransferArrayBuffer = buffer => buffer.transfer();
673
+ }
674
+ else if (typeof structuredClone === 'function') {
675
+ TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });
676
+ }
677
+ else {
678
+ // Not implemented correctly
679
+ TransferArrayBuffer = buffer => buffer;
680
+ }
681
+ return TransferArrayBuffer(O);
682
+ };
683
+ let IsDetachedBuffer = (O) => {
684
+ if (typeof O.detached === 'boolean') {
685
+ IsDetachedBuffer = buffer => buffer.detached;
686
+ }
687
+ else {
688
+ // Not implemented correctly
689
+ IsDetachedBuffer = buffer => buffer.byteLength === 0;
690
+ }
691
+ return IsDetachedBuffer(O);
692
+ };
661
693
  function ArrayBufferSlice(buffer, begin, end) {
662
694
  // ArrayBuffer.prototype.slice is not available on IE10
663
695
  // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice
@@ -669,6 +701,68 @@ function ArrayBufferSlice(buffer, begin, end) {
669
701
  CopyDataBlockBytes(slice, 0, buffer, begin, length);
670
702
  return slice;
671
703
  }
704
+ function GetMethod(receiver, prop) {
705
+ const func = receiver[prop];
706
+ if (func === undefined || func === null) {
707
+ return undefined;
708
+ }
709
+ if (typeof func !== 'function') {
710
+ throw new TypeError(`${String(prop)} is not a function`);
711
+ }
712
+ return func;
713
+ }
714
+ function CreateAsyncFromSyncIterator(syncIteratorRecord) {
715
+ // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,
716
+ // we use yield* inside an async generator function to achieve the same result.
717
+ // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.
718
+ const syncIterable = {
719
+ [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator
720
+ };
721
+ // Create an async generator function and immediately invoke it.
722
+ const asyncIterator = (async function* () {
723
+ return yield* syncIterable;
724
+ }());
725
+ // Return as an async iterator record.
726
+ const nextMethod = asyncIterator.next;
727
+ return { iterator: asyncIterator, nextMethod, done: false };
728
+ }
729
+ function GetIterator(obj, hint = 'sync', method) {
730
+ if (method === undefined) {
731
+ if (hint === 'async') {
732
+ method = GetMethod(obj, SymbolPolyfill.asyncIterator);
733
+ if (method === undefined) {
734
+ const syncMethod = GetMethod(obj, SymbolPolyfill.iterator);
735
+ const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod);
736
+ return CreateAsyncFromSyncIterator(syncIteratorRecord);
737
+ }
738
+ }
739
+ else {
740
+ method = GetMethod(obj, SymbolPolyfill.iterator);
741
+ }
742
+ }
743
+ if (method === undefined) {
744
+ throw new TypeError('The object is not iterable');
745
+ }
746
+ const iterator = reflectCall(method, obj, []);
747
+ if (!typeIsObject(iterator)) {
748
+ throw new TypeError('The iterator method must return an object');
749
+ }
750
+ const nextMethod = iterator.next;
751
+ return { iterator, nextMethod, done: false };
752
+ }
753
+ function IteratorNext(iteratorRecord) {
754
+ const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);
755
+ if (!typeIsObject(result)) {
756
+ throw new TypeError('The iterator.next() method must return an object');
757
+ }
758
+ return result;
759
+ }
760
+ function IteratorComplete(iterResult) {
761
+ return Boolean(iterResult.done);
762
+ }
763
+ function IteratorValue(iterResult) {
764
+ return iterResult.value;
765
+ }
672
766
 
673
767
  function IsNonNegativeNumber(v) {
674
768
  if (typeof v !== 'number') {
@@ -711,6 +805,19 @@ function ResetQueue(container) {
711
805
  container._queueTotalSize = 0;
712
806
  }
713
807
 
808
+ function isDataViewConstructor(ctor) {
809
+ return ctor === DataView;
810
+ }
811
+ function isDataView(view) {
812
+ return isDataViewConstructor(view.constructor);
813
+ }
814
+ function arrayBufferViewElementSize(ctor) {
815
+ if (isDataViewConstructor(ctor)) {
816
+ return 1;
817
+ }
818
+ return ctor.BYTES_PER_ELEMENT;
819
+ }
820
+
714
821
  /**
715
822
  * A pull-into request in a {@link ReadableByteStreamController}.
716
823
  *
@@ -738,7 +845,9 @@ class ReadableStreamBYOBRequest {
738
845
  if (this._associatedReadableByteStreamController === undefined) {
739
846
  throw new TypeError('This BYOB request has been invalidated');
740
847
  }
741
- if (IsDetachedBuffer(this._view.buffer)) ;
848
+ if (IsDetachedBuffer(this._view.buffer)) {
849
+ throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);
850
+ }
742
851
  ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
743
852
  }
744
853
  respondWithNewView(view) {
@@ -752,7 +861,9 @@ class ReadableStreamBYOBRequest {
752
861
  if (this._associatedReadableByteStreamController === undefined) {
753
862
  throw new TypeError('This BYOB request has been invalidated');
754
863
  }
755
- if (IsDetachedBuffer(view.buffer)) ;
864
+ if (IsDetachedBuffer(view.buffer)) {
865
+ throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response');
866
+ }
756
867
  ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
757
868
  }
758
869
  }
@@ -761,6 +872,8 @@ Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
761
872
  respondWithNewView: { enumerable: true },
762
873
  view: { enumerable: true }
763
874
  });
875
+ setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');
876
+ setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');
764
877
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
765
878
  Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
766
879
  value: 'ReadableStreamBYOBRequest',
@@ -856,11 +969,7 @@ class ReadableByteStreamController {
856
969
  [PullSteps](readRequest) {
857
970
  const stream = this._controlledReadableByteStream;
858
971
  if (this._queueTotalSize > 0) {
859
- const entry = this._queue.shift();
860
- this._queueTotalSize -= entry.byteLength;
861
- ReadableByteStreamControllerHandleQueueDrain(this);
862
- const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
863
- readRequest._chunkSteps(view);
972
+ ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);
864
973
  return;
865
974
  }
866
975
  const autoAllocateChunkSize = this._autoAllocateChunkSize;
@@ -879,6 +988,7 @@ class ReadableByteStreamController {
879
988
  byteOffset: 0,
880
989
  byteLength: autoAllocateChunkSize,
881
990
  bytesFilled: 0,
991
+ minimumFill: 1,
882
992
  elementSize: 1,
883
993
  viewConstructor: Uint8Array,
884
994
  readerType: 'default'
@@ -888,6 +998,15 @@ class ReadableByteStreamController {
888
998
  ReadableStreamAddReadRequest(stream, readRequest);
889
999
  ReadableByteStreamControllerCallPullIfNeeded(this);
890
1000
  }
1001
+ /** @internal */
1002
+ [ReleaseSteps]() {
1003
+ if (this._pendingPullIntos.length > 0) {
1004
+ const firstPullInto = this._pendingPullIntos.peek();
1005
+ firstPullInto.readerType = 'none';
1006
+ this._pendingPullIntos = new SimpleQueue();
1007
+ this._pendingPullIntos.push(firstPullInto);
1008
+ }
1009
+ }
891
1010
  }
892
1011
  Object.defineProperties(ReadableByteStreamController.prototype, {
893
1012
  close: { enumerable: true },
@@ -896,6 +1015,9 @@ Object.defineProperties(ReadableByteStreamController.prototype, {
896
1015
  byobRequest: { enumerable: true },
897
1016
  desiredSize: { enumerable: true }
898
1017
  });
1018
+ setFunctionName(ReadableByteStreamController.prototype.close, 'close');
1019
+ setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');
1020
+ setFunctionName(ReadableByteStreamController.prototype.error, 'error');
899
1021
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
900
1022
  Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
901
1023
  value: 'ReadableByteStreamController',
@@ -939,8 +1061,10 @@ function ReadableByteStreamControllerCallPullIfNeeded(controller) {
939
1061
  controller._pullAgain = false;
940
1062
  ReadableByteStreamControllerCallPullIfNeeded(controller);
941
1063
  }
1064
+ return null;
942
1065
  }, e => {
943
1066
  ReadableByteStreamControllerError(controller, e);
1067
+ return null;
944
1068
  });
945
1069
  }
946
1070
  function ReadableByteStreamControllerClearPendingPullIntos(controller) {
@@ -969,15 +1093,33 @@ function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byt
969
1093
  controller._queue.push({ buffer, byteOffset, byteLength });
970
1094
  controller._queueTotalSize += byteLength;
971
1095
  }
1096
+ function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) {
1097
+ let clonedChunk;
1098
+ try {
1099
+ clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);
1100
+ }
1101
+ catch (cloneE) {
1102
+ ReadableByteStreamControllerError(controller, cloneE);
1103
+ throw cloneE;
1104
+ }
1105
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);
1106
+ }
1107
+ function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) {
1108
+ if (firstDescriptor.bytesFilled > 0) {
1109
+ ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled);
1110
+ }
1111
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
1112
+ }
972
1113
  function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
973
- const elementSize = pullIntoDescriptor.elementSize;
974
- const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
975
1114
  const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
976
1115
  const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
977
- const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
978
1116
  let totalBytesToCopyRemaining = maxBytesToCopy;
979
1117
  let ready = false;
980
- if (maxAlignedBytes > currentAlignedBytes) {
1118
+ const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;
1119
+ const maxAlignedBytes = maxBytesFilled - remainderBytes;
1120
+ // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1121
+ // of the queue, so the underlying source can keep filling it.
1122
+ if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {
981
1123
  totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
982
1124
  ready = true;
983
1125
  }
@@ -1032,25 +1174,37 @@ function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(contro
1032
1174
  }
1033
1175
  }
1034
1176
  }
1035
- function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
1036
- const stream = controller._controlledReadableByteStream;
1037
- let elementSize = 1;
1038
- if (view.constructor !== DataView) {
1039
- elementSize = view.constructor.BYTES_PER_ELEMENT;
1177
+ function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) {
1178
+ const reader = controller._controlledReadableByteStream._reader;
1179
+ while (reader._readRequests.length > 0) {
1180
+ if (controller._queueTotalSize === 0) {
1181
+ return;
1182
+ }
1183
+ const readRequest = reader._readRequests.shift();
1184
+ ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);
1040
1185
  }
1186
+ }
1187
+ function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) {
1188
+ const stream = controller._controlledReadableByteStream;
1041
1189
  const ctor = view.constructor;
1042
- // try {
1043
- const buffer = TransferArrayBuffer(view.buffer);
1044
- // } catch (e) {
1045
- // readIntoRequest._errorSteps(e);
1046
- // return;
1047
- // }
1190
+ const elementSize = arrayBufferViewElementSize(ctor);
1191
+ const { byteOffset, byteLength } = view;
1192
+ const minimumFill = min * elementSize;
1193
+ let buffer;
1194
+ try {
1195
+ buffer = TransferArrayBuffer(view.buffer);
1196
+ }
1197
+ catch (e) {
1198
+ readIntoRequest._errorSteps(e);
1199
+ return;
1200
+ }
1048
1201
  const pullIntoDescriptor = {
1049
1202
  buffer,
1050
1203
  bufferByteLength: buffer.byteLength,
1051
- byteOffset: view.byteOffset,
1052
- byteLength: view.byteLength,
1204
+ byteOffset,
1205
+ byteLength,
1053
1206
  bytesFilled: 0,
1207
+ minimumFill,
1054
1208
  elementSize,
1055
1209
  viewConstructor: ctor,
1056
1210
  readerType: 'byob'
@@ -1087,6 +1241,9 @@ function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest)
1087
1241
  ReadableByteStreamControllerCallPullIfNeeded(controller);
1088
1242
  }
1089
1243
  function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
1244
+ if (firstDescriptor.readerType === 'none') {
1245
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
1246
+ }
1090
1247
  const stream = controller._controlledReadableByteStream;
1091
1248
  if (ReadableStreamHasBYOBReader(stream)) {
1092
1249
  while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
@@ -1097,15 +1254,21 @@ function ReadableByteStreamControllerRespondInClosedState(controller, firstDescr
1097
1254
  }
1098
1255
  function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
1099
1256
  ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
1100
- if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
1257
+ if (pullIntoDescriptor.readerType === 'none') {
1258
+ ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);
1259
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1260
+ return;
1261
+ }
1262
+ if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {
1263
+ // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1264
+ // of the queue, so the underlying source can keep filling it.
1101
1265
  return;
1102
1266
  }
1103
1267
  ReadableByteStreamControllerShiftPendingPullInto(controller);
1104
1268
  const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
1105
1269
  if (remainderSize > 0) {
1106
1270
  const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
1107
- const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);
1108
- ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
1271
+ ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize);
1109
1272
  }
1110
1273
  pullIntoDescriptor.bytesFilled -= remainderSize;
1111
1274
  ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
@@ -1116,7 +1279,7 @@ function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
1116
1279
  ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1117
1280
  const state = controller._controlledReadableByteStream._state;
1118
1281
  if (state === 'closed') {
1119
- ReadableByteStreamControllerRespondInClosedState(controller);
1282
+ ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
1120
1283
  }
1121
1284
  else {
1122
1285
  ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
@@ -1166,7 +1329,7 @@ function ReadableByteStreamControllerClose(controller) {
1166
1329
  }
1167
1330
  if (controller._pendingPullIntos.length > 0) {
1168
1331
  const firstPendingPullInto = controller._pendingPullIntos.peek();
1169
- if (firstPendingPullInto.bytesFilled > 0) {
1332
+ if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {
1170
1333
  const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
1171
1334
  ReadableByteStreamControllerError(controller, e);
1172
1335
  throw e;
@@ -1180,17 +1343,24 @@ function ReadableByteStreamControllerEnqueue(controller, chunk) {
1180
1343
  if (controller._closeRequested || stream._state !== 'readable') {
1181
1344
  return;
1182
1345
  }
1183
- const buffer = chunk.buffer;
1184
- const byteOffset = chunk.byteOffset;
1185
- const byteLength = chunk.byteLength;
1346
+ const { buffer, byteOffset, byteLength } = chunk;
1347
+ if (IsDetachedBuffer(buffer)) {
1348
+ throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued');
1349
+ }
1186
1350
  const transferredBuffer = TransferArrayBuffer(buffer);
1187
1351
  if (controller._pendingPullIntos.length > 0) {
1188
1352
  const firstPendingPullInto = controller._pendingPullIntos.peek();
1189
- if (IsDetachedBuffer(firstPendingPullInto.buffer)) ;
1353
+ if (IsDetachedBuffer(firstPendingPullInto.buffer)) {
1354
+ throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk');
1355
+ }
1356
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1190
1357
  firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
1358
+ if (firstPendingPullInto.readerType === 'none') {
1359
+ ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);
1360
+ }
1191
1361
  }
1192
- ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1193
1362
  if (ReadableStreamHasDefaultReader(stream)) {
1363
+ ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
1194
1364
  if (ReadableStreamGetNumReadRequests(stream) === 0) {
1195
1365
  ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1196
1366
  }
@@ -1222,6 +1392,13 @@ function ReadableByteStreamControllerError(controller, e) {
1222
1392
  ReadableByteStreamControllerClearAlgorithms(controller);
1223
1393
  ReadableStreamError(stream, e);
1224
1394
  }
1395
+ function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
1396
+ const entry = controller._queue.shift();
1397
+ controller._queueTotalSize -= entry.byteLength;
1398
+ ReadableByteStreamControllerHandleQueueDrain(controller);
1399
+ const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
1400
+ readRequest._chunkSteps(view);
1401
+ }
1225
1402
  function ReadableByteStreamControllerGetBYOBRequest(controller) {
1226
1403
  if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
1227
1404
  const firstDescriptor = controller._pendingPullIntos.peek();
@@ -1307,24 +1484,35 @@ function SetUpReadableByteStreamController(stream, controller, startAlgorithm, p
1307
1484
  uponPromise(promiseResolvedWith(startResult), () => {
1308
1485
  controller._started = true;
1309
1486
  ReadableByteStreamControllerCallPullIfNeeded(controller);
1487
+ return null;
1310
1488
  }, r => {
1311
1489
  ReadableByteStreamControllerError(controller, r);
1490
+ return null;
1312
1491
  });
1313
1492
  }
1314
1493
  function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
1315
1494
  const controller = Object.create(ReadableByteStreamController.prototype);
1316
- let startAlgorithm = () => undefined;
1317
- let pullAlgorithm = () => promiseResolvedWith(undefined);
1318
- let cancelAlgorithm = () => promiseResolvedWith(undefined);
1495
+ let startAlgorithm;
1496
+ let pullAlgorithm;
1497
+ let cancelAlgorithm;
1319
1498
  if (underlyingByteSource.start !== undefined) {
1320
1499
  startAlgorithm = () => underlyingByteSource.start(controller);
1321
1500
  }
1501
+ else {
1502
+ startAlgorithm = () => undefined;
1503
+ }
1322
1504
  if (underlyingByteSource.pull !== undefined) {
1323
1505
  pullAlgorithm = () => underlyingByteSource.pull(controller);
1324
1506
  }
1507
+ else {
1508
+ pullAlgorithm = () => promiseResolvedWith(undefined);
1509
+ }
1325
1510
  if (underlyingByteSource.cancel !== undefined) {
1326
1511
  cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
1327
1512
  }
1513
+ else {
1514
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
1515
+ }
1328
1516
  const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
1329
1517
  if (autoAllocateChunkSize === 0) {
1330
1518
  throw new TypeError('autoAllocateChunkSize must be greater than 0');
@@ -1344,6 +1532,29 @@ function byteStreamControllerBrandCheckException(name) {
1344
1532
  return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
1345
1533
  }
1346
1534
 
1535
+ function convertReaderOptions(options, context) {
1536
+ assertDictionary(options, context);
1537
+ const mode = options === null || options === void 0 ? void 0 : options.mode;
1538
+ return {
1539
+ mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
1540
+ };
1541
+ }
1542
+ function convertReadableStreamReaderMode(mode, context) {
1543
+ mode = `${mode}`;
1544
+ if (mode !== 'byob') {
1545
+ throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
1546
+ }
1547
+ return mode;
1548
+ }
1549
+ function convertByobReadOptions(options, context) {
1550
+ var _a;
1551
+ assertDictionary(options, context);
1552
+ const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1;
1553
+ return {
1554
+ min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`)
1555
+ };
1556
+ }
1557
+
1347
1558
  // Abstract operations for the ReadableStream.
1348
1559
  function AcquireReadableStreamBYOBReader(stream) {
1349
1560
  return new ReadableStreamBYOBReader(stream);
@@ -1416,12 +1627,7 @@ class ReadableStreamBYOBReader {
1416
1627
  }
1417
1628
  return ReadableStreamReaderGenericCancel(this, reason);
1418
1629
  }
1419
- /**
1420
- * Attempts to reads bytes into view, and returns a promise resolved with the result.
1421
- *
1422
- * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
1423
- */
1424
- read(view) {
1630
+ read(view, rawOptions = {}) {
1425
1631
  if (!IsReadableStreamBYOBReader(this)) {
1426
1632
  return promiseRejectedWith(byobReaderBrandCheckException('read'));
1427
1633
  }
@@ -1434,7 +1640,28 @@ class ReadableStreamBYOBReader {
1434
1640
  if (view.buffer.byteLength === 0) {
1435
1641
  return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
1436
1642
  }
1437
- if (IsDetachedBuffer(view.buffer)) ;
1643
+ if (IsDetachedBuffer(view.buffer)) {
1644
+ return promiseRejectedWith(new TypeError('view\'s buffer has been detached'));
1645
+ }
1646
+ let options;
1647
+ try {
1648
+ options = convertByobReadOptions(rawOptions, 'options');
1649
+ }
1650
+ catch (e) {
1651
+ return promiseRejectedWith(e);
1652
+ }
1653
+ const min = options.min;
1654
+ if (min === 0) {
1655
+ return promiseRejectedWith(new TypeError('options.min must be greater than 0'));
1656
+ }
1657
+ if (!isDataView(view)) {
1658
+ if (min > view.length) {
1659
+ return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length'));
1660
+ }
1661
+ }
1662
+ else if (min > view.byteLength) {
1663
+ return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength'));
1664
+ }
1438
1665
  if (this._ownerReadableStream === undefined) {
1439
1666
  return promiseRejectedWith(readerLockException('read from'));
1440
1667
  }
@@ -1449,7 +1676,7 @@ class ReadableStreamBYOBReader {
1449
1676
  _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
1450
1677
  _errorSteps: e => rejectPromise(e)
1451
1678
  };
1452
- ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
1679
+ ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);
1453
1680
  return promise;
1454
1681
  }
1455
1682
  /**
@@ -1468,10 +1695,7 @@ class ReadableStreamBYOBReader {
1468
1695
  if (this._ownerReadableStream === undefined) {
1469
1696
  return;
1470
1697
  }
1471
- if (this._readIntoRequests.length > 0) {
1472
- throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
1473
- }
1474
- ReadableStreamReaderGenericRelease(this);
1698
+ ReadableStreamBYOBReaderRelease(this);
1475
1699
  }
1476
1700
  }
1477
1701
  Object.defineProperties(ReadableStreamBYOBReader.prototype, {
@@ -1480,6 +1704,9 @@ Object.defineProperties(ReadableStreamBYOBReader.prototype, {
1480
1704
  releaseLock: { enumerable: true },
1481
1705
  closed: { enumerable: true }
1482
1706
  });
1707
+ setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');
1708
+ setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');
1709
+ setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');
1483
1710
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1484
1711
  Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
1485
1712
  value: 'ReadableStreamBYOBReader',
@@ -1496,16 +1723,28 @@ function IsReadableStreamBYOBReader(x) {
1496
1723
  }
1497
1724
  return x instanceof ReadableStreamBYOBReader;
1498
1725
  }
1499
- function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
1726
+ function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) {
1500
1727
  const stream = reader._ownerReadableStream;
1501
1728
  stream._disturbed = true;
1502
1729
  if (stream._state === 'errored') {
1503
1730
  readIntoRequest._errorSteps(stream._storedError);
1504
1731
  }
1505
1732
  else {
1506
- ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
1733
+ ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest);
1507
1734
  }
1508
1735
  }
1736
+ function ReadableStreamBYOBReaderRelease(reader) {
1737
+ ReadableStreamReaderGenericRelease(reader);
1738
+ const e = new TypeError('Reader was released');
1739
+ ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
1740
+ }
1741
+ function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) {
1742
+ const readIntoRequests = reader._readIntoRequests;
1743
+ reader._readIntoRequests = new SimpleQueue();
1744
+ readIntoRequests.forEach(readIntoRequest => {
1745
+ readIntoRequest._errorSteps(e);
1746
+ });
1747
+ }
1509
1748
  // Helper functions for the ReadableStreamBYOBReader.
1510
1749
  function byobReaderBrandCheckException(name) {
1511
1750
  return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
@@ -1706,6 +1945,9 @@ Object.defineProperties(WritableStream.prototype, {
1706
1945
  getWriter: { enumerable: true },
1707
1946
  locked: { enumerable: true }
1708
1947
  });
1948
+ setFunctionName(WritableStream.prototype.abort, 'abort');
1949
+ setFunctionName(WritableStream.prototype.close, 'close');
1950
+ setFunctionName(WritableStream.prototype.getWriter, 'getWriter');
1709
1951
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1710
1952
  Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
1711
1953
  value: 'WritableStream',
@@ -1771,7 +2013,7 @@ function WritableStreamAbort(stream, reason) {
1771
2013
  return promiseResolvedWith(undefined);
1772
2014
  }
1773
2015
  stream._writableStreamController._abortReason = reason;
1774
- (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort();
2016
+ (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason);
1775
2017
  // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',
1776
2018
  // but it doesn't know that signaling abort runs author code that might have changed the state.
1777
2019
  // Widen the type again by casting to WritableStreamState.
@@ -1876,9 +2118,11 @@ function WritableStreamFinishErroring(stream) {
1876
2118
  uponPromise(promise, () => {
1877
2119
  abortRequest._resolve();
1878
2120
  WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2121
+ return null;
1879
2122
  }, (reason) => {
1880
2123
  abortRequest._reject(reason);
1881
2124
  WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2125
+ return null;
1882
2126
  });
1883
2127
  }
1884
2128
  function WritableStreamFinishInFlightWrite(stream) {
@@ -2106,6 +2350,10 @@ Object.defineProperties(WritableStreamDefaultWriter.prototype, {
2106
2350
  desiredSize: { enumerable: true },
2107
2351
  ready: { enumerable: true }
2108
2352
  });
2353
+ setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');
2354
+ setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');
2355
+ setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');
2356
+ setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');
2109
2357
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2110
2358
  Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
2111
2359
  value: 'WritableStreamDefaultWriter',
@@ -2311,29 +2559,43 @@ function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm
2311
2559
  uponPromise(startPromise, () => {
2312
2560
  controller._started = true;
2313
2561
  WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2562
+ return null;
2314
2563
  }, r => {
2315
2564
  controller._started = true;
2316
2565
  WritableStreamDealWithRejection(stream, r);
2566
+ return null;
2317
2567
  });
2318
2568
  }
2319
2569
  function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
2320
2570
  const controller = Object.create(WritableStreamDefaultController.prototype);
2321
- let startAlgorithm = () => undefined;
2322
- let writeAlgorithm = () => promiseResolvedWith(undefined);
2323
- let closeAlgorithm = () => promiseResolvedWith(undefined);
2324
- let abortAlgorithm = () => promiseResolvedWith(undefined);
2571
+ let startAlgorithm;
2572
+ let writeAlgorithm;
2573
+ let closeAlgorithm;
2574
+ let abortAlgorithm;
2325
2575
  if (underlyingSink.start !== undefined) {
2326
2576
  startAlgorithm = () => underlyingSink.start(controller);
2327
2577
  }
2578
+ else {
2579
+ startAlgorithm = () => undefined;
2580
+ }
2328
2581
  if (underlyingSink.write !== undefined) {
2329
2582
  writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
2330
2583
  }
2584
+ else {
2585
+ writeAlgorithm = () => promiseResolvedWith(undefined);
2586
+ }
2331
2587
  if (underlyingSink.close !== undefined) {
2332
2588
  closeAlgorithm = () => underlyingSink.close();
2333
2589
  }
2590
+ else {
2591
+ closeAlgorithm = () => promiseResolvedWith(undefined);
2592
+ }
2334
2593
  if (underlyingSink.abort !== undefined) {
2335
2594
  abortAlgorithm = reason => underlyingSink.abort(reason);
2336
2595
  }
2596
+ else {
2597
+ abortAlgorithm = () => promiseResolvedWith(undefined);
2598
+ }
2337
2599
  SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
2338
2600
  }
2339
2601
  // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
@@ -2412,8 +2674,10 @@ function WritableStreamDefaultControllerProcessClose(controller) {
2412
2674
  WritableStreamDefaultControllerClearAlgorithms(controller);
2413
2675
  uponPromise(sinkClosePromise, () => {
2414
2676
  WritableStreamFinishInFlightClose(stream);
2677
+ return null;
2415
2678
  }, reason => {
2416
2679
  WritableStreamFinishInFlightCloseWithError(stream, reason);
2680
+ return null;
2417
2681
  });
2418
2682
  }
2419
2683
  function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
@@ -2429,11 +2693,13 @@ function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
2429
2693
  WritableStreamUpdateBackpressure(stream, backpressure);
2430
2694
  }
2431
2695
  WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2696
+ return null;
2432
2697
  }, reason => {
2433
2698
  if (stream._state === 'writable') {
2434
2699
  WritableStreamDefaultControllerClearAlgorithms(controller);
2435
2700
  }
2436
2701
  WritableStreamFinishInFlightWriteWithError(stream, reason);
2702
+ return null;
2437
2703
  });
2438
2704
  }
2439
2705
  function WritableStreamDefaultControllerGetBackpressure(controller) {
@@ -2540,13 +2806,28 @@ function defaultWriterReadyPromiseResolve(writer) {
2540
2806
  }
2541
2807
 
2542
2808
  /// <reference lib="dom" />
2543
- const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
2809
+ function getGlobals() {
2810
+ if (typeof globalThis !== 'undefined') {
2811
+ return globalThis;
2812
+ }
2813
+ else if (typeof self !== 'undefined') {
2814
+ return self;
2815
+ }
2816
+ else if (typeof global !== 'undefined') {
2817
+ return global;
2818
+ }
2819
+ return undefined;
2820
+ }
2821
+ const globals = getGlobals();
2544
2822
 
2545
2823
  /// <reference types="node" />
2546
2824
  function isDOMExceptionConstructor(ctor) {
2547
2825
  if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
2548
2826
  return false;
2549
2827
  }
2828
+ if (ctor.name !== 'DOMException') {
2829
+ return false;
2830
+ }
2550
2831
  try {
2551
2832
  new ctor();
2552
2833
  return true;
@@ -2555,8 +2836,21 @@ function isDOMExceptionConstructor(ctor) {
2555
2836
  return false;
2556
2837
  }
2557
2838
  }
2558
- function createDOMExceptionPolyfill() {
2559
- // eslint-disable-next-line no-shadow
2839
+ /**
2840
+ * Support:
2841
+ * - Web browsers
2842
+ * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)
2843
+ */
2844
+ function getFromGlobal() {
2845
+ const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException;
2846
+ return isDOMExceptionConstructor(ctor) ? ctor : undefined;
2847
+ }
2848
+ /**
2849
+ * Support:
2850
+ * - All platforms
2851
+ */
2852
+ function createPolyfill() {
2853
+ // eslint-disable-next-line @typescript-eslint/no-shadow
2560
2854
  const ctor = function DOMException(message, name) {
2561
2855
  this.message = message || '';
2562
2856
  this.name = name || 'Error';
@@ -2564,12 +2858,13 @@ function createDOMExceptionPolyfill() {
2564
2858
  Error.captureStackTrace(this, this.constructor);
2565
2859
  }
2566
2860
  };
2861
+ setFunctionName(ctor, 'DOMException');
2567
2862
  ctor.prototype = Object.create(Error.prototype);
2568
2863
  Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
2569
2864
  return ctor;
2570
2865
  }
2571
- // eslint-disable-next-line no-redeclare
2572
- const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
2866
+ // eslint-disable-next-line @typescript-eslint/no-redeclare
2867
+ const DOMException = getFromGlobal() || createPolyfill();
2573
2868
 
2574
2869
  function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
2575
2870
  const reader = AcquireReadableStreamDefaultReader(source);
@@ -2582,7 +2877,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2582
2877
  let abortAlgorithm;
2583
2878
  if (signal !== undefined) {
2584
2879
  abortAlgorithm = () => {
2585
- const error = new DOMException$1('Aborted', 'AbortError');
2880
+ const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');
2586
2881
  const actions = [];
2587
2882
  if (!preventAbort) {
2588
2883
  actions.push(() => {
@@ -2651,6 +2946,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2651
2946
  else {
2652
2947
  shutdown(true, storedError);
2653
2948
  }
2949
+ return null;
2654
2950
  });
2655
2951
  // Errors must be propagated backward
2656
2952
  isOrBecomesErrored(dest, writer._closedPromise, storedError => {
@@ -2660,6 +2956,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2660
2956
  else {
2661
2957
  shutdown(true, storedError);
2662
2958
  }
2959
+ return null;
2663
2960
  });
2664
2961
  // Closing must be propagated forward
2665
2962
  isOrBecomesClosed(source, reader._closedPromise, () => {
@@ -2669,6 +2966,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2669
2966
  else {
2670
2967
  shutdown();
2671
2968
  }
2969
+ return null;
2672
2970
  });
2673
2971
  // Closing must be propagated backward
2674
2972
  if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
@@ -2716,6 +3014,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2716
3014
  }
2717
3015
  function doTheRest() {
2718
3016
  uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
3017
+ return null;
2719
3018
  }
2720
3019
  }
2721
3020
  function shutdown(isError, error) {
@@ -2742,6 +3041,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2742
3041
  else {
2743
3042
  resolve(undefined);
2744
3043
  }
3044
+ return null;
2745
3045
  }
2746
3046
  });
2747
3047
  }
@@ -2822,6 +3122,10 @@ class ReadableStreamDefaultController {
2822
3122
  ReadableStreamDefaultControllerCallPullIfNeeded(this);
2823
3123
  }
2824
3124
  }
3125
+ /** @internal */
3126
+ [ReleaseSteps]() {
3127
+ // Do nothing.
3128
+ }
2825
3129
  }
2826
3130
  Object.defineProperties(ReadableStreamDefaultController.prototype, {
2827
3131
  close: { enumerable: true },
@@ -2829,6 +3133,9 @@ Object.defineProperties(ReadableStreamDefaultController.prototype, {
2829
3133
  error: { enumerable: true },
2830
3134
  desiredSize: { enumerable: true }
2831
3135
  });
3136
+ setFunctionName(ReadableStreamDefaultController.prototype.close, 'close');
3137
+ setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');
3138
+ setFunctionName(ReadableStreamDefaultController.prototype.error, 'error');
2832
3139
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2833
3140
  Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
2834
3141
  value: 'ReadableStreamDefaultController',
@@ -2862,8 +3169,10 @@ function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
2862
3169
  controller._pullAgain = false;
2863
3170
  ReadableStreamDefaultControllerCallPullIfNeeded(controller);
2864
3171
  }
3172
+ return null;
2865
3173
  }, e => {
2866
3174
  ReadableStreamDefaultControllerError(controller, e);
3175
+ return null;
2867
3176
  });
2868
3177
  }
2869
3178
  function ReadableStreamDefaultControllerShouldCallPull(controller) {
@@ -2978,24 +3287,35 @@ function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm
2978
3287
  uponPromise(promiseResolvedWith(startResult), () => {
2979
3288
  controller._started = true;
2980
3289
  ReadableStreamDefaultControllerCallPullIfNeeded(controller);
3290
+ return null;
2981
3291
  }, r => {
2982
3292
  ReadableStreamDefaultControllerError(controller, r);
3293
+ return null;
2983
3294
  });
2984
3295
  }
2985
3296
  function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
2986
3297
  const controller = Object.create(ReadableStreamDefaultController.prototype);
2987
- let startAlgorithm = () => undefined;
2988
- let pullAlgorithm = () => promiseResolvedWith(undefined);
2989
- let cancelAlgorithm = () => promiseResolvedWith(undefined);
3298
+ let startAlgorithm;
3299
+ let pullAlgorithm;
3300
+ let cancelAlgorithm;
2990
3301
  if (underlyingSource.start !== undefined) {
2991
3302
  startAlgorithm = () => underlyingSource.start(controller);
2992
3303
  }
3304
+ else {
3305
+ startAlgorithm = () => undefined;
3306
+ }
2993
3307
  if (underlyingSource.pull !== undefined) {
2994
3308
  pullAlgorithm = () => underlyingSource.pull(controller);
2995
3309
  }
3310
+ else {
3311
+ pullAlgorithm = () => promiseResolvedWith(undefined);
3312
+ }
2996
3313
  if (underlyingSource.cancel !== undefined) {
2997
3314
  cancelAlgorithm = reason => underlyingSource.cancel(reason);
2998
3315
  }
3316
+ else {
3317
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
3318
+ }
2999
3319
  SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
3000
3320
  }
3001
3321
  // Helper functions for the ReadableStreamDefaultController.
@@ -3034,7 +3354,7 @@ function ReadableStreamDefaultTee(stream, cloneForBranch2) {
3034
3354
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3035
3355
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3036
3356
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3037
- queueMicrotask(() => {
3357
+ _queueMicrotask(() => {
3038
3358
  readAgain = false;
3039
3359
  const chunk1 = chunk;
3040
3360
  const chunk2 = chunk;
@@ -3105,6 +3425,7 @@ function ReadableStreamDefaultTee(stream, cloneForBranch2) {
3105
3425
  if (!canceled1 || !canceled2) {
3106
3426
  resolveCancelPromise(undefined);
3107
3427
  }
3428
+ return null;
3108
3429
  });
3109
3430
  return [branch1, branch2];
3110
3431
  }
@@ -3126,13 +3447,14 @@ function ReadableByteStreamTee(stream) {
3126
3447
  function forwardReaderError(thisReader) {
3127
3448
  uponRejection(thisReader._closedPromise, r => {
3128
3449
  if (thisReader !== reader) {
3129
- return;
3450
+ return null;
3130
3451
  }
3131
3452
  ReadableByteStreamControllerError(branch1._readableStreamController, r);
3132
3453
  ReadableByteStreamControllerError(branch2._readableStreamController, r);
3133
3454
  if (!canceled1 || !canceled2) {
3134
3455
  resolveCancelPromise(undefined);
3135
3456
  }
3457
+ return null;
3136
3458
  });
3137
3459
  }
3138
3460
  function pullWithDefaultReader() {
@@ -3146,7 +3468,7 @@ function ReadableByteStreamTee(stream) {
3146
3468
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3147
3469
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3148
3470
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3149
- queueMicrotask(() => {
3471
+ _queueMicrotask(() => {
3150
3472
  readAgainForBranch1 = false;
3151
3473
  readAgainForBranch2 = false;
3152
3474
  const chunk1 = chunk;
@@ -3214,7 +3536,7 @@ function ReadableByteStreamTee(stream) {
3214
3536
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3215
3537
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3216
3538
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3217
- queueMicrotask(() => {
3539
+ _queueMicrotask(() => {
3218
3540
  readAgainForBranch1 = false;
3219
3541
  readAgainForBranch2 = false;
3220
3542
  const byobCanceled = forBranch2 ? canceled2 : canceled1;
@@ -3273,7 +3595,7 @@ function ReadableByteStreamTee(stream) {
3273
3595
  reading = false;
3274
3596
  }
3275
3597
  };
3276
- ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);
3598
+ ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);
3277
3599
  }
3278
3600
  function pull1Algorithm() {
3279
3601
  if (reading) {
@@ -3334,6 +3656,109 @@ function ReadableByteStreamTee(stream) {
3334
3656
  return [branch1, branch2];
3335
3657
  }
3336
3658
 
3659
+ function isReadableStreamLike(stream) {
3660
+ return typeIsObject(stream) && typeof stream.getReader !== 'undefined';
3661
+ }
3662
+
3663
+ function ReadableStreamFrom(source) {
3664
+ if (isReadableStreamLike(source)) {
3665
+ return ReadableStreamFromDefaultReader(source.getReader());
3666
+ }
3667
+ return ReadableStreamFromIterable(source);
3668
+ }
3669
+ function ReadableStreamFromIterable(asyncIterable) {
3670
+ let stream;
3671
+ const iteratorRecord = GetIterator(asyncIterable, 'async');
3672
+ const startAlgorithm = noop;
3673
+ function pullAlgorithm() {
3674
+ let nextResult;
3675
+ try {
3676
+ nextResult = IteratorNext(iteratorRecord);
3677
+ }
3678
+ catch (e) {
3679
+ return promiseRejectedWith(e);
3680
+ }
3681
+ const nextPromise = promiseResolvedWith(nextResult);
3682
+ return transformPromiseWith(nextPromise, iterResult => {
3683
+ if (!typeIsObject(iterResult)) {
3684
+ throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');
3685
+ }
3686
+ const done = IteratorComplete(iterResult);
3687
+ if (done) {
3688
+ ReadableStreamDefaultControllerClose(stream._readableStreamController);
3689
+ }
3690
+ else {
3691
+ const value = IteratorValue(iterResult);
3692
+ ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3693
+ }
3694
+ });
3695
+ }
3696
+ function cancelAlgorithm(reason) {
3697
+ const iterator = iteratorRecord.iterator;
3698
+ let returnMethod;
3699
+ try {
3700
+ returnMethod = GetMethod(iterator, 'return');
3701
+ }
3702
+ catch (e) {
3703
+ return promiseRejectedWith(e);
3704
+ }
3705
+ if (returnMethod === undefined) {
3706
+ return promiseResolvedWith(undefined);
3707
+ }
3708
+ let returnResult;
3709
+ try {
3710
+ returnResult = reflectCall(returnMethod, iterator, [reason]);
3711
+ }
3712
+ catch (e) {
3713
+ return promiseRejectedWith(e);
3714
+ }
3715
+ const returnPromise = promiseResolvedWith(returnResult);
3716
+ return transformPromiseWith(returnPromise, iterResult => {
3717
+ if (!typeIsObject(iterResult)) {
3718
+ throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');
3719
+ }
3720
+ return undefined;
3721
+ });
3722
+ }
3723
+ stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3724
+ return stream;
3725
+ }
3726
+ function ReadableStreamFromDefaultReader(reader) {
3727
+ let stream;
3728
+ const startAlgorithm = noop;
3729
+ function pullAlgorithm() {
3730
+ let readPromise;
3731
+ try {
3732
+ readPromise = reader.read();
3733
+ }
3734
+ catch (e) {
3735
+ return promiseRejectedWith(e);
3736
+ }
3737
+ return transformPromiseWith(readPromise, readResult => {
3738
+ if (!typeIsObject(readResult)) {
3739
+ throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');
3740
+ }
3741
+ if (readResult.done) {
3742
+ ReadableStreamDefaultControllerClose(stream._readableStreamController);
3743
+ }
3744
+ else {
3745
+ const value = readResult.value;
3746
+ ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3747
+ }
3748
+ });
3749
+ }
3750
+ function cancelAlgorithm(reason) {
3751
+ try {
3752
+ return promiseResolvedWith(reader.cancel(reason));
3753
+ }
3754
+ catch (e) {
3755
+ return promiseRejectedWith(e);
3756
+ }
3757
+ }
3758
+ stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3759
+ return stream;
3760
+ }
3761
+
3337
3762
  function convertUnderlyingDefaultOrByteSource(source, context) {
3338
3763
  assertDictionary(source, context);
3339
3764
  const original = source;
@@ -3378,21 +3803,6 @@ function convertReadableStreamType(type, context) {
3378
3803
  return type;
3379
3804
  }
3380
3805
 
3381
- function convertReaderOptions(options, context) {
3382
- assertDictionary(options, context);
3383
- const mode = options === null || options === void 0 ? void 0 : options.mode;
3384
- return {
3385
- mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
3386
- };
3387
- }
3388
- function convertReadableStreamReaderMode(mode, context) {
3389
- mode = `${mode}`;
3390
- if (mode !== 'byob') {
3391
- throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
3392
- }
3393
- return mode;
3394
- }
3395
-
3396
3806
  function convertIteratorOptions(options, context) {
3397
3807
  assertDictionary(options, context);
3398
3808
  const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
@@ -3562,7 +3972,19 @@ class ReadableStream {
3562
3972
  const options = convertIteratorOptions(rawOptions, 'First parameter');
3563
3973
  return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
3564
3974
  }
3975
+ /**
3976
+ * Creates a new ReadableStream wrapping the provided iterable or async iterable.
3977
+ *
3978
+ * This can be used to adapt various kinds of objects into a readable stream,
3979
+ * such as an array, an async generator, or a Node.js readable stream.
3980
+ */
3981
+ static from(asyncIterable) {
3982
+ return ReadableStreamFrom(asyncIterable);
3983
+ }
3565
3984
  }
3985
+ Object.defineProperties(ReadableStream, {
3986
+ from: { enumerable: true }
3987
+ });
3566
3988
  Object.defineProperties(ReadableStream.prototype, {
3567
3989
  cancel: { enumerable: true },
3568
3990
  getReader: { enumerable: true },
@@ -3572,6 +3994,13 @@ Object.defineProperties(ReadableStream.prototype, {
3572
3994
  values: { enumerable: true },
3573
3995
  locked: { enumerable: true }
3574
3996
  });
3997
+ setFunctionName(ReadableStream.from, 'from');
3998
+ setFunctionName(ReadableStream.prototype.cancel, 'cancel');
3999
+ setFunctionName(ReadableStream.prototype.getReader, 'getReader');
4000
+ setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');
4001
+ setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');
4002
+ setFunctionName(ReadableStream.prototype.tee, 'tee');
4003
+ setFunctionName(ReadableStream.prototype.values, 'values');
3575
4004
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
3576
4005
  Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {
3577
4006
  value: 'ReadableStream',
@@ -3635,10 +4064,11 @@ function ReadableStreamCancel(stream, reason) {
3635
4064
  ReadableStreamClose(stream);
3636
4065
  const reader = stream._reader;
3637
4066
  if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {
3638
- reader._readIntoRequests.forEach(readIntoRequest => {
4067
+ const readIntoRequests = reader._readIntoRequests;
4068
+ reader._readIntoRequests = new SimpleQueue();
4069
+ readIntoRequests.forEach(readIntoRequest => {
3639
4070
  readIntoRequest._closeSteps(undefined);
3640
4071
  });
3641
- reader._readIntoRequests = new SimpleQueue();
3642
4072
  }
3643
4073
  const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
3644
4074
  return transformPromiseWith(sourceCancelPromise, noop);
@@ -3651,10 +4081,11 @@ function ReadableStreamClose(stream) {
3651
4081
  }
3652
4082
  defaultReaderClosedPromiseResolve(reader);
3653
4083
  if (IsReadableStreamDefaultReader(reader)) {
3654
- reader._readRequests.forEach(readRequest => {
4084
+ const readRequests = reader._readRequests;
4085
+ reader._readRequests = new SimpleQueue();
4086
+ readRequests.forEach(readRequest => {
3655
4087
  readRequest._closeSteps();
3656
4088
  });
3657
- reader._readRequests = new SimpleQueue();
3658
4089
  }
3659
4090
  }
3660
4091
  function ReadableStreamError(stream, e) {
@@ -3666,16 +4097,10 @@ function ReadableStreamError(stream, e) {
3666
4097
  }
3667
4098
  defaultReaderClosedPromiseReject(reader, e);
3668
4099
  if (IsReadableStreamDefaultReader(reader)) {
3669
- reader._readRequests.forEach(readRequest => {
3670
- readRequest._errorSteps(e);
3671
- });
3672
- reader._readRequests = new SimpleQueue();
4100
+ ReadableStreamDefaultReaderErrorReadRequests(reader, e);
3673
4101
  }
3674
4102
  else {
3675
- reader._readIntoRequests.forEach(readIntoRequest => {
3676
- readIntoRequest._errorSteps(e);
3677
- });
3678
- reader._readIntoRequests = new SimpleQueue();
4103
+ ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
3679
4104
  }
3680
4105
  }
3681
4106
  // Helper functions for the ReadableStream.
@@ -3696,16 +4121,7 @@ function convertQueuingStrategyInit(init, context) {
3696
4121
  const byteLengthSizeFunction = (chunk) => {
3697
4122
  return chunk.byteLength;
3698
4123
  };
3699
- try {
3700
- Object.defineProperty(byteLengthSizeFunction, 'name', {
3701
- value: 'size',
3702
- configurable: true
3703
- });
3704
- }
3705
- catch (_a) {
3706
- // This property is non-configurable in older browsers, so ignore if this throws.
3707
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
3708
- }
4124
+ setFunctionName(byteLengthSizeFunction, 'size');
3709
4125
  /**
3710
4126
  * A queuing strategy that counts the number of bytes in each chunk.
3711
4127
  *
@@ -3764,16 +4180,7 @@ function IsByteLengthQueuingStrategy(x) {
3764
4180
  const countSizeFunction = () => {
3765
4181
  return 1;
3766
4182
  };
3767
- try {
3768
- Object.defineProperty(countSizeFunction, 'name', {
3769
- value: 'size',
3770
- configurable: true
3771
- });
3772
- }
3773
- catch (_a) {
3774
- // This property is non-configurable in older browsers, so ignore if this throws.
3775
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
3776
- }
4183
+ setFunctionName(countSizeFunction, 'size');
3777
4184
  /**
3778
4185
  * A queuing strategy that counts the number of chunks.
3779
4186
  *
@@ -3831,12 +4238,16 @@ function IsCountQueuingStrategy(x) {
3831
4238
 
3832
4239
  function convertTransformer(original, context) {
3833
4240
  assertDictionary(original, context);
4241
+ const cancel = original === null || original === void 0 ? void 0 : original.cancel;
3834
4242
  const flush = original === null || original === void 0 ? void 0 : original.flush;
3835
4243
  const readableType = original === null || original === void 0 ? void 0 : original.readableType;
3836
4244
  const start = original === null || original === void 0 ? void 0 : original.start;
3837
4245
  const transform = original === null || original === void 0 ? void 0 : original.transform;
3838
4246
  const writableType = original === null || original === void 0 ? void 0 : original.writableType;
3839
4247
  return {
4248
+ cancel: cancel === undefined ?
4249
+ undefined :
4250
+ convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`),
3840
4251
  flush: flush === undefined ?
3841
4252
  undefined :
3842
4253
  convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
@@ -3862,6 +4273,10 @@ function convertTransformerTransformCallback(fn, original, context) {
3862
4273
  assertFunction(fn, context);
3863
4274
  return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
3864
4275
  }
4276
+ function convertTransformerCancelCallback(fn, original, context) {
4277
+ assertFunction(fn, context);
4278
+ return (reason) => promiseCall(fn, original, [reason]);
4279
+ }
3865
4280
 
3866
4281
  // Class TransformStream
3867
4282
  /**
@@ -3950,8 +4365,7 @@ function InitializeTransformStream(stream, startPromise, writableHighWaterMark,
3950
4365
  return TransformStreamDefaultSourcePullAlgorithm(stream);
3951
4366
  }
3952
4367
  function cancelAlgorithm(reason) {
3953
- TransformStreamErrorWritableAndUnblockWrite(stream, reason);
3954
- return promiseResolvedWith(undefined);
4368
+ return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);
3955
4369
  }
3956
4370
  stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
3957
4371
  // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
@@ -3978,6 +4392,9 @@ function TransformStreamError(stream, e) {
3978
4392
  function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
3979
4393
  TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
3980
4394
  WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
4395
+ TransformStreamUnblockWrite(stream);
4396
+ }
4397
+ function TransformStreamUnblockWrite(stream) {
3981
4398
  if (stream._backpressure) {
3982
4399
  // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
3983
4400
  // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
@@ -4048,6 +4465,9 @@ Object.defineProperties(TransformStreamDefaultController.prototype, {
4048
4465
  terminate: { enumerable: true },
4049
4466
  desiredSize: { enumerable: true }
4050
4467
  });
4468
+ setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');
4469
+ setFunctionName(TransformStreamDefaultController.prototype.error, 'error');
4470
+ setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');
4051
4471
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4052
4472
  Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
4053
4473
  value: 'TransformStreamDefaultController',
@@ -4064,35 +4484,53 @@ function IsTransformStreamDefaultController(x) {
4064
4484
  }
4065
4485
  return x instanceof TransformStreamDefaultController;
4066
4486
  }
4067
- function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
4487
+ function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
4068
4488
  controller._controlledTransformStream = stream;
4069
4489
  stream._transformStreamController = controller;
4070
4490
  controller._transformAlgorithm = transformAlgorithm;
4071
4491
  controller._flushAlgorithm = flushAlgorithm;
4492
+ controller._cancelAlgorithm = cancelAlgorithm;
4493
+ controller._finishPromise = undefined;
4494
+ controller._finishPromise_resolve = undefined;
4495
+ controller._finishPromise_reject = undefined;
4072
4496
  }
4073
4497
  function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
4074
4498
  const controller = Object.create(TransformStreamDefaultController.prototype);
4075
- let transformAlgorithm = (chunk) => {
4076
- try {
4077
- TransformStreamDefaultControllerEnqueue(controller, chunk);
4078
- return promiseResolvedWith(undefined);
4079
- }
4080
- catch (transformResultE) {
4081
- return promiseRejectedWith(transformResultE);
4082
- }
4083
- };
4084
- let flushAlgorithm = () => promiseResolvedWith(undefined);
4499
+ let transformAlgorithm;
4500
+ let flushAlgorithm;
4501
+ let cancelAlgorithm;
4085
4502
  if (transformer.transform !== undefined) {
4086
4503
  transformAlgorithm = chunk => transformer.transform(chunk, controller);
4087
4504
  }
4505
+ else {
4506
+ transformAlgorithm = chunk => {
4507
+ try {
4508
+ TransformStreamDefaultControllerEnqueue(controller, chunk);
4509
+ return promiseResolvedWith(undefined);
4510
+ }
4511
+ catch (transformResultE) {
4512
+ return promiseRejectedWith(transformResultE);
4513
+ }
4514
+ };
4515
+ }
4088
4516
  if (transformer.flush !== undefined) {
4089
4517
  flushAlgorithm = () => transformer.flush(controller);
4090
4518
  }
4091
- SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
4519
+ else {
4520
+ flushAlgorithm = () => promiseResolvedWith(undefined);
4521
+ }
4522
+ if (transformer.cancel !== undefined) {
4523
+ cancelAlgorithm = reason => transformer.cancel(reason);
4524
+ }
4525
+ else {
4526
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
4527
+ }
4528
+ SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);
4092
4529
  }
4093
4530
  function TransformStreamDefaultControllerClearAlgorithms(controller) {
4094
4531
  controller._transformAlgorithm = undefined;
4095
4532
  controller._flushAlgorithm = undefined;
4533
+ controller._cancelAlgorithm = undefined;
4096
4534
  }
4097
4535
  function TransformStreamDefaultControllerEnqueue(controller, chunk) {
4098
4536
  const stream = controller._controlledTransformStream;
@@ -4149,27 +4587,66 @@ function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
4149
4587
  return TransformStreamDefaultControllerPerformTransform(controller, chunk);
4150
4588
  }
4151
4589
  function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
4152
- // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
4153
- // errored.
4154
- TransformStreamError(stream, reason);
4155
- return promiseResolvedWith(undefined);
4590
+ const controller = stream._transformStreamController;
4591
+ if (controller._finishPromise !== undefined) {
4592
+ return controller._finishPromise;
4593
+ }
4594
+ // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4595
+ const readable = stream._readable;
4596
+ // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,
4597
+ // we don't run the _cancelAlgorithm again.
4598
+ controller._finishPromise = newPromise((resolve, reject) => {
4599
+ controller._finishPromise_resolve = resolve;
4600
+ controller._finishPromise_reject = reject;
4601
+ });
4602
+ const cancelPromise = controller._cancelAlgorithm(reason);
4603
+ TransformStreamDefaultControllerClearAlgorithms(controller);
4604
+ uponPromise(cancelPromise, () => {
4605
+ if (readable._state === 'errored') {
4606
+ defaultControllerFinishPromiseReject(controller, readable._storedError);
4607
+ }
4608
+ else {
4609
+ ReadableStreamDefaultControllerError(readable._readableStreamController, reason);
4610
+ defaultControllerFinishPromiseResolve(controller);
4611
+ }
4612
+ return null;
4613
+ }, r => {
4614
+ ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4615
+ defaultControllerFinishPromiseReject(controller, r);
4616
+ return null;
4617
+ });
4618
+ return controller._finishPromise;
4156
4619
  }
4157
4620
  function TransformStreamDefaultSinkCloseAlgorithm(stream) {
4621
+ const controller = stream._transformStreamController;
4622
+ if (controller._finishPromise !== undefined) {
4623
+ return controller._finishPromise;
4624
+ }
4158
4625
  // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4159
4626
  const readable = stream._readable;
4160
- const controller = stream._transformStreamController;
4627
+ // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,
4628
+ // we don't also run the _cancelAlgorithm.
4629
+ controller._finishPromise = newPromise((resolve, reject) => {
4630
+ controller._finishPromise_resolve = resolve;
4631
+ controller._finishPromise_reject = reject;
4632
+ });
4161
4633
  const flushPromise = controller._flushAlgorithm();
4162
4634
  TransformStreamDefaultControllerClearAlgorithms(controller);
4163
- // Return a promise that is fulfilled with undefined on success.
4164
- return transformPromiseWith(flushPromise, () => {
4635
+ uponPromise(flushPromise, () => {
4165
4636
  if (readable._state === 'errored') {
4166
- throw readable._storedError;
4637
+ defaultControllerFinishPromiseReject(controller, readable._storedError);
4638
+ }
4639
+ else {
4640
+ ReadableStreamDefaultControllerClose(readable._readableStreamController);
4641
+ defaultControllerFinishPromiseResolve(controller);
4167
4642
  }
4168
- ReadableStreamDefaultControllerClose(readable._readableStreamController);
4643
+ return null;
4169
4644
  }, r => {
4170
- TransformStreamError(stream, r);
4171
- throw readable._storedError;
4645
+ ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4646
+ defaultControllerFinishPromiseReject(controller, r);
4647
+ return null;
4172
4648
  });
4649
+ return controller._finishPromise;
4173
4650
  }
4174
4651
  // TransformStreamDefaultSource Algorithms
4175
4652
  function TransformStreamDefaultSourcePullAlgorithm(stream) {
@@ -4178,10 +4655,61 @@ function TransformStreamDefaultSourcePullAlgorithm(stream) {
4178
4655
  // Prevent the next pull() call until there is backpressure.
4179
4656
  return stream._backpressureChangePromise;
4180
4657
  }
4658
+ function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) {
4659
+ const controller = stream._transformStreamController;
4660
+ if (controller._finishPromise !== undefined) {
4661
+ return controller._finishPromise;
4662
+ }
4663
+ // stream._writable cannot change after construction, so caching it across a call to user code is safe.
4664
+ const writable = stream._writable;
4665
+ // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or
4666
+ // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the
4667
+ // _flushAlgorithm.
4668
+ controller._finishPromise = newPromise((resolve, reject) => {
4669
+ controller._finishPromise_resolve = resolve;
4670
+ controller._finishPromise_reject = reject;
4671
+ });
4672
+ const cancelPromise = controller._cancelAlgorithm(reason);
4673
+ TransformStreamDefaultControllerClearAlgorithms(controller);
4674
+ uponPromise(cancelPromise, () => {
4675
+ if (writable._state === 'errored') {
4676
+ defaultControllerFinishPromiseReject(controller, writable._storedError);
4677
+ }
4678
+ else {
4679
+ WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);
4680
+ TransformStreamUnblockWrite(stream);
4681
+ defaultControllerFinishPromiseResolve(controller);
4682
+ }
4683
+ return null;
4684
+ }, r => {
4685
+ WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);
4686
+ TransformStreamUnblockWrite(stream);
4687
+ defaultControllerFinishPromiseReject(controller, r);
4688
+ return null;
4689
+ });
4690
+ return controller._finishPromise;
4691
+ }
4181
4692
  // Helper functions for the TransformStreamDefaultController.
4182
4693
  function defaultControllerBrandCheckException(name) {
4183
4694
  return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
4184
4695
  }
4696
+ function defaultControllerFinishPromiseResolve(controller) {
4697
+ if (controller._finishPromise_resolve === undefined) {
4698
+ return;
4699
+ }
4700
+ controller._finishPromise_resolve();
4701
+ controller._finishPromise_resolve = undefined;
4702
+ controller._finishPromise_reject = undefined;
4703
+ }
4704
+ function defaultControllerFinishPromiseReject(controller, reason) {
4705
+ if (controller._finishPromise_reject === undefined) {
4706
+ return;
4707
+ }
4708
+ setPromiseIsHandledToTrue(controller._finishPromise);
4709
+ controller._finishPromise_reject(reason);
4710
+ controller._finishPromise_resolve = undefined;
4711
+ controller._finishPromise_reject = undefined;
4712
+ }
4185
4713
  // Helper functions for the TransformStream.
4186
4714
  function streamBrandCheckException(name) {
4187
4715
  return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);