web-streams-polyfill 3.2.0 → 3.3.0

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 (43) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +11 -14
  3. package/dist/polyfill.es2018.js +723 -185
  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 -181
  8. package/dist/polyfill.es2018.mjs.map +1 -1
  9. package/dist/polyfill.es6.js +789 -185
  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 -181
  14. package/dist/polyfill.es6.mjs.map +1 -1
  15. package/dist/polyfill.js +873 -231
  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 -227
  20. package/dist/polyfill.mjs.map +1 -1
  21. package/dist/ponyfill.es2018.js +723 -185
  22. package/dist/ponyfill.es2018.js.map +1 -1
  23. package/dist/ponyfill.es2018.mjs +721 -181
  24. package/dist/ponyfill.es2018.mjs.map +1 -1
  25. package/dist/ponyfill.es6.js +789 -185
  26. package/dist/ponyfill.es6.js.map +1 -1
  27. package/dist/ponyfill.es6.mjs +787 -181
  28. package/dist/ponyfill.es6.mjs.map +1 -1
  29. package/dist/ponyfill.js +873 -231
  30. package/dist/ponyfill.js.map +1 -1
  31. package/dist/ponyfill.mjs +871 -227
  32. package/dist/ponyfill.mjs.map +1 -1
  33. package/es2018/package.json +1 -1
  34. package/es6/package.json +1 -1
  35. package/package.json +30 -32
  36. package/ponyfill/es2018/package.json +1 -1
  37. package/ponyfill/es6/package.json +1 -1
  38. package/ponyfill/package.json +1 -1
  39. package/types/polyfill.d.ts +29 -0
  40. package/{dist/types/ts3.6/polyfill.d.ts → types/ponyfill.d.ts} +57 -7
  41. package/{dist/types → types}/tsdoc-metadata.json +1 -1
  42. package/CHANGELOG.md +0 -134
  43. package/dist/types/polyfill.d.ts +0 -771
@@ -1,50 +1,54 @@
1
1
  /**
2
- * web-streams-polyfill v3.2.0
2
+ * @license
3
+ * web-streams-polyfill v3.3.0
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
  (function (global, factory) {
5
9
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
6
10
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
7
11
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {}));
8
- }(this, (function (exports) { 'use strict';
12
+ })(this, (function (exports) { 'use strict';
9
13
 
10
14
  /// <reference lib="es2015.symbol" />
11
15
  const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
12
16
  Symbol :
13
17
  description => `Symbol(${description})`;
14
18
 
15
- /// <reference lib="dom" />
16
19
  function noop() {
17
20
  return undefined;
18
21
  }
19
- function getGlobals() {
20
- if (typeof self !== 'undefined') {
21
- return self;
22
- }
23
- else if (typeof window !== 'undefined') {
24
- return window;
25
- }
26
- else if (typeof global !== 'undefined') {
27
- return global;
28
- }
29
- return undefined;
30
- }
31
- const globals = getGlobals();
32
22
 
33
23
  function typeIsObject(x) {
34
24
  return (typeof x === 'object' && x !== null) || typeof x === 'function';
35
25
  }
36
26
  const rethrowAssertionErrorRejection = noop;
27
+ function setFunctionName(fn, name) {
28
+ try {
29
+ Object.defineProperty(fn, 'name', {
30
+ value: name,
31
+ configurable: true
32
+ });
33
+ }
34
+ catch (_a) {
35
+ // This property is non-configurable in older browsers, so ignore if this throws.
36
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
37
+ }
38
+ }
37
39
 
38
40
  const originalPromise = Promise;
39
41
  const originalPromiseThen = Promise.prototype.then;
40
- const originalPromiseResolve = Promise.resolve.bind(originalPromise);
41
42
  const originalPromiseReject = Promise.reject.bind(originalPromise);
43
+ // https://webidl.spec.whatwg.org/#a-new-promise
42
44
  function newPromise(executor) {
43
45
  return new originalPromise(executor);
44
46
  }
47
+ // https://webidl.spec.whatwg.org/#a-promise-resolved-with
45
48
  function promiseResolvedWith(value) {
46
- return originalPromiseResolve(value);
49
+ return newPromise(resolve => resolve(value));
47
50
  }
51
+ // https://webidl.spec.whatwg.org/#a-promise-rejected-with
48
52
  function promiseRejectedWith(reason) {
49
53
  return originalPromiseReject(reason);
50
54
  }
@@ -53,6 +57,9 @@
53
57
  // approximation.
54
58
  return originalPromiseThen.call(promise, onFulfilled, onRejected);
55
59
  }
60
+ // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned
61
+ // from that handler. To prevent this, return null instead of void from all handlers.
62
+ // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it
56
63
  function uponPromise(promise, onFulfilled, onRejected) {
57
64
  PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
58
65
  }
@@ -68,14 +75,16 @@
68
75
  function setPromiseIsHandledToTrue(promise) {
69
76
  PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
70
77
  }
71
- const queueMicrotask = (() => {
72
- const globalQueueMicrotask = globals && globals.queueMicrotask;
73
- if (typeof globalQueueMicrotask === 'function') {
74
- return globalQueueMicrotask;
78
+ let _queueMicrotask = callback => {
79
+ if (typeof queueMicrotask === 'function') {
80
+ _queueMicrotask = queueMicrotask;
75
81
  }
76
- const resolvedPromise = promiseResolvedWith(undefined);
77
- return (fn) => PerformPromiseThen(resolvedPromise, fn);
78
- })();
82
+ else {
83
+ const resolvedPromise = promiseResolvedWith(undefined);
84
+ _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);
85
+ }
86
+ return _queueMicrotask(callback);
87
+ };
79
88
  function reflectCall(F, V, args) {
80
89
  if (typeof F !== 'function') {
81
90
  throw new TypeError('Argument is not a function');
@@ -199,6 +208,12 @@
199
208
  }
200
209
  }
201
210
 
211
+ const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
212
+ const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
213
+ const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
214
+ const PullSteps = SymbolPolyfill('[[PullSteps]]');
215
+ const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]');
216
+
202
217
  function ReadableStreamReaderGenericInitialize(reader, stream) {
203
218
  reader._ownerReadableStream = stream;
204
219
  stream._reader = reader;
@@ -219,13 +234,15 @@
219
234
  return ReadableStreamCancel(stream, reason);
220
235
  }
221
236
  function ReadableStreamReaderGenericRelease(reader) {
222
- if (reader._ownerReadableStream._state === 'readable') {
237
+ const stream = reader._ownerReadableStream;
238
+ if (stream._state === 'readable') {
223
239
  defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
224
240
  }
225
241
  else {
226
242
  defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
227
243
  }
228
- reader._ownerReadableStream._reader = undefined;
244
+ stream._readableStreamController[ReleaseSteps]();
245
+ stream._reader = undefined;
229
246
  reader._ownerReadableStream = undefined;
230
247
  }
231
248
  // Helper functions for the readers.
@@ -268,11 +285,6 @@
268
285
  reader._closedPromise_reject = undefined;
269
286
  }
270
287
 
271
- const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
272
- const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
273
- const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
274
- const PullSteps = SymbolPolyfill('[[PullSteps]]');
275
-
276
288
  /// <reference lib="es2015.core" />
277
289
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
278
290
  const NumberIsFinite = Number.isFinite || function (x) {
@@ -468,10 +480,7 @@
468
480
  if (this._ownerReadableStream === undefined) {
469
481
  return;
470
482
  }
471
- if (this._readRequests.length > 0) {
472
- throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
473
- }
474
- ReadableStreamReaderGenericRelease(this);
483
+ ReadableStreamDefaultReaderRelease(this);
475
484
  }
476
485
  }
477
486
  Object.defineProperties(ReadableStreamDefaultReader.prototype, {
@@ -480,6 +489,9 @@
480
489
  releaseLock: { enumerable: true },
481
490
  closed: { enumerable: true }
482
491
  });
492
+ setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');
493
+ setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');
494
+ setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');
483
495
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
484
496
  Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
485
497
  value: 'ReadableStreamDefaultReader',
@@ -509,6 +521,18 @@
509
521
  stream._readableStreamController[PullSteps](readRequest);
510
522
  }
511
523
  }
524
+ function ReadableStreamDefaultReaderRelease(reader) {
525
+ ReadableStreamReaderGenericRelease(reader);
526
+ const e = new TypeError('Reader was released');
527
+ ReadableStreamDefaultReaderErrorReadRequests(reader, e);
528
+ }
529
+ function ReadableStreamDefaultReaderErrorReadRequests(reader, e) {
530
+ const readRequests = reader._readRequests;
531
+ reader._readRequests = new SimpleQueue();
532
+ readRequests.forEach(readRequest => {
533
+ readRequest._errorSteps(e);
534
+ });
535
+ }
512
536
  // Helper functions for the ReadableStreamDefaultReader.
513
537
  function defaultReaderBrandCheckException(name) {
514
538
  return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
@@ -555,9 +579,6 @@
555
579
  return Promise.resolve({ value: undefined, done: true });
556
580
  }
557
581
  const reader = this._reader;
558
- if (reader._ownerReadableStream === undefined) {
559
- return promiseRejectedWith(readerLockException('iterate'));
560
- }
561
582
  let resolvePromise;
562
583
  let rejectPromise;
563
584
  const promise = newPromise((resolve, reject) => {
@@ -569,7 +590,7 @@
569
590
  this._ongoingPromise = undefined;
570
591
  // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
571
592
  // FIXME Is this a bug in the specification, or in the test?
572
- queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
593
+ _queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
573
594
  },
574
595
  _closeSteps: () => {
575
596
  this._ongoingPromise = undefined;
@@ -593,9 +614,6 @@
593
614
  }
594
615
  this._isFinished = true;
595
616
  const reader = this._reader;
596
- if (reader._ownerReadableStream === undefined) {
597
- return promiseRejectedWith(readerLockException('finish iterating'));
598
- }
599
617
  if (!this._preventCancel) {
600
618
  const result = ReadableStreamReaderGenericCancel(reader, value);
601
619
  ReadableStreamReaderGenericRelease(reader);
@@ -658,6 +676,70 @@
658
676
  return x !== x;
659
677
  };
660
678
 
679
+ /******************************************************************************
680
+ Copyright (c) Microsoft Corporation.
681
+
682
+ Permission to use, copy, modify, and/or distribute this software for any
683
+ purpose with or without fee is hereby granted.
684
+
685
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
686
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
687
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
688
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
689
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
690
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
691
+ PERFORMANCE OF THIS SOFTWARE.
692
+ ***************************************************************************** */
693
+ /* global Reflect, Promise, SuppressedError, Symbol */
694
+
695
+
696
+ function __values(o) {
697
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
698
+ if (m) return m.call(o);
699
+ if (o && typeof o.length === "number") return {
700
+ next: function () {
701
+ if (o && i >= o.length) o = void 0;
702
+ return { value: o && o[i++], done: !o };
703
+ }
704
+ };
705
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
706
+ }
707
+
708
+ function __await(v) {
709
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
710
+ }
711
+
712
+ function __asyncGenerator(thisArg, _arguments, generator) {
713
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
714
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
715
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
716
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
717
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
718
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
719
+ function fulfill(value) { resume("next", value); }
720
+ function reject(value) { resume("throw", value); }
721
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
722
+ }
723
+
724
+ function __asyncDelegator(o) {
725
+ var i, p;
726
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
727
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
728
+ }
729
+
730
+ function __asyncValues(o) {
731
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
732
+ var m = o[Symbol.asyncIterator], i;
733
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
734
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
735
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
736
+ }
737
+
738
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
739
+ var e = new Error(message);
740
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
741
+ };
742
+
661
743
  function CreateArrayFromList(elements) {
662
744
  // We use arrays to represent lists, so this is basically a no-op.
663
745
  // Do a slice though just in case we happen to depend on the unique-ness.
@@ -666,15 +748,29 @@
666
748
  function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
667
749
  new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
668
750
  }
669
- // Not implemented correctly
670
- function TransferArrayBuffer(O) {
671
- return O;
672
- }
673
- // Not implemented correctly
674
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
675
- function IsDetachedBuffer(O) {
676
- return false;
677
- }
751
+ let TransferArrayBuffer = (O) => {
752
+ if (typeof O.transfer === 'function') {
753
+ TransferArrayBuffer = buffer => buffer.transfer();
754
+ }
755
+ else if (typeof structuredClone === 'function') {
756
+ TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });
757
+ }
758
+ else {
759
+ // Not implemented correctly
760
+ TransferArrayBuffer = buffer => buffer;
761
+ }
762
+ return TransferArrayBuffer(O);
763
+ };
764
+ let IsDetachedBuffer = (O) => {
765
+ if (typeof O.detached === 'boolean') {
766
+ IsDetachedBuffer = buffer => buffer.detached;
767
+ }
768
+ else {
769
+ // Not implemented correctly
770
+ IsDetachedBuffer = buffer => buffer.byteLength === 0;
771
+ }
772
+ return IsDetachedBuffer(O);
773
+ };
678
774
  function ArrayBufferSlice(buffer, begin, end) {
679
775
  // ArrayBuffer.prototype.slice is not available on IE10
680
776
  // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice
@@ -686,6 +782,70 @@
686
782
  CopyDataBlockBytes(slice, 0, buffer, begin, length);
687
783
  return slice;
688
784
  }
785
+ function GetMethod(receiver, prop) {
786
+ const func = receiver[prop];
787
+ if (func === undefined || func === null) {
788
+ return undefined;
789
+ }
790
+ if (typeof func !== 'function') {
791
+ throw new TypeError(`${String(prop)} is not a function`);
792
+ }
793
+ return func;
794
+ }
795
+ function CreateAsyncFromSyncIterator(syncIteratorRecord) {
796
+ // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,
797
+ // we use yield* inside an async generator function to achieve the same result.
798
+ // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.
799
+ const syncIterable = {
800
+ [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator
801
+ };
802
+ // Create an async generator function and immediately invoke it.
803
+ const asyncIterator = (function () {
804
+ return __asyncGenerator(this, arguments, function* () {
805
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable))));
806
+ });
807
+ }());
808
+ // Return as an async iterator record.
809
+ const nextMethod = asyncIterator.next;
810
+ return { iterator: asyncIterator, nextMethod, done: false };
811
+ }
812
+ function GetIterator(obj, hint = 'sync', method) {
813
+ if (method === undefined) {
814
+ if (hint === 'async') {
815
+ method = GetMethod(obj, SymbolPolyfill.asyncIterator);
816
+ if (method === undefined) {
817
+ const syncMethod = GetMethod(obj, SymbolPolyfill.iterator);
818
+ const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod);
819
+ return CreateAsyncFromSyncIterator(syncIteratorRecord);
820
+ }
821
+ }
822
+ else {
823
+ method = GetMethod(obj, SymbolPolyfill.iterator);
824
+ }
825
+ }
826
+ if (method === undefined) {
827
+ throw new TypeError('The object is not iterable');
828
+ }
829
+ const iterator = reflectCall(method, obj, []);
830
+ if (!typeIsObject(iterator)) {
831
+ throw new TypeError('The iterator method must return an object');
832
+ }
833
+ const nextMethod = iterator.next;
834
+ return { iterator, nextMethod, done: false };
835
+ }
836
+ function IteratorNext(iteratorRecord) {
837
+ const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);
838
+ if (!typeIsObject(result)) {
839
+ throw new TypeError('The iterator.next() method must return an object');
840
+ }
841
+ return result;
842
+ }
843
+ function IteratorComplete(iterResult) {
844
+ return Boolean(iterResult.done);
845
+ }
846
+ function IteratorValue(iterResult) {
847
+ return iterResult.value;
848
+ }
689
849
 
690
850
  function IsNonNegativeNumber(v) {
691
851
  if (typeof v !== 'number') {
@@ -728,6 +888,19 @@
728
888
  container._queueTotalSize = 0;
729
889
  }
730
890
 
891
+ function isDataViewConstructor(ctor) {
892
+ return ctor === DataView;
893
+ }
894
+ function isDataView(view) {
895
+ return isDataViewConstructor(view.constructor);
896
+ }
897
+ function arrayBufferViewElementSize(ctor) {
898
+ if (isDataViewConstructor(ctor)) {
899
+ return 1;
900
+ }
901
+ return ctor.BYTES_PER_ELEMENT;
902
+ }
903
+
731
904
  /**
732
905
  * A pull-into request in a {@link ReadableByteStreamController}.
733
906
  *
@@ -755,7 +928,9 @@
755
928
  if (this._associatedReadableByteStreamController === undefined) {
756
929
  throw new TypeError('This BYOB request has been invalidated');
757
930
  }
758
- if (IsDetachedBuffer(this._view.buffer)) ;
931
+ if (IsDetachedBuffer(this._view.buffer)) {
932
+ throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);
933
+ }
759
934
  ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
760
935
  }
761
936
  respondWithNewView(view) {
@@ -769,7 +944,9 @@
769
944
  if (this._associatedReadableByteStreamController === undefined) {
770
945
  throw new TypeError('This BYOB request has been invalidated');
771
946
  }
772
- if (IsDetachedBuffer(view.buffer)) ;
947
+ if (IsDetachedBuffer(view.buffer)) {
948
+ throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response');
949
+ }
773
950
  ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
774
951
  }
775
952
  }
@@ -778,6 +955,8 @@
778
955
  respondWithNewView: { enumerable: true },
779
956
  view: { enumerable: true }
780
957
  });
958
+ setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');
959
+ setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');
781
960
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
782
961
  Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
783
962
  value: 'ReadableStreamBYOBRequest',
@@ -873,11 +1052,7 @@
873
1052
  [PullSteps](readRequest) {
874
1053
  const stream = this._controlledReadableByteStream;
875
1054
  if (this._queueTotalSize > 0) {
876
- const entry = this._queue.shift();
877
- this._queueTotalSize -= entry.byteLength;
878
- ReadableByteStreamControllerHandleQueueDrain(this);
879
- const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
880
- readRequest._chunkSteps(view);
1055
+ ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);
881
1056
  return;
882
1057
  }
883
1058
  const autoAllocateChunkSize = this._autoAllocateChunkSize;
@@ -896,6 +1071,7 @@
896
1071
  byteOffset: 0,
897
1072
  byteLength: autoAllocateChunkSize,
898
1073
  bytesFilled: 0,
1074
+ minimumFill: 1,
899
1075
  elementSize: 1,
900
1076
  viewConstructor: Uint8Array,
901
1077
  readerType: 'default'
@@ -905,6 +1081,15 @@
905
1081
  ReadableStreamAddReadRequest(stream, readRequest);
906
1082
  ReadableByteStreamControllerCallPullIfNeeded(this);
907
1083
  }
1084
+ /** @internal */
1085
+ [ReleaseSteps]() {
1086
+ if (this._pendingPullIntos.length > 0) {
1087
+ const firstPullInto = this._pendingPullIntos.peek();
1088
+ firstPullInto.readerType = 'none';
1089
+ this._pendingPullIntos = new SimpleQueue();
1090
+ this._pendingPullIntos.push(firstPullInto);
1091
+ }
1092
+ }
908
1093
  }
909
1094
  Object.defineProperties(ReadableByteStreamController.prototype, {
910
1095
  close: { enumerable: true },
@@ -913,6 +1098,9 @@
913
1098
  byobRequest: { enumerable: true },
914
1099
  desiredSize: { enumerable: true }
915
1100
  });
1101
+ setFunctionName(ReadableByteStreamController.prototype.close, 'close');
1102
+ setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');
1103
+ setFunctionName(ReadableByteStreamController.prototype.error, 'error');
916
1104
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
917
1105
  Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
918
1106
  value: 'ReadableByteStreamController',
@@ -956,8 +1144,10 @@
956
1144
  controller._pullAgain = false;
957
1145
  ReadableByteStreamControllerCallPullIfNeeded(controller);
958
1146
  }
1147
+ return null;
959
1148
  }, e => {
960
1149
  ReadableByteStreamControllerError(controller, e);
1150
+ return null;
961
1151
  });
962
1152
  }
963
1153
  function ReadableByteStreamControllerClearPendingPullIntos(controller) {
@@ -986,15 +1176,33 @@
986
1176
  controller._queue.push({ buffer, byteOffset, byteLength });
987
1177
  controller._queueTotalSize += byteLength;
988
1178
  }
1179
+ function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) {
1180
+ let clonedChunk;
1181
+ try {
1182
+ clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);
1183
+ }
1184
+ catch (cloneE) {
1185
+ ReadableByteStreamControllerError(controller, cloneE);
1186
+ throw cloneE;
1187
+ }
1188
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);
1189
+ }
1190
+ function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) {
1191
+ if (firstDescriptor.bytesFilled > 0) {
1192
+ ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled);
1193
+ }
1194
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
1195
+ }
989
1196
  function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
990
- const elementSize = pullIntoDescriptor.elementSize;
991
- const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
992
1197
  const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
993
1198
  const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
994
- const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
995
1199
  let totalBytesToCopyRemaining = maxBytesToCopy;
996
1200
  let ready = false;
997
- if (maxAlignedBytes > currentAlignedBytes) {
1201
+ const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;
1202
+ const maxAlignedBytes = maxBytesFilled - remainderBytes;
1203
+ // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1204
+ // of the queue, so the underlying source can keep filling it.
1205
+ if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {
998
1206
  totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
999
1207
  ready = true;
1000
1208
  }
@@ -1049,25 +1257,37 @@
1049
1257
  }
1050
1258
  }
1051
1259
  }
1052
- function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
1053
- const stream = controller._controlledReadableByteStream;
1054
- let elementSize = 1;
1055
- if (view.constructor !== DataView) {
1056
- elementSize = view.constructor.BYTES_PER_ELEMENT;
1260
+ function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) {
1261
+ const reader = controller._controlledReadableByteStream._reader;
1262
+ while (reader._readRequests.length > 0) {
1263
+ if (controller._queueTotalSize === 0) {
1264
+ return;
1265
+ }
1266
+ const readRequest = reader._readRequests.shift();
1267
+ ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);
1057
1268
  }
1269
+ }
1270
+ function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) {
1271
+ const stream = controller._controlledReadableByteStream;
1058
1272
  const ctor = view.constructor;
1059
- // try {
1060
- const buffer = TransferArrayBuffer(view.buffer);
1061
- // } catch (e) {
1062
- // readIntoRequest._errorSteps(e);
1063
- // return;
1064
- // }
1273
+ const elementSize = arrayBufferViewElementSize(ctor);
1274
+ const { byteOffset, byteLength } = view;
1275
+ const minimumFill = min * elementSize;
1276
+ let buffer;
1277
+ try {
1278
+ buffer = TransferArrayBuffer(view.buffer);
1279
+ }
1280
+ catch (e) {
1281
+ readIntoRequest._errorSteps(e);
1282
+ return;
1283
+ }
1065
1284
  const pullIntoDescriptor = {
1066
1285
  buffer,
1067
1286
  bufferByteLength: buffer.byteLength,
1068
- byteOffset: view.byteOffset,
1069
- byteLength: view.byteLength,
1287
+ byteOffset,
1288
+ byteLength,
1070
1289
  bytesFilled: 0,
1290
+ minimumFill,
1071
1291
  elementSize,
1072
1292
  viewConstructor: ctor,
1073
1293
  readerType: 'byob'
@@ -1104,6 +1324,9 @@
1104
1324
  ReadableByteStreamControllerCallPullIfNeeded(controller);
1105
1325
  }
1106
1326
  function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
1327
+ if (firstDescriptor.readerType === 'none') {
1328
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
1329
+ }
1107
1330
  const stream = controller._controlledReadableByteStream;
1108
1331
  if (ReadableStreamHasBYOBReader(stream)) {
1109
1332
  while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
@@ -1114,15 +1337,21 @@
1114
1337
  }
1115
1338
  function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
1116
1339
  ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
1117
- if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
1340
+ if (pullIntoDescriptor.readerType === 'none') {
1341
+ ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);
1342
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1343
+ return;
1344
+ }
1345
+ if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {
1346
+ // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1347
+ // of the queue, so the underlying source can keep filling it.
1118
1348
  return;
1119
1349
  }
1120
1350
  ReadableByteStreamControllerShiftPendingPullInto(controller);
1121
1351
  const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
1122
1352
  if (remainderSize > 0) {
1123
1353
  const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
1124
- const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);
1125
- ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
1354
+ ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize);
1126
1355
  }
1127
1356
  pullIntoDescriptor.bytesFilled -= remainderSize;
1128
1357
  ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
@@ -1133,7 +1362,7 @@
1133
1362
  ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1134
1363
  const state = controller._controlledReadableByteStream._state;
1135
1364
  if (state === 'closed') {
1136
- ReadableByteStreamControllerRespondInClosedState(controller);
1365
+ ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
1137
1366
  }
1138
1367
  else {
1139
1368
  ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
@@ -1183,7 +1412,7 @@
1183
1412
  }
1184
1413
  if (controller._pendingPullIntos.length > 0) {
1185
1414
  const firstPendingPullInto = controller._pendingPullIntos.peek();
1186
- if (firstPendingPullInto.bytesFilled > 0) {
1415
+ if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {
1187
1416
  const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
1188
1417
  ReadableByteStreamControllerError(controller, e);
1189
1418
  throw e;
@@ -1197,17 +1426,24 @@
1197
1426
  if (controller._closeRequested || stream._state !== 'readable') {
1198
1427
  return;
1199
1428
  }
1200
- const buffer = chunk.buffer;
1201
- const byteOffset = chunk.byteOffset;
1202
- const byteLength = chunk.byteLength;
1429
+ const { buffer, byteOffset, byteLength } = chunk;
1430
+ if (IsDetachedBuffer(buffer)) {
1431
+ throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued');
1432
+ }
1203
1433
  const transferredBuffer = TransferArrayBuffer(buffer);
1204
1434
  if (controller._pendingPullIntos.length > 0) {
1205
1435
  const firstPendingPullInto = controller._pendingPullIntos.peek();
1206
- if (IsDetachedBuffer(firstPendingPullInto.buffer)) ;
1436
+ if (IsDetachedBuffer(firstPendingPullInto.buffer)) {
1437
+ throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk');
1438
+ }
1439
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1207
1440
  firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
1441
+ if (firstPendingPullInto.readerType === 'none') {
1442
+ ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);
1443
+ }
1208
1444
  }
1209
- ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1210
1445
  if (ReadableStreamHasDefaultReader(stream)) {
1446
+ ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
1211
1447
  if (ReadableStreamGetNumReadRequests(stream) === 0) {
1212
1448
  ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1213
1449
  }
@@ -1239,6 +1475,13 @@
1239
1475
  ReadableByteStreamControllerClearAlgorithms(controller);
1240
1476
  ReadableStreamError(stream, e);
1241
1477
  }
1478
+ function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
1479
+ const entry = controller._queue.shift();
1480
+ controller._queueTotalSize -= entry.byteLength;
1481
+ ReadableByteStreamControllerHandleQueueDrain(controller);
1482
+ const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
1483
+ readRequest._chunkSteps(view);
1484
+ }
1242
1485
  function ReadableByteStreamControllerGetBYOBRequest(controller) {
1243
1486
  if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
1244
1487
  const firstDescriptor = controller._pendingPullIntos.peek();
@@ -1324,24 +1567,35 @@
1324
1567
  uponPromise(promiseResolvedWith(startResult), () => {
1325
1568
  controller._started = true;
1326
1569
  ReadableByteStreamControllerCallPullIfNeeded(controller);
1570
+ return null;
1327
1571
  }, r => {
1328
1572
  ReadableByteStreamControllerError(controller, r);
1573
+ return null;
1329
1574
  });
1330
1575
  }
1331
1576
  function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
1332
1577
  const controller = Object.create(ReadableByteStreamController.prototype);
1333
- let startAlgorithm = () => undefined;
1334
- let pullAlgorithm = () => promiseResolvedWith(undefined);
1335
- let cancelAlgorithm = () => promiseResolvedWith(undefined);
1578
+ let startAlgorithm;
1579
+ let pullAlgorithm;
1580
+ let cancelAlgorithm;
1336
1581
  if (underlyingByteSource.start !== undefined) {
1337
1582
  startAlgorithm = () => underlyingByteSource.start(controller);
1338
1583
  }
1584
+ else {
1585
+ startAlgorithm = () => undefined;
1586
+ }
1339
1587
  if (underlyingByteSource.pull !== undefined) {
1340
1588
  pullAlgorithm = () => underlyingByteSource.pull(controller);
1341
1589
  }
1590
+ else {
1591
+ pullAlgorithm = () => promiseResolvedWith(undefined);
1592
+ }
1342
1593
  if (underlyingByteSource.cancel !== undefined) {
1343
1594
  cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
1344
1595
  }
1596
+ else {
1597
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
1598
+ }
1345
1599
  const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
1346
1600
  if (autoAllocateChunkSize === 0) {
1347
1601
  throw new TypeError('autoAllocateChunkSize must be greater than 0');
@@ -1361,6 +1615,29 @@
1361
1615
  return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
1362
1616
  }
1363
1617
 
1618
+ function convertReaderOptions(options, context) {
1619
+ assertDictionary(options, context);
1620
+ const mode = options === null || options === void 0 ? void 0 : options.mode;
1621
+ return {
1622
+ mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
1623
+ };
1624
+ }
1625
+ function convertReadableStreamReaderMode(mode, context) {
1626
+ mode = `${mode}`;
1627
+ if (mode !== 'byob') {
1628
+ throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
1629
+ }
1630
+ return mode;
1631
+ }
1632
+ function convertByobReadOptions(options, context) {
1633
+ var _a;
1634
+ assertDictionary(options, context);
1635
+ const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1;
1636
+ return {
1637
+ min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`)
1638
+ };
1639
+ }
1640
+
1364
1641
  // Abstract operations for the ReadableStream.
1365
1642
  function AcquireReadableStreamBYOBReader(stream) {
1366
1643
  return new ReadableStreamBYOBReader(stream);
@@ -1433,12 +1710,7 @@
1433
1710
  }
1434
1711
  return ReadableStreamReaderGenericCancel(this, reason);
1435
1712
  }
1436
- /**
1437
- * Attempts to reads bytes into view, and returns a promise resolved with the result.
1438
- *
1439
- * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
1440
- */
1441
- read(view) {
1713
+ read(view, rawOptions = {}) {
1442
1714
  if (!IsReadableStreamBYOBReader(this)) {
1443
1715
  return promiseRejectedWith(byobReaderBrandCheckException('read'));
1444
1716
  }
@@ -1451,7 +1723,28 @@
1451
1723
  if (view.buffer.byteLength === 0) {
1452
1724
  return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
1453
1725
  }
1454
- if (IsDetachedBuffer(view.buffer)) ;
1726
+ if (IsDetachedBuffer(view.buffer)) {
1727
+ return promiseRejectedWith(new TypeError('view\'s buffer has been detached'));
1728
+ }
1729
+ let options;
1730
+ try {
1731
+ options = convertByobReadOptions(rawOptions, 'options');
1732
+ }
1733
+ catch (e) {
1734
+ return promiseRejectedWith(e);
1735
+ }
1736
+ const min = options.min;
1737
+ if (min === 0) {
1738
+ return promiseRejectedWith(new TypeError('options.min must be greater than 0'));
1739
+ }
1740
+ if (!isDataView(view)) {
1741
+ if (min > view.length) {
1742
+ return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length'));
1743
+ }
1744
+ }
1745
+ else if (min > view.byteLength) {
1746
+ return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength'));
1747
+ }
1455
1748
  if (this._ownerReadableStream === undefined) {
1456
1749
  return promiseRejectedWith(readerLockException('read from'));
1457
1750
  }
@@ -1466,7 +1759,7 @@
1466
1759
  _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
1467
1760
  _errorSteps: e => rejectPromise(e)
1468
1761
  };
1469
- ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
1762
+ ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);
1470
1763
  return promise;
1471
1764
  }
1472
1765
  /**
@@ -1485,10 +1778,7 @@
1485
1778
  if (this._ownerReadableStream === undefined) {
1486
1779
  return;
1487
1780
  }
1488
- if (this._readIntoRequests.length > 0) {
1489
- throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
1490
- }
1491
- ReadableStreamReaderGenericRelease(this);
1781
+ ReadableStreamBYOBReaderRelease(this);
1492
1782
  }
1493
1783
  }
1494
1784
  Object.defineProperties(ReadableStreamBYOBReader.prototype, {
@@ -1497,6 +1787,9 @@
1497
1787
  releaseLock: { enumerable: true },
1498
1788
  closed: { enumerable: true }
1499
1789
  });
1790
+ setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');
1791
+ setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');
1792
+ setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');
1500
1793
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1501
1794
  Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
1502
1795
  value: 'ReadableStreamBYOBReader',
@@ -1513,16 +1806,28 @@
1513
1806
  }
1514
1807
  return x instanceof ReadableStreamBYOBReader;
1515
1808
  }
1516
- function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
1809
+ function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) {
1517
1810
  const stream = reader._ownerReadableStream;
1518
1811
  stream._disturbed = true;
1519
1812
  if (stream._state === 'errored') {
1520
1813
  readIntoRequest._errorSteps(stream._storedError);
1521
1814
  }
1522
1815
  else {
1523
- ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
1816
+ ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest);
1524
1817
  }
1525
1818
  }
1819
+ function ReadableStreamBYOBReaderRelease(reader) {
1820
+ ReadableStreamReaderGenericRelease(reader);
1821
+ const e = new TypeError('Reader was released');
1822
+ ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
1823
+ }
1824
+ function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) {
1825
+ const readIntoRequests = reader._readIntoRequests;
1826
+ reader._readIntoRequests = new SimpleQueue();
1827
+ readIntoRequests.forEach(readIntoRequest => {
1828
+ readIntoRequest._errorSteps(e);
1829
+ });
1830
+ }
1526
1831
  // Helper functions for the ReadableStreamBYOBReader.
1527
1832
  function byobReaderBrandCheckException(name) {
1528
1833
  return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
@@ -1723,6 +2028,9 @@
1723
2028
  getWriter: { enumerable: true },
1724
2029
  locked: { enumerable: true }
1725
2030
  });
2031
+ setFunctionName(WritableStream.prototype.abort, 'abort');
2032
+ setFunctionName(WritableStream.prototype.close, 'close');
2033
+ setFunctionName(WritableStream.prototype.getWriter, 'getWriter');
1726
2034
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1727
2035
  Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
1728
2036
  value: 'WritableStream',
@@ -1788,7 +2096,7 @@
1788
2096
  return promiseResolvedWith(undefined);
1789
2097
  }
1790
2098
  stream._writableStreamController._abortReason = reason;
1791
- (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort();
2099
+ (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason);
1792
2100
  // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',
1793
2101
  // but it doesn't know that signaling abort runs author code that might have changed the state.
1794
2102
  // Widen the type again by casting to WritableStreamState.
@@ -1893,9 +2201,11 @@
1893
2201
  uponPromise(promise, () => {
1894
2202
  abortRequest._resolve();
1895
2203
  WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2204
+ return null;
1896
2205
  }, (reason) => {
1897
2206
  abortRequest._reject(reason);
1898
2207
  WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2208
+ return null;
1899
2209
  });
1900
2210
  }
1901
2211
  function WritableStreamFinishInFlightWrite(stream) {
@@ -2123,6 +2433,10 @@
2123
2433
  desiredSize: { enumerable: true },
2124
2434
  ready: { enumerable: true }
2125
2435
  });
2436
+ setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');
2437
+ setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');
2438
+ setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');
2439
+ setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');
2126
2440
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2127
2441
  Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
2128
2442
  value: 'WritableStreamDefaultWriter',
@@ -2328,29 +2642,43 @@
2328
2642
  uponPromise(startPromise, () => {
2329
2643
  controller._started = true;
2330
2644
  WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2645
+ return null;
2331
2646
  }, r => {
2332
2647
  controller._started = true;
2333
2648
  WritableStreamDealWithRejection(stream, r);
2649
+ return null;
2334
2650
  });
2335
2651
  }
2336
2652
  function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
2337
2653
  const controller = Object.create(WritableStreamDefaultController.prototype);
2338
- let startAlgorithm = () => undefined;
2339
- let writeAlgorithm = () => promiseResolvedWith(undefined);
2340
- let closeAlgorithm = () => promiseResolvedWith(undefined);
2341
- let abortAlgorithm = () => promiseResolvedWith(undefined);
2654
+ let startAlgorithm;
2655
+ let writeAlgorithm;
2656
+ let closeAlgorithm;
2657
+ let abortAlgorithm;
2342
2658
  if (underlyingSink.start !== undefined) {
2343
2659
  startAlgorithm = () => underlyingSink.start(controller);
2344
2660
  }
2661
+ else {
2662
+ startAlgorithm = () => undefined;
2663
+ }
2345
2664
  if (underlyingSink.write !== undefined) {
2346
2665
  writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
2347
2666
  }
2667
+ else {
2668
+ writeAlgorithm = () => promiseResolvedWith(undefined);
2669
+ }
2348
2670
  if (underlyingSink.close !== undefined) {
2349
2671
  closeAlgorithm = () => underlyingSink.close();
2350
2672
  }
2673
+ else {
2674
+ closeAlgorithm = () => promiseResolvedWith(undefined);
2675
+ }
2351
2676
  if (underlyingSink.abort !== undefined) {
2352
2677
  abortAlgorithm = reason => underlyingSink.abort(reason);
2353
2678
  }
2679
+ else {
2680
+ abortAlgorithm = () => promiseResolvedWith(undefined);
2681
+ }
2354
2682
  SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
2355
2683
  }
2356
2684
  // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
@@ -2429,8 +2757,10 @@
2429
2757
  WritableStreamDefaultControllerClearAlgorithms(controller);
2430
2758
  uponPromise(sinkClosePromise, () => {
2431
2759
  WritableStreamFinishInFlightClose(stream);
2760
+ return null;
2432
2761
  }, reason => {
2433
2762
  WritableStreamFinishInFlightCloseWithError(stream, reason);
2763
+ return null;
2434
2764
  });
2435
2765
  }
2436
2766
  function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
@@ -2446,11 +2776,13 @@
2446
2776
  WritableStreamUpdateBackpressure(stream, backpressure);
2447
2777
  }
2448
2778
  WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2779
+ return null;
2449
2780
  }, reason => {
2450
2781
  if (stream._state === 'writable') {
2451
2782
  WritableStreamDefaultControllerClearAlgorithms(controller);
2452
2783
  }
2453
2784
  WritableStreamFinishInFlightWriteWithError(stream, reason);
2785
+ return null;
2454
2786
  });
2455
2787
  }
2456
2788
  function WritableStreamDefaultControllerGetBackpressure(controller) {
@@ -2557,13 +2889,28 @@
2557
2889
  }
2558
2890
 
2559
2891
  /// <reference lib="dom" />
2560
- const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
2892
+ function getGlobals() {
2893
+ if (typeof globalThis !== 'undefined') {
2894
+ return globalThis;
2895
+ }
2896
+ else if (typeof self !== 'undefined') {
2897
+ return self;
2898
+ }
2899
+ else if (typeof global !== 'undefined') {
2900
+ return global;
2901
+ }
2902
+ return undefined;
2903
+ }
2904
+ const globals = getGlobals();
2561
2905
 
2562
2906
  /// <reference types="node" />
2563
2907
  function isDOMExceptionConstructor(ctor) {
2564
2908
  if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
2565
2909
  return false;
2566
2910
  }
2911
+ if (ctor.name !== 'DOMException') {
2912
+ return false;
2913
+ }
2567
2914
  try {
2568
2915
  new ctor();
2569
2916
  return true;
@@ -2572,8 +2919,21 @@
2572
2919
  return false;
2573
2920
  }
2574
2921
  }
2575
- function createDOMExceptionPolyfill() {
2576
- // eslint-disable-next-line no-shadow
2922
+ /**
2923
+ * Support:
2924
+ * - Web browsers
2925
+ * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)
2926
+ */
2927
+ function getFromGlobal() {
2928
+ const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException;
2929
+ return isDOMExceptionConstructor(ctor) ? ctor : undefined;
2930
+ }
2931
+ /**
2932
+ * Support:
2933
+ * - All platforms
2934
+ */
2935
+ function createPolyfill() {
2936
+ // eslint-disable-next-line @typescript-eslint/no-shadow
2577
2937
  const ctor = function DOMException(message, name) {
2578
2938
  this.message = message || '';
2579
2939
  this.name = name || 'Error';
@@ -2581,12 +2941,13 @@
2581
2941
  Error.captureStackTrace(this, this.constructor);
2582
2942
  }
2583
2943
  };
2944
+ setFunctionName(ctor, 'DOMException');
2584
2945
  ctor.prototype = Object.create(Error.prototype);
2585
2946
  Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
2586
2947
  return ctor;
2587
2948
  }
2588
- // eslint-disable-next-line no-redeclare
2589
- const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
2949
+ // eslint-disable-next-line @typescript-eslint/no-redeclare
2950
+ const DOMException = getFromGlobal() || createPolyfill();
2590
2951
 
2591
2952
  function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
2592
2953
  const reader = AcquireReadableStreamDefaultReader(source);
@@ -2599,7 +2960,7 @@
2599
2960
  let abortAlgorithm;
2600
2961
  if (signal !== undefined) {
2601
2962
  abortAlgorithm = () => {
2602
- const error = new DOMException$1('Aborted', 'AbortError');
2963
+ const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');
2603
2964
  const actions = [];
2604
2965
  if (!preventAbort) {
2605
2966
  actions.push(() => {
@@ -2668,6 +3029,7 @@
2668
3029
  else {
2669
3030
  shutdown(true, storedError);
2670
3031
  }
3032
+ return null;
2671
3033
  });
2672
3034
  // Errors must be propagated backward
2673
3035
  isOrBecomesErrored(dest, writer._closedPromise, storedError => {
@@ -2677,6 +3039,7 @@
2677
3039
  else {
2678
3040
  shutdown(true, storedError);
2679
3041
  }
3042
+ return null;
2680
3043
  });
2681
3044
  // Closing must be propagated forward
2682
3045
  isOrBecomesClosed(source, reader._closedPromise, () => {
@@ -2686,6 +3049,7 @@
2686
3049
  else {
2687
3050
  shutdown();
2688
3051
  }
3052
+ return null;
2689
3053
  });
2690
3054
  // Closing must be propagated backward
2691
3055
  if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
@@ -2733,6 +3097,7 @@
2733
3097
  }
2734
3098
  function doTheRest() {
2735
3099
  uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
3100
+ return null;
2736
3101
  }
2737
3102
  }
2738
3103
  function shutdown(isError, error) {
@@ -2759,6 +3124,7 @@
2759
3124
  else {
2760
3125
  resolve(undefined);
2761
3126
  }
3127
+ return null;
2762
3128
  }
2763
3129
  });
2764
3130
  }
@@ -2839,6 +3205,10 @@
2839
3205
  ReadableStreamDefaultControllerCallPullIfNeeded(this);
2840
3206
  }
2841
3207
  }
3208
+ /** @internal */
3209
+ [ReleaseSteps]() {
3210
+ // Do nothing.
3211
+ }
2842
3212
  }
2843
3213
  Object.defineProperties(ReadableStreamDefaultController.prototype, {
2844
3214
  close: { enumerable: true },
@@ -2846,6 +3216,9 @@
2846
3216
  error: { enumerable: true },
2847
3217
  desiredSize: { enumerable: true }
2848
3218
  });
3219
+ setFunctionName(ReadableStreamDefaultController.prototype.close, 'close');
3220
+ setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');
3221
+ setFunctionName(ReadableStreamDefaultController.prototype.error, 'error');
2849
3222
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2850
3223
  Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
2851
3224
  value: 'ReadableStreamDefaultController',
@@ -2879,8 +3252,10 @@
2879
3252
  controller._pullAgain = false;
2880
3253
  ReadableStreamDefaultControllerCallPullIfNeeded(controller);
2881
3254
  }
3255
+ return null;
2882
3256
  }, e => {
2883
3257
  ReadableStreamDefaultControllerError(controller, e);
3258
+ return null;
2884
3259
  });
2885
3260
  }
2886
3261
  function ReadableStreamDefaultControllerShouldCallPull(controller) {
@@ -2995,24 +3370,35 @@
2995
3370
  uponPromise(promiseResolvedWith(startResult), () => {
2996
3371
  controller._started = true;
2997
3372
  ReadableStreamDefaultControllerCallPullIfNeeded(controller);
3373
+ return null;
2998
3374
  }, r => {
2999
3375
  ReadableStreamDefaultControllerError(controller, r);
3376
+ return null;
3000
3377
  });
3001
3378
  }
3002
3379
  function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
3003
3380
  const controller = Object.create(ReadableStreamDefaultController.prototype);
3004
- let startAlgorithm = () => undefined;
3005
- let pullAlgorithm = () => promiseResolvedWith(undefined);
3006
- let cancelAlgorithm = () => promiseResolvedWith(undefined);
3381
+ let startAlgorithm;
3382
+ let pullAlgorithm;
3383
+ let cancelAlgorithm;
3007
3384
  if (underlyingSource.start !== undefined) {
3008
3385
  startAlgorithm = () => underlyingSource.start(controller);
3009
3386
  }
3387
+ else {
3388
+ startAlgorithm = () => undefined;
3389
+ }
3010
3390
  if (underlyingSource.pull !== undefined) {
3011
3391
  pullAlgorithm = () => underlyingSource.pull(controller);
3012
3392
  }
3393
+ else {
3394
+ pullAlgorithm = () => promiseResolvedWith(undefined);
3395
+ }
3013
3396
  if (underlyingSource.cancel !== undefined) {
3014
3397
  cancelAlgorithm = reason => underlyingSource.cancel(reason);
3015
3398
  }
3399
+ else {
3400
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
3401
+ }
3016
3402
  SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
3017
3403
  }
3018
3404
  // Helper functions for the ReadableStreamDefaultController.
@@ -3051,7 +3437,7 @@
3051
3437
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3052
3438
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3053
3439
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3054
- queueMicrotask(() => {
3440
+ _queueMicrotask(() => {
3055
3441
  readAgain = false;
3056
3442
  const chunk1 = chunk;
3057
3443
  const chunk2 = chunk;
@@ -3122,6 +3508,7 @@
3122
3508
  if (!canceled1 || !canceled2) {
3123
3509
  resolveCancelPromise(undefined);
3124
3510
  }
3511
+ return null;
3125
3512
  });
3126
3513
  return [branch1, branch2];
3127
3514
  }
@@ -3143,13 +3530,14 @@
3143
3530
  function forwardReaderError(thisReader) {
3144
3531
  uponRejection(thisReader._closedPromise, r => {
3145
3532
  if (thisReader !== reader) {
3146
- return;
3533
+ return null;
3147
3534
  }
3148
3535
  ReadableByteStreamControllerError(branch1._readableStreamController, r);
3149
3536
  ReadableByteStreamControllerError(branch2._readableStreamController, r);
3150
3537
  if (!canceled1 || !canceled2) {
3151
3538
  resolveCancelPromise(undefined);
3152
3539
  }
3540
+ return null;
3153
3541
  });
3154
3542
  }
3155
3543
  function pullWithDefaultReader() {
@@ -3163,7 +3551,7 @@
3163
3551
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3164
3552
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3165
3553
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3166
- queueMicrotask(() => {
3554
+ _queueMicrotask(() => {
3167
3555
  readAgainForBranch1 = false;
3168
3556
  readAgainForBranch2 = false;
3169
3557
  const chunk1 = chunk;
@@ -3231,7 +3619,7 @@
3231
3619
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3232
3620
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3233
3621
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3234
- queueMicrotask(() => {
3622
+ _queueMicrotask(() => {
3235
3623
  readAgainForBranch1 = false;
3236
3624
  readAgainForBranch2 = false;
3237
3625
  const byobCanceled = forBranch2 ? canceled2 : canceled1;
@@ -3290,7 +3678,7 @@
3290
3678
  reading = false;
3291
3679
  }
3292
3680
  };
3293
- ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);
3681
+ ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);
3294
3682
  }
3295
3683
  function pull1Algorithm() {
3296
3684
  if (reading) {
@@ -3351,6 +3739,109 @@
3351
3739
  return [branch1, branch2];
3352
3740
  }
3353
3741
 
3742
+ function isReadableStreamLike(stream) {
3743
+ return typeIsObject(stream) && typeof stream.getReader !== 'undefined';
3744
+ }
3745
+
3746
+ function ReadableStreamFrom(source) {
3747
+ if (isReadableStreamLike(source)) {
3748
+ return ReadableStreamFromDefaultReader(source.getReader());
3749
+ }
3750
+ return ReadableStreamFromIterable(source);
3751
+ }
3752
+ function ReadableStreamFromIterable(asyncIterable) {
3753
+ let stream;
3754
+ const iteratorRecord = GetIterator(asyncIterable, 'async');
3755
+ const startAlgorithm = noop;
3756
+ function pullAlgorithm() {
3757
+ let nextResult;
3758
+ try {
3759
+ nextResult = IteratorNext(iteratorRecord);
3760
+ }
3761
+ catch (e) {
3762
+ return promiseRejectedWith(e);
3763
+ }
3764
+ const nextPromise = promiseResolvedWith(nextResult);
3765
+ return transformPromiseWith(nextPromise, iterResult => {
3766
+ if (!typeIsObject(iterResult)) {
3767
+ throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');
3768
+ }
3769
+ const done = IteratorComplete(iterResult);
3770
+ if (done) {
3771
+ ReadableStreamDefaultControllerClose(stream._readableStreamController);
3772
+ }
3773
+ else {
3774
+ const value = IteratorValue(iterResult);
3775
+ ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3776
+ }
3777
+ });
3778
+ }
3779
+ function cancelAlgorithm(reason) {
3780
+ const iterator = iteratorRecord.iterator;
3781
+ let returnMethod;
3782
+ try {
3783
+ returnMethod = GetMethod(iterator, 'return');
3784
+ }
3785
+ catch (e) {
3786
+ return promiseRejectedWith(e);
3787
+ }
3788
+ if (returnMethod === undefined) {
3789
+ return promiseResolvedWith(undefined);
3790
+ }
3791
+ let returnResult;
3792
+ try {
3793
+ returnResult = reflectCall(returnMethod, iterator, [reason]);
3794
+ }
3795
+ catch (e) {
3796
+ return promiseRejectedWith(e);
3797
+ }
3798
+ const returnPromise = promiseResolvedWith(returnResult);
3799
+ return transformPromiseWith(returnPromise, iterResult => {
3800
+ if (!typeIsObject(iterResult)) {
3801
+ throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');
3802
+ }
3803
+ return undefined;
3804
+ });
3805
+ }
3806
+ stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3807
+ return stream;
3808
+ }
3809
+ function ReadableStreamFromDefaultReader(reader) {
3810
+ let stream;
3811
+ const startAlgorithm = noop;
3812
+ function pullAlgorithm() {
3813
+ let readPromise;
3814
+ try {
3815
+ readPromise = reader.read();
3816
+ }
3817
+ catch (e) {
3818
+ return promiseRejectedWith(e);
3819
+ }
3820
+ return transformPromiseWith(readPromise, readResult => {
3821
+ if (!typeIsObject(readResult)) {
3822
+ throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');
3823
+ }
3824
+ if (readResult.done) {
3825
+ ReadableStreamDefaultControllerClose(stream._readableStreamController);
3826
+ }
3827
+ else {
3828
+ const value = readResult.value;
3829
+ ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3830
+ }
3831
+ });
3832
+ }
3833
+ function cancelAlgorithm(reason) {
3834
+ try {
3835
+ return promiseResolvedWith(reader.cancel(reason));
3836
+ }
3837
+ catch (e) {
3838
+ return promiseRejectedWith(e);
3839
+ }
3840
+ }
3841
+ stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3842
+ return stream;
3843
+ }
3844
+
3354
3845
  function convertUnderlyingDefaultOrByteSource(source, context) {
3355
3846
  assertDictionary(source, context);
3356
3847
  const original = source;
@@ -3395,21 +3886,6 @@
3395
3886
  return type;
3396
3887
  }
3397
3888
 
3398
- function convertReaderOptions(options, context) {
3399
- assertDictionary(options, context);
3400
- const mode = options === null || options === void 0 ? void 0 : options.mode;
3401
- return {
3402
- mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
3403
- };
3404
- }
3405
- function convertReadableStreamReaderMode(mode, context) {
3406
- mode = `${mode}`;
3407
- if (mode !== 'byob') {
3408
- throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
3409
- }
3410
- return mode;
3411
- }
3412
-
3413
3889
  function convertIteratorOptions(options, context) {
3414
3890
  assertDictionary(options, context);
3415
3891
  const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
@@ -3579,7 +4055,19 @@
3579
4055
  const options = convertIteratorOptions(rawOptions, 'First parameter');
3580
4056
  return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
3581
4057
  }
4058
+ /**
4059
+ * Creates a new ReadableStream wrapping the provided iterable or async iterable.
4060
+ *
4061
+ * This can be used to adapt various kinds of objects into a readable stream,
4062
+ * such as an array, an async generator, or a Node.js readable stream.
4063
+ */
4064
+ static from(asyncIterable) {
4065
+ return ReadableStreamFrom(asyncIterable);
4066
+ }
3582
4067
  }
4068
+ Object.defineProperties(ReadableStream, {
4069
+ from: { enumerable: true }
4070
+ });
3583
4071
  Object.defineProperties(ReadableStream.prototype, {
3584
4072
  cancel: { enumerable: true },
3585
4073
  getReader: { enumerable: true },
@@ -3589,6 +4077,13 @@
3589
4077
  values: { enumerable: true },
3590
4078
  locked: { enumerable: true }
3591
4079
  });
4080
+ setFunctionName(ReadableStream.from, 'from');
4081
+ setFunctionName(ReadableStream.prototype.cancel, 'cancel');
4082
+ setFunctionName(ReadableStream.prototype.getReader, 'getReader');
4083
+ setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');
4084
+ setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');
4085
+ setFunctionName(ReadableStream.prototype.tee, 'tee');
4086
+ setFunctionName(ReadableStream.prototype.values, 'values');
3592
4087
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
3593
4088
  Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {
3594
4089
  value: 'ReadableStream',
@@ -3652,10 +4147,11 @@
3652
4147
  ReadableStreamClose(stream);
3653
4148
  const reader = stream._reader;
3654
4149
  if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {
3655
- reader._readIntoRequests.forEach(readIntoRequest => {
4150
+ const readIntoRequests = reader._readIntoRequests;
4151
+ reader._readIntoRequests = new SimpleQueue();
4152
+ readIntoRequests.forEach(readIntoRequest => {
3656
4153
  readIntoRequest._closeSteps(undefined);
3657
4154
  });
3658
- reader._readIntoRequests = new SimpleQueue();
3659
4155
  }
3660
4156
  const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
3661
4157
  return transformPromiseWith(sourceCancelPromise, noop);
@@ -3668,10 +4164,11 @@
3668
4164
  }
3669
4165
  defaultReaderClosedPromiseResolve(reader);
3670
4166
  if (IsReadableStreamDefaultReader(reader)) {
3671
- reader._readRequests.forEach(readRequest => {
4167
+ const readRequests = reader._readRequests;
4168
+ reader._readRequests = new SimpleQueue();
4169
+ readRequests.forEach(readRequest => {
3672
4170
  readRequest._closeSteps();
3673
4171
  });
3674
- reader._readRequests = new SimpleQueue();
3675
4172
  }
3676
4173
  }
3677
4174
  function ReadableStreamError(stream, e) {
@@ -3683,16 +4180,10 @@
3683
4180
  }
3684
4181
  defaultReaderClosedPromiseReject(reader, e);
3685
4182
  if (IsReadableStreamDefaultReader(reader)) {
3686
- reader._readRequests.forEach(readRequest => {
3687
- readRequest._errorSteps(e);
3688
- });
3689
- reader._readRequests = new SimpleQueue();
4183
+ ReadableStreamDefaultReaderErrorReadRequests(reader, e);
3690
4184
  }
3691
4185
  else {
3692
- reader._readIntoRequests.forEach(readIntoRequest => {
3693
- readIntoRequest._errorSteps(e);
3694
- });
3695
- reader._readIntoRequests = new SimpleQueue();
4186
+ ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
3696
4187
  }
3697
4188
  }
3698
4189
  // Helper functions for the ReadableStream.
@@ -3713,10 +4204,7 @@
3713
4204
  const byteLengthSizeFunction = (chunk) => {
3714
4205
  return chunk.byteLength;
3715
4206
  };
3716
- Object.defineProperty(byteLengthSizeFunction, 'name', {
3717
- value: 'size',
3718
- configurable: true
3719
- });
4207
+ setFunctionName(byteLengthSizeFunction, 'size');
3720
4208
  /**
3721
4209
  * A queuing strategy that counts the number of bytes in each chunk.
3722
4210
  *
@@ -3775,10 +4263,7 @@
3775
4263
  const countSizeFunction = () => {
3776
4264
  return 1;
3777
4265
  };
3778
- Object.defineProperty(countSizeFunction, 'name', {
3779
- value: 'size',
3780
- configurable: true
3781
- });
4266
+ setFunctionName(countSizeFunction, 'size');
3782
4267
  /**
3783
4268
  * A queuing strategy that counts the number of chunks.
3784
4269
  *
@@ -3836,12 +4321,16 @@
3836
4321
 
3837
4322
  function convertTransformer(original, context) {
3838
4323
  assertDictionary(original, context);
4324
+ const cancel = original === null || original === void 0 ? void 0 : original.cancel;
3839
4325
  const flush = original === null || original === void 0 ? void 0 : original.flush;
3840
4326
  const readableType = original === null || original === void 0 ? void 0 : original.readableType;
3841
4327
  const start = original === null || original === void 0 ? void 0 : original.start;
3842
4328
  const transform = original === null || original === void 0 ? void 0 : original.transform;
3843
4329
  const writableType = original === null || original === void 0 ? void 0 : original.writableType;
3844
4330
  return {
4331
+ cancel: cancel === undefined ?
4332
+ undefined :
4333
+ convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`),
3845
4334
  flush: flush === undefined ?
3846
4335
  undefined :
3847
4336
  convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
@@ -3867,6 +4356,10 @@
3867
4356
  assertFunction(fn, context);
3868
4357
  return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
3869
4358
  }
4359
+ function convertTransformerCancelCallback(fn, original, context) {
4360
+ assertFunction(fn, context);
4361
+ return (reason) => promiseCall(fn, original, [reason]);
4362
+ }
3870
4363
 
3871
4364
  // Class TransformStream
3872
4365
  /**
@@ -3955,8 +4448,7 @@
3955
4448
  return TransformStreamDefaultSourcePullAlgorithm(stream);
3956
4449
  }
3957
4450
  function cancelAlgorithm(reason) {
3958
- TransformStreamErrorWritableAndUnblockWrite(stream, reason);
3959
- return promiseResolvedWith(undefined);
4451
+ return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);
3960
4452
  }
3961
4453
  stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
3962
4454
  // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
@@ -3983,6 +4475,9 @@
3983
4475
  function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
3984
4476
  TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
3985
4477
  WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
4478
+ TransformStreamUnblockWrite(stream);
4479
+ }
4480
+ function TransformStreamUnblockWrite(stream) {
3986
4481
  if (stream._backpressure) {
3987
4482
  // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
3988
4483
  // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
@@ -4053,6 +4548,9 @@
4053
4548
  terminate: { enumerable: true },
4054
4549
  desiredSize: { enumerable: true }
4055
4550
  });
4551
+ setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');
4552
+ setFunctionName(TransformStreamDefaultController.prototype.error, 'error');
4553
+ setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');
4056
4554
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4057
4555
  Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
4058
4556
  value: 'TransformStreamDefaultController',
@@ -4069,35 +4567,53 @@
4069
4567
  }
4070
4568
  return x instanceof TransformStreamDefaultController;
4071
4569
  }
4072
- function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
4570
+ function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
4073
4571
  controller._controlledTransformStream = stream;
4074
4572
  stream._transformStreamController = controller;
4075
4573
  controller._transformAlgorithm = transformAlgorithm;
4076
4574
  controller._flushAlgorithm = flushAlgorithm;
4575
+ controller._cancelAlgorithm = cancelAlgorithm;
4576
+ controller._finishPromise = undefined;
4577
+ controller._finishPromise_resolve = undefined;
4578
+ controller._finishPromise_reject = undefined;
4077
4579
  }
4078
4580
  function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
4079
4581
  const controller = Object.create(TransformStreamDefaultController.prototype);
4080
- let transformAlgorithm = (chunk) => {
4081
- try {
4082
- TransformStreamDefaultControllerEnqueue(controller, chunk);
4083
- return promiseResolvedWith(undefined);
4084
- }
4085
- catch (transformResultE) {
4086
- return promiseRejectedWith(transformResultE);
4087
- }
4088
- };
4089
- let flushAlgorithm = () => promiseResolvedWith(undefined);
4582
+ let transformAlgorithm;
4583
+ let flushAlgorithm;
4584
+ let cancelAlgorithm;
4090
4585
  if (transformer.transform !== undefined) {
4091
4586
  transformAlgorithm = chunk => transformer.transform(chunk, controller);
4092
4587
  }
4588
+ else {
4589
+ transformAlgorithm = chunk => {
4590
+ try {
4591
+ TransformStreamDefaultControllerEnqueue(controller, chunk);
4592
+ return promiseResolvedWith(undefined);
4593
+ }
4594
+ catch (transformResultE) {
4595
+ return promiseRejectedWith(transformResultE);
4596
+ }
4597
+ };
4598
+ }
4093
4599
  if (transformer.flush !== undefined) {
4094
4600
  flushAlgorithm = () => transformer.flush(controller);
4095
4601
  }
4096
- SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
4602
+ else {
4603
+ flushAlgorithm = () => promiseResolvedWith(undefined);
4604
+ }
4605
+ if (transformer.cancel !== undefined) {
4606
+ cancelAlgorithm = reason => transformer.cancel(reason);
4607
+ }
4608
+ else {
4609
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
4610
+ }
4611
+ SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);
4097
4612
  }
4098
4613
  function TransformStreamDefaultControllerClearAlgorithms(controller) {
4099
4614
  controller._transformAlgorithm = undefined;
4100
4615
  controller._flushAlgorithm = undefined;
4616
+ controller._cancelAlgorithm = undefined;
4101
4617
  }
4102
4618
  function TransformStreamDefaultControllerEnqueue(controller, chunk) {
4103
4619
  const stream = controller._controlledTransformStream;
@@ -4154,27 +4670,66 @@
4154
4670
  return TransformStreamDefaultControllerPerformTransform(controller, chunk);
4155
4671
  }
4156
4672
  function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
4157
- // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
4158
- // errored.
4159
- TransformStreamError(stream, reason);
4160
- return promiseResolvedWith(undefined);
4673
+ const controller = stream._transformStreamController;
4674
+ if (controller._finishPromise !== undefined) {
4675
+ return controller._finishPromise;
4676
+ }
4677
+ // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4678
+ const readable = stream._readable;
4679
+ // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,
4680
+ // we don't run the _cancelAlgorithm again.
4681
+ controller._finishPromise = newPromise((resolve, reject) => {
4682
+ controller._finishPromise_resolve = resolve;
4683
+ controller._finishPromise_reject = reject;
4684
+ });
4685
+ const cancelPromise = controller._cancelAlgorithm(reason);
4686
+ TransformStreamDefaultControllerClearAlgorithms(controller);
4687
+ uponPromise(cancelPromise, () => {
4688
+ if (readable._state === 'errored') {
4689
+ defaultControllerFinishPromiseReject(controller, readable._storedError);
4690
+ }
4691
+ else {
4692
+ ReadableStreamDefaultControllerError(readable._readableStreamController, reason);
4693
+ defaultControllerFinishPromiseResolve(controller);
4694
+ }
4695
+ return null;
4696
+ }, r => {
4697
+ ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4698
+ defaultControllerFinishPromiseReject(controller, r);
4699
+ return null;
4700
+ });
4701
+ return controller._finishPromise;
4161
4702
  }
4162
4703
  function TransformStreamDefaultSinkCloseAlgorithm(stream) {
4704
+ const controller = stream._transformStreamController;
4705
+ if (controller._finishPromise !== undefined) {
4706
+ return controller._finishPromise;
4707
+ }
4163
4708
  // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4164
4709
  const readable = stream._readable;
4165
- const controller = stream._transformStreamController;
4710
+ // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,
4711
+ // we don't also run the _cancelAlgorithm.
4712
+ controller._finishPromise = newPromise((resolve, reject) => {
4713
+ controller._finishPromise_resolve = resolve;
4714
+ controller._finishPromise_reject = reject;
4715
+ });
4166
4716
  const flushPromise = controller._flushAlgorithm();
4167
4717
  TransformStreamDefaultControllerClearAlgorithms(controller);
4168
- // Return a promise that is fulfilled with undefined on success.
4169
- return transformPromiseWith(flushPromise, () => {
4718
+ uponPromise(flushPromise, () => {
4170
4719
  if (readable._state === 'errored') {
4171
- throw readable._storedError;
4720
+ defaultControllerFinishPromiseReject(controller, readable._storedError);
4172
4721
  }
4173
- ReadableStreamDefaultControllerClose(readable._readableStreamController);
4722
+ else {
4723
+ ReadableStreamDefaultControllerClose(readable._readableStreamController);
4724
+ defaultControllerFinishPromiseResolve(controller);
4725
+ }
4726
+ return null;
4174
4727
  }, r => {
4175
- TransformStreamError(stream, r);
4176
- throw readable._storedError;
4728
+ ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4729
+ defaultControllerFinishPromiseReject(controller, r);
4730
+ return null;
4177
4731
  });
4732
+ return controller._finishPromise;
4178
4733
  }
4179
4734
  // TransformStreamDefaultSource Algorithms
4180
4735
  function TransformStreamDefaultSourcePullAlgorithm(stream) {
@@ -4183,10 +4738,61 @@
4183
4738
  // Prevent the next pull() call until there is backpressure.
4184
4739
  return stream._backpressureChangePromise;
4185
4740
  }
4741
+ function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) {
4742
+ const controller = stream._transformStreamController;
4743
+ if (controller._finishPromise !== undefined) {
4744
+ return controller._finishPromise;
4745
+ }
4746
+ // stream._writable cannot change after construction, so caching it across a call to user code is safe.
4747
+ const writable = stream._writable;
4748
+ // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or
4749
+ // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the
4750
+ // _flushAlgorithm.
4751
+ controller._finishPromise = newPromise((resolve, reject) => {
4752
+ controller._finishPromise_resolve = resolve;
4753
+ controller._finishPromise_reject = reject;
4754
+ });
4755
+ const cancelPromise = controller._cancelAlgorithm(reason);
4756
+ TransformStreamDefaultControllerClearAlgorithms(controller);
4757
+ uponPromise(cancelPromise, () => {
4758
+ if (writable._state === 'errored') {
4759
+ defaultControllerFinishPromiseReject(controller, writable._storedError);
4760
+ }
4761
+ else {
4762
+ WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);
4763
+ TransformStreamUnblockWrite(stream);
4764
+ defaultControllerFinishPromiseResolve(controller);
4765
+ }
4766
+ return null;
4767
+ }, r => {
4768
+ WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);
4769
+ TransformStreamUnblockWrite(stream);
4770
+ defaultControllerFinishPromiseReject(controller, r);
4771
+ return null;
4772
+ });
4773
+ return controller._finishPromise;
4774
+ }
4186
4775
  // Helper functions for the TransformStreamDefaultController.
4187
4776
  function defaultControllerBrandCheckException(name) {
4188
4777
  return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
4189
4778
  }
4779
+ function defaultControllerFinishPromiseResolve(controller) {
4780
+ if (controller._finishPromise_resolve === undefined) {
4781
+ return;
4782
+ }
4783
+ controller._finishPromise_resolve();
4784
+ controller._finishPromise_resolve = undefined;
4785
+ controller._finishPromise_reject = undefined;
4786
+ }
4787
+ function defaultControllerFinishPromiseReject(controller, reason) {
4788
+ if (controller._finishPromise_reject === undefined) {
4789
+ return;
4790
+ }
4791
+ setPromiseIsHandledToTrue(controller._finishPromise);
4792
+ controller._finishPromise_reject(reason);
4793
+ controller._finishPromise_resolve = undefined;
4794
+ controller._finishPromise_reject = undefined;
4795
+ }
4190
4796
  // Helper functions for the TransformStream.
4191
4797
  function streamBrandCheckException(name) {
4192
4798
  return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
@@ -4206,7 +4812,5 @@
4206
4812
  exports.WritableStreamDefaultController = WritableStreamDefaultController;
4207
4813
  exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
4208
4814
 
4209
- Object.defineProperty(exports, '__esModule', { value: true });
4210
-
4211
- })));
4815
+ }));
4212
4816
  //# sourceMappingURL=ponyfill.es6.js.map