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`);
@@ -544,9 +568,6 @@
544
568
  return Promise.resolve({ value: undefined, done: true });
545
569
  }
546
570
  const reader = this._reader;
547
- if (reader._ownerReadableStream === undefined) {
548
- return promiseRejectedWith(readerLockException('iterate'));
549
- }
550
571
  let resolvePromise;
551
572
  let rejectPromise;
552
573
  const promise = newPromise((resolve, reject) => {
@@ -558,7 +579,7 @@
558
579
  this._ongoingPromise = undefined;
559
580
  // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
560
581
  // FIXME Is this a bug in the specification, or in the test?
561
- queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
582
+ _queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
562
583
  },
563
584
  _closeSteps: () => {
564
585
  this._ongoingPromise = undefined;
@@ -582,9 +603,6 @@
582
603
  }
583
604
  this._isFinished = true;
584
605
  const reader = this._reader;
585
- if (reader._ownerReadableStream === undefined) {
586
- return promiseRejectedWith(readerLockException('finish iterating'));
587
- }
588
606
  if (!this._preventCancel) {
589
607
  const result = ReadableStreamReaderGenericCancel(reader, value);
590
608
  ReadableStreamReaderGenericRelease(reader);
@@ -655,15 +673,29 @@
655
673
  function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
656
674
  new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
657
675
  }
658
- // Not implemented correctly
659
- function TransferArrayBuffer(O) {
660
- return O;
661
- }
662
- // Not implemented correctly
663
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
664
- function IsDetachedBuffer(O) {
665
- return false;
666
- }
676
+ let TransferArrayBuffer = (O) => {
677
+ if (typeof O.transfer === 'function') {
678
+ TransferArrayBuffer = buffer => buffer.transfer();
679
+ }
680
+ else if (typeof structuredClone === 'function') {
681
+ TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });
682
+ }
683
+ else {
684
+ // Not implemented correctly
685
+ TransferArrayBuffer = buffer => buffer;
686
+ }
687
+ return TransferArrayBuffer(O);
688
+ };
689
+ let IsDetachedBuffer = (O) => {
690
+ if (typeof O.detached === 'boolean') {
691
+ IsDetachedBuffer = buffer => buffer.detached;
692
+ }
693
+ else {
694
+ // Not implemented correctly
695
+ IsDetachedBuffer = buffer => buffer.byteLength === 0;
696
+ }
697
+ return IsDetachedBuffer(O);
698
+ };
667
699
  function ArrayBufferSlice(buffer, begin, end) {
668
700
  // ArrayBuffer.prototype.slice is not available on IE10
669
701
  // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice
@@ -675,6 +707,68 @@
675
707
  CopyDataBlockBytes(slice, 0, buffer, begin, length);
676
708
  return slice;
677
709
  }
710
+ function GetMethod(receiver, prop) {
711
+ const func = receiver[prop];
712
+ if (func === undefined || func === null) {
713
+ return undefined;
714
+ }
715
+ if (typeof func !== 'function') {
716
+ throw new TypeError(`${String(prop)} is not a function`);
717
+ }
718
+ return func;
719
+ }
720
+ function CreateAsyncFromSyncIterator(syncIteratorRecord) {
721
+ // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,
722
+ // we use yield* inside an async generator function to achieve the same result.
723
+ // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.
724
+ const syncIterable = {
725
+ [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator
726
+ };
727
+ // Create an async generator function and immediately invoke it.
728
+ const asyncIterator = (async function* () {
729
+ return yield* syncIterable;
730
+ }());
731
+ // Return as an async iterator record.
732
+ const nextMethod = asyncIterator.next;
733
+ return { iterator: asyncIterator, nextMethod, done: false };
734
+ }
735
+ function GetIterator(obj, hint = 'sync', method) {
736
+ if (method === undefined) {
737
+ if (hint === 'async') {
738
+ method = GetMethod(obj, SymbolPolyfill.asyncIterator);
739
+ if (method === undefined) {
740
+ const syncMethod = GetMethod(obj, SymbolPolyfill.iterator);
741
+ const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod);
742
+ return CreateAsyncFromSyncIterator(syncIteratorRecord);
743
+ }
744
+ }
745
+ else {
746
+ method = GetMethod(obj, SymbolPolyfill.iterator);
747
+ }
748
+ }
749
+ if (method === undefined) {
750
+ throw new TypeError('The object is not iterable');
751
+ }
752
+ const iterator = reflectCall(method, obj, []);
753
+ if (!typeIsObject(iterator)) {
754
+ throw new TypeError('The iterator method must return an object');
755
+ }
756
+ const nextMethod = iterator.next;
757
+ return { iterator, nextMethod, done: false };
758
+ }
759
+ function IteratorNext(iteratorRecord) {
760
+ const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);
761
+ if (!typeIsObject(result)) {
762
+ throw new TypeError('The iterator.next() method must return an object');
763
+ }
764
+ return result;
765
+ }
766
+ function IteratorComplete(iterResult) {
767
+ return Boolean(iterResult.done);
768
+ }
769
+ function IteratorValue(iterResult) {
770
+ return iterResult.value;
771
+ }
678
772
 
679
773
  function IsNonNegativeNumber(v) {
680
774
  if (typeof v !== 'number') {
@@ -717,6 +811,19 @@
717
811
  container._queueTotalSize = 0;
718
812
  }
719
813
 
814
+ function isDataViewConstructor(ctor) {
815
+ return ctor === DataView;
816
+ }
817
+ function isDataView(view) {
818
+ return isDataViewConstructor(view.constructor);
819
+ }
820
+ function arrayBufferViewElementSize(ctor) {
821
+ if (isDataViewConstructor(ctor)) {
822
+ return 1;
823
+ }
824
+ return ctor.BYTES_PER_ELEMENT;
825
+ }
826
+
720
827
  /**
721
828
  * A pull-into request in a {@link ReadableByteStreamController}.
722
829
  *
@@ -744,7 +851,9 @@
744
851
  if (this._associatedReadableByteStreamController === undefined) {
745
852
  throw new TypeError('This BYOB request has been invalidated');
746
853
  }
747
- if (IsDetachedBuffer(this._view.buffer)) ;
854
+ if (IsDetachedBuffer(this._view.buffer)) {
855
+ throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);
856
+ }
748
857
  ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
749
858
  }
750
859
  respondWithNewView(view) {
@@ -758,7 +867,9 @@
758
867
  if (this._associatedReadableByteStreamController === undefined) {
759
868
  throw new TypeError('This BYOB request has been invalidated');
760
869
  }
761
- if (IsDetachedBuffer(view.buffer)) ;
870
+ if (IsDetachedBuffer(view.buffer)) {
871
+ throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response');
872
+ }
762
873
  ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
763
874
  }
764
875
  }
@@ -767,6 +878,8 @@
767
878
  respondWithNewView: { enumerable: true },
768
879
  view: { enumerable: true }
769
880
  });
881
+ setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');
882
+ setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');
770
883
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
771
884
  Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
772
885
  value: 'ReadableStreamBYOBRequest',
@@ -862,11 +975,7 @@
862
975
  [PullSteps](readRequest) {
863
976
  const stream = this._controlledReadableByteStream;
864
977
  if (this._queueTotalSize > 0) {
865
- const entry = this._queue.shift();
866
- this._queueTotalSize -= entry.byteLength;
867
- ReadableByteStreamControllerHandleQueueDrain(this);
868
- const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
869
- readRequest._chunkSteps(view);
978
+ ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);
870
979
  return;
871
980
  }
872
981
  const autoAllocateChunkSize = this._autoAllocateChunkSize;
@@ -885,6 +994,7 @@
885
994
  byteOffset: 0,
886
995
  byteLength: autoAllocateChunkSize,
887
996
  bytesFilled: 0,
997
+ minimumFill: 1,
888
998
  elementSize: 1,
889
999
  viewConstructor: Uint8Array,
890
1000
  readerType: 'default'
@@ -894,6 +1004,15 @@
894
1004
  ReadableStreamAddReadRequest(stream, readRequest);
895
1005
  ReadableByteStreamControllerCallPullIfNeeded(this);
896
1006
  }
1007
+ /** @internal */
1008
+ [ReleaseSteps]() {
1009
+ if (this._pendingPullIntos.length > 0) {
1010
+ const firstPullInto = this._pendingPullIntos.peek();
1011
+ firstPullInto.readerType = 'none';
1012
+ this._pendingPullIntos = new SimpleQueue();
1013
+ this._pendingPullIntos.push(firstPullInto);
1014
+ }
1015
+ }
897
1016
  }
898
1017
  Object.defineProperties(ReadableByteStreamController.prototype, {
899
1018
  close: { enumerable: true },
@@ -902,6 +1021,9 @@
902
1021
  byobRequest: { enumerable: true },
903
1022
  desiredSize: { enumerable: true }
904
1023
  });
1024
+ setFunctionName(ReadableByteStreamController.prototype.close, 'close');
1025
+ setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');
1026
+ setFunctionName(ReadableByteStreamController.prototype.error, 'error');
905
1027
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
906
1028
  Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
907
1029
  value: 'ReadableByteStreamController',
@@ -945,8 +1067,10 @@
945
1067
  controller._pullAgain = false;
946
1068
  ReadableByteStreamControllerCallPullIfNeeded(controller);
947
1069
  }
1070
+ return null;
948
1071
  }, e => {
949
1072
  ReadableByteStreamControllerError(controller, e);
1073
+ return null;
950
1074
  });
951
1075
  }
952
1076
  function ReadableByteStreamControllerClearPendingPullIntos(controller) {
@@ -975,15 +1099,33 @@
975
1099
  controller._queue.push({ buffer, byteOffset, byteLength });
976
1100
  controller._queueTotalSize += byteLength;
977
1101
  }
1102
+ function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) {
1103
+ let clonedChunk;
1104
+ try {
1105
+ clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);
1106
+ }
1107
+ catch (cloneE) {
1108
+ ReadableByteStreamControllerError(controller, cloneE);
1109
+ throw cloneE;
1110
+ }
1111
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);
1112
+ }
1113
+ function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) {
1114
+ if (firstDescriptor.bytesFilled > 0) {
1115
+ ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled);
1116
+ }
1117
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
1118
+ }
978
1119
  function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
979
- const elementSize = pullIntoDescriptor.elementSize;
980
- const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
981
1120
  const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
982
1121
  const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
983
- const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
984
1122
  let totalBytesToCopyRemaining = maxBytesToCopy;
985
1123
  let ready = false;
986
- if (maxAlignedBytes > currentAlignedBytes) {
1124
+ const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;
1125
+ const maxAlignedBytes = maxBytesFilled - remainderBytes;
1126
+ // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1127
+ // of the queue, so the underlying source can keep filling it.
1128
+ if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {
987
1129
  totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
988
1130
  ready = true;
989
1131
  }
@@ -1038,25 +1180,37 @@
1038
1180
  }
1039
1181
  }
1040
1182
  }
1041
- function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
1042
- const stream = controller._controlledReadableByteStream;
1043
- let elementSize = 1;
1044
- if (view.constructor !== DataView) {
1045
- elementSize = view.constructor.BYTES_PER_ELEMENT;
1183
+ function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) {
1184
+ const reader = controller._controlledReadableByteStream._reader;
1185
+ while (reader._readRequests.length > 0) {
1186
+ if (controller._queueTotalSize === 0) {
1187
+ return;
1188
+ }
1189
+ const readRequest = reader._readRequests.shift();
1190
+ ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);
1046
1191
  }
1192
+ }
1193
+ function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) {
1194
+ const stream = controller._controlledReadableByteStream;
1047
1195
  const ctor = view.constructor;
1048
- // try {
1049
- const buffer = TransferArrayBuffer(view.buffer);
1050
- // } catch (e) {
1051
- // readIntoRequest._errorSteps(e);
1052
- // return;
1053
- // }
1196
+ const elementSize = arrayBufferViewElementSize(ctor);
1197
+ const { byteOffset, byteLength } = view;
1198
+ const minimumFill = min * elementSize;
1199
+ let buffer;
1200
+ try {
1201
+ buffer = TransferArrayBuffer(view.buffer);
1202
+ }
1203
+ catch (e) {
1204
+ readIntoRequest._errorSteps(e);
1205
+ return;
1206
+ }
1054
1207
  const pullIntoDescriptor = {
1055
1208
  buffer,
1056
1209
  bufferByteLength: buffer.byteLength,
1057
- byteOffset: view.byteOffset,
1058
- byteLength: view.byteLength,
1210
+ byteOffset,
1211
+ byteLength,
1059
1212
  bytesFilled: 0,
1213
+ minimumFill,
1060
1214
  elementSize,
1061
1215
  viewConstructor: ctor,
1062
1216
  readerType: 'byob'
@@ -1093,6 +1247,9 @@
1093
1247
  ReadableByteStreamControllerCallPullIfNeeded(controller);
1094
1248
  }
1095
1249
  function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
1250
+ if (firstDescriptor.readerType === 'none') {
1251
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
1252
+ }
1096
1253
  const stream = controller._controlledReadableByteStream;
1097
1254
  if (ReadableStreamHasBYOBReader(stream)) {
1098
1255
  while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
@@ -1103,15 +1260,21 @@
1103
1260
  }
1104
1261
  function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
1105
1262
  ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
1106
- if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
1263
+ if (pullIntoDescriptor.readerType === 'none') {
1264
+ ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);
1265
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1266
+ return;
1267
+ }
1268
+ if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {
1269
+ // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1270
+ // of the queue, so the underlying source can keep filling it.
1107
1271
  return;
1108
1272
  }
1109
1273
  ReadableByteStreamControllerShiftPendingPullInto(controller);
1110
1274
  const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
1111
1275
  if (remainderSize > 0) {
1112
1276
  const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
1113
- const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);
1114
- ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
1277
+ ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize);
1115
1278
  }
1116
1279
  pullIntoDescriptor.bytesFilled -= remainderSize;
1117
1280
  ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
@@ -1122,7 +1285,7 @@
1122
1285
  ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1123
1286
  const state = controller._controlledReadableByteStream._state;
1124
1287
  if (state === 'closed') {
1125
- ReadableByteStreamControllerRespondInClosedState(controller);
1288
+ ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
1126
1289
  }
1127
1290
  else {
1128
1291
  ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
@@ -1172,7 +1335,7 @@
1172
1335
  }
1173
1336
  if (controller._pendingPullIntos.length > 0) {
1174
1337
  const firstPendingPullInto = controller._pendingPullIntos.peek();
1175
- if (firstPendingPullInto.bytesFilled > 0) {
1338
+ if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {
1176
1339
  const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
1177
1340
  ReadableByteStreamControllerError(controller, e);
1178
1341
  throw e;
@@ -1186,17 +1349,24 @@
1186
1349
  if (controller._closeRequested || stream._state !== 'readable') {
1187
1350
  return;
1188
1351
  }
1189
- const buffer = chunk.buffer;
1190
- const byteOffset = chunk.byteOffset;
1191
- const byteLength = chunk.byteLength;
1352
+ const { buffer, byteOffset, byteLength } = chunk;
1353
+ if (IsDetachedBuffer(buffer)) {
1354
+ throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued');
1355
+ }
1192
1356
  const transferredBuffer = TransferArrayBuffer(buffer);
1193
1357
  if (controller._pendingPullIntos.length > 0) {
1194
1358
  const firstPendingPullInto = controller._pendingPullIntos.peek();
1195
- if (IsDetachedBuffer(firstPendingPullInto.buffer)) ;
1359
+ if (IsDetachedBuffer(firstPendingPullInto.buffer)) {
1360
+ throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk');
1361
+ }
1362
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1196
1363
  firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
1364
+ if (firstPendingPullInto.readerType === 'none') {
1365
+ ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);
1366
+ }
1197
1367
  }
1198
- ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1199
1368
  if (ReadableStreamHasDefaultReader(stream)) {
1369
+ ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
1200
1370
  if (ReadableStreamGetNumReadRequests(stream) === 0) {
1201
1371
  ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1202
1372
  }
@@ -1228,6 +1398,13 @@
1228
1398
  ReadableByteStreamControllerClearAlgorithms(controller);
1229
1399
  ReadableStreamError(stream, e);
1230
1400
  }
1401
+ function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
1402
+ const entry = controller._queue.shift();
1403
+ controller._queueTotalSize -= entry.byteLength;
1404
+ ReadableByteStreamControllerHandleQueueDrain(controller);
1405
+ const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
1406
+ readRequest._chunkSteps(view);
1407
+ }
1231
1408
  function ReadableByteStreamControllerGetBYOBRequest(controller) {
1232
1409
  if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
1233
1410
  const firstDescriptor = controller._pendingPullIntos.peek();
@@ -1313,24 +1490,35 @@
1313
1490
  uponPromise(promiseResolvedWith(startResult), () => {
1314
1491
  controller._started = true;
1315
1492
  ReadableByteStreamControllerCallPullIfNeeded(controller);
1493
+ return null;
1316
1494
  }, r => {
1317
1495
  ReadableByteStreamControllerError(controller, r);
1496
+ return null;
1318
1497
  });
1319
1498
  }
1320
1499
  function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
1321
1500
  const controller = Object.create(ReadableByteStreamController.prototype);
1322
- let startAlgorithm = () => undefined;
1323
- let pullAlgorithm = () => promiseResolvedWith(undefined);
1324
- let cancelAlgorithm = () => promiseResolvedWith(undefined);
1501
+ let startAlgorithm;
1502
+ let pullAlgorithm;
1503
+ let cancelAlgorithm;
1325
1504
  if (underlyingByteSource.start !== undefined) {
1326
1505
  startAlgorithm = () => underlyingByteSource.start(controller);
1327
1506
  }
1507
+ else {
1508
+ startAlgorithm = () => undefined;
1509
+ }
1328
1510
  if (underlyingByteSource.pull !== undefined) {
1329
1511
  pullAlgorithm = () => underlyingByteSource.pull(controller);
1330
1512
  }
1513
+ else {
1514
+ pullAlgorithm = () => promiseResolvedWith(undefined);
1515
+ }
1331
1516
  if (underlyingByteSource.cancel !== undefined) {
1332
1517
  cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
1333
1518
  }
1519
+ else {
1520
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
1521
+ }
1334
1522
  const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
1335
1523
  if (autoAllocateChunkSize === 0) {
1336
1524
  throw new TypeError('autoAllocateChunkSize must be greater than 0');
@@ -1350,6 +1538,29 @@
1350
1538
  return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
1351
1539
  }
1352
1540
 
1541
+ function convertReaderOptions(options, context) {
1542
+ assertDictionary(options, context);
1543
+ const mode = options === null || options === void 0 ? void 0 : options.mode;
1544
+ return {
1545
+ mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
1546
+ };
1547
+ }
1548
+ function convertReadableStreamReaderMode(mode, context) {
1549
+ mode = `${mode}`;
1550
+ if (mode !== 'byob') {
1551
+ throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
1552
+ }
1553
+ return mode;
1554
+ }
1555
+ function convertByobReadOptions(options, context) {
1556
+ var _a;
1557
+ assertDictionary(options, context);
1558
+ const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1;
1559
+ return {
1560
+ min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`)
1561
+ };
1562
+ }
1563
+
1353
1564
  // Abstract operations for the ReadableStream.
1354
1565
  function AcquireReadableStreamBYOBReader(stream) {
1355
1566
  return new ReadableStreamBYOBReader(stream);
@@ -1422,12 +1633,7 @@
1422
1633
  }
1423
1634
  return ReadableStreamReaderGenericCancel(this, reason);
1424
1635
  }
1425
- /**
1426
- * Attempts to reads bytes into view, and returns a promise resolved with the result.
1427
- *
1428
- * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
1429
- */
1430
- read(view) {
1636
+ read(view, rawOptions = {}) {
1431
1637
  if (!IsReadableStreamBYOBReader(this)) {
1432
1638
  return promiseRejectedWith(byobReaderBrandCheckException('read'));
1433
1639
  }
@@ -1440,7 +1646,28 @@
1440
1646
  if (view.buffer.byteLength === 0) {
1441
1647
  return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
1442
1648
  }
1443
- if (IsDetachedBuffer(view.buffer)) ;
1649
+ if (IsDetachedBuffer(view.buffer)) {
1650
+ return promiseRejectedWith(new TypeError('view\'s buffer has been detached'));
1651
+ }
1652
+ let options;
1653
+ try {
1654
+ options = convertByobReadOptions(rawOptions, 'options');
1655
+ }
1656
+ catch (e) {
1657
+ return promiseRejectedWith(e);
1658
+ }
1659
+ const min = options.min;
1660
+ if (min === 0) {
1661
+ return promiseRejectedWith(new TypeError('options.min must be greater than 0'));
1662
+ }
1663
+ if (!isDataView(view)) {
1664
+ if (min > view.length) {
1665
+ return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length'));
1666
+ }
1667
+ }
1668
+ else if (min > view.byteLength) {
1669
+ return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength'));
1670
+ }
1444
1671
  if (this._ownerReadableStream === undefined) {
1445
1672
  return promiseRejectedWith(readerLockException('read from'));
1446
1673
  }
@@ -1455,7 +1682,7 @@
1455
1682
  _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
1456
1683
  _errorSteps: e => rejectPromise(e)
1457
1684
  };
1458
- ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
1685
+ ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);
1459
1686
  return promise;
1460
1687
  }
1461
1688
  /**
@@ -1474,10 +1701,7 @@
1474
1701
  if (this._ownerReadableStream === undefined) {
1475
1702
  return;
1476
1703
  }
1477
- if (this._readIntoRequests.length > 0) {
1478
- throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
1479
- }
1480
- ReadableStreamReaderGenericRelease(this);
1704
+ ReadableStreamBYOBReaderRelease(this);
1481
1705
  }
1482
1706
  }
1483
1707
  Object.defineProperties(ReadableStreamBYOBReader.prototype, {
@@ -1486,6 +1710,9 @@
1486
1710
  releaseLock: { enumerable: true },
1487
1711
  closed: { enumerable: true }
1488
1712
  });
1713
+ setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');
1714
+ setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');
1715
+ setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');
1489
1716
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1490
1717
  Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
1491
1718
  value: 'ReadableStreamBYOBReader',
@@ -1502,16 +1729,28 @@
1502
1729
  }
1503
1730
  return x instanceof ReadableStreamBYOBReader;
1504
1731
  }
1505
- function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
1732
+ function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) {
1506
1733
  const stream = reader._ownerReadableStream;
1507
1734
  stream._disturbed = true;
1508
1735
  if (stream._state === 'errored') {
1509
1736
  readIntoRequest._errorSteps(stream._storedError);
1510
1737
  }
1511
1738
  else {
1512
- ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
1739
+ ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest);
1513
1740
  }
1514
1741
  }
1742
+ function ReadableStreamBYOBReaderRelease(reader) {
1743
+ ReadableStreamReaderGenericRelease(reader);
1744
+ const e = new TypeError('Reader was released');
1745
+ ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
1746
+ }
1747
+ function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) {
1748
+ const readIntoRequests = reader._readIntoRequests;
1749
+ reader._readIntoRequests = new SimpleQueue();
1750
+ readIntoRequests.forEach(readIntoRequest => {
1751
+ readIntoRequest._errorSteps(e);
1752
+ });
1753
+ }
1515
1754
  // Helper functions for the ReadableStreamBYOBReader.
1516
1755
  function byobReaderBrandCheckException(name) {
1517
1756
  return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
@@ -1712,6 +1951,9 @@
1712
1951
  getWriter: { enumerable: true },
1713
1952
  locked: { enumerable: true }
1714
1953
  });
1954
+ setFunctionName(WritableStream.prototype.abort, 'abort');
1955
+ setFunctionName(WritableStream.prototype.close, 'close');
1956
+ setFunctionName(WritableStream.prototype.getWriter, 'getWriter');
1715
1957
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1716
1958
  Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
1717
1959
  value: 'WritableStream',
@@ -1777,7 +2019,7 @@
1777
2019
  return promiseResolvedWith(undefined);
1778
2020
  }
1779
2021
  stream._writableStreamController._abortReason = reason;
1780
- (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort();
2022
+ (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason);
1781
2023
  // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',
1782
2024
  // but it doesn't know that signaling abort runs author code that might have changed the state.
1783
2025
  // Widen the type again by casting to WritableStreamState.
@@ -1882,9 +2124,11 @@
1882
2124
  uponPromise(promise, () => {
1883
2125
  abortRequest._resolve();
1884
2126
  WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2127
+ return null;
1885
2128
  }, (reason) => {
1886
2129
  abortRequest._reject(reason);
1887
2130
  WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2131
+ return null;
1888
2132
  });
1889
2133
  }
1890
2134
  function WritableStreamFinishInFlightWrite(stream) {
@@ -2112,6 +2356,10 @@
2112
2356
  desiredSize: { enumerable: true },
2113
2357
  ready: { enumerable: true }
2114
2358
  });
2359
+ setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');
2360
+ setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');
2361
+ setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');
2362
+ setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');
2115
2363
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2116
2364
  Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
2117
2365
  value: 'WritableStreamDefaultWriter',
@@ -2317,29 +2565,43 @@
2317
2565
  uponPromise(startPromise, () => {
2318
2566
  controller._started = true;
2319
2567
  WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2568
+ return null;
2320
2569
  }, r => {
2321
2570
  controller._started = true;
2322
2571
  WritableStreamDealWithRejection(stream, r);
2572
+ return null;
2323
2573
  });
2324
2574
  }
2325
2575
  function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
2326
2576
  const controller = Object.create(WritableStreamDefaultController.prototype);
2327
- let startAlgorithm = () => undefined;
2328
- let writeAlgorithm = () => promiseResolvedWith(undefined);
2329
- let closeAlgorithm = () => promiseResolvedWith(undefined);
2330
- let abortAlgorithm = () => promiseResolvedWith(undefined);
2577
+ let startAlgorithm;
2578
+ let writeAlgorithm;
2579
+ let closeAlgorithm;
2580
+ let abortAlgorithm;
2331
2581
  if (underlyingSink.start !== undefined) {
2332
2582
  startAlgorithm = () => underlyingSink.start(controller);
2333
2583
  }
2584
+ else {
2585
+ startAlgorithm = () => undefined;
2586
+ }
2334
2587
  if (underlyingSink.write !== undefined) {
2335
2588
  writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
2336
2589
  }
2590
+ else {
2591
+ writeAlgorithm = () => promiseResolvedWith(undefined);
2592
+ }
2337
2593
  if (underlyingSink.close !== undefined) {
2338
2594
  closeAlgorithm = () => underlyingSink.close();
2339
2595
  }
2596
+ else {
2597
+ closeAlgorithm = () => promiseResolvedWith(undefined);
2598
+ }
2340
2599
  if (underlyingSink.abort !== undefined) {
2341
2600
  abortAlgorithm = reason => underlyingSink.abort(reason);
2342
2601
  }
2602
+ else {
2603
+ abortAlgorithm = () => promiseResolvedWith(undefined);
2604
+ }
2343
2605
  SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
2344
2606
  }
2345
2607
  // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
@@ -2418,8 +2680,10 @@
2418
2680
  WritableStreamDefaultControllerClearAlgorithms(controller);
2419
2681
  uponPromise(sinkClosePromise, () => {
2420
2682
  WritableStreamFinishInFlightClose(stream);
2683
+ return null;
2421
2684
  }, reason => {
2422
2685
  WritableStreamFinishInFlightCloseWithError(stream, reason);
2686
+ return null;
2423
2687
  });
2424
2688
  }
2425
2689
  function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
@@ -2435,11 +2699,13 @@
2435
2699
  WritableStreamUpdateBackpressure(stream, backpressure);
2436
2700
  }
2437
2701
  WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2702
+ return null;
2438
2703
  }, reason => {
2439
2704
  if (stream._state === 'writable') {
2440
2705
  WritableStreamDefaultControllerClearAlgorithms(controller);
2441
2706
  }
2442
2707
  WritableStreamFinishInFlightWriteWithError(stream, reason);
2708
+ return null;
2443
2709
  });
2444
2710
  }
2445
2711
  function WritableStreamDefaultControllerGetBackpressure(controller) {
@@ -2546,13 +2812,28 @@
2546
2812
  }
2547
2813
 
2548
2814
  /// <reference lib="dom" />
2549
- const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
2815
+ function getGlobals() {
2816
+ if (typeof globalThis !== 'undefined') {
2817
+ return globalThis;
2818
+ }
2819
+ else if (typeof self !== 'undefined') {
2820
+ return self;
2821
+ }
2822
+ else if (typeof global !== 'undefined') {
2823
+ return global;
2824
+ }
2825
+ return undefined;
2826
+ }
2827
+ const globals = getGlobals();
2550
2828
 
2551
2829
  /// <reference types="node" />
2552
2830
  function isDOMExceptionConstructor(ctor) {
2553
2831
  if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
2554
2832
  return false;
2555
2833
  }
2834
+ if (ctor.name !== 'DOMException') {
2835
+ return false;
2836
+ }
2556
2837
  try {
2557
2838
  new ctor();
2558
2839
  return true;
@@ -2561,8 +2842,21 @@
2561
2842
  return false;
2562
2843
  }
2563
2844
  }
2564
- function createDOMExceptionPolyfill() {
2565
- // eslint-disable-next-line no-shadow
2845
+ /**
2846
+ * Support:
2847
+ * - Web browsers
2848
+ * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)
2849
+ */
2850
+ function getFromGlobal() {
2851
+ const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException;
2852
+ return isDOMExceptionConstructor(ctor) ? ctor : undefined;
2853
+ }
2854
+ /**
2855
+ * Support:
2856
+ * - All platforms
2857
+ */
2858
+ function createPolyfill() {
2859
+ // eslint-disable-next-line @typescript-eslint/no-shadow
2566
2860
  const ctor = function DOMException(message, name) {
2567
2861
  this.message = message || '';
2568
2862
  this.name = name || 'Error';
@@ -2570,12 +2864,13 @@
2570
2864
  Error.captureStackTrace(this, this.constructor);
2571
2865
  }
2572
2866
  };
2867
+ setFunctionName(ctor, 'DOMException');
2573
2868
  ctor.prototype = Object.create(Error.prototype);
2574
2869
  Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
2575
2870
  return ctor;
2576
2871
  }
2577
- // eslint-disable-next-line no-redeclare
2578
- const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
2872
+ // eslint-disable-next-line @typescript-eslint/no-redeclare
2873
+ const DOMException = getFromGlobal() || createPolyfill();
2579
2874
 
2580
2875
  function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
2581
2876
  const reader = AcquireReadableStreamDefaultReader(source);
@@ -2588,7 +2883,7 @@
2588
2883
  let abortAlgorithm;
2589
2884
  if (signal !== undefined) {
2590
2885
  abortAlgorithm = () => {
2591
- const error = new DOMException$1('Aborted', 'AbortError');
2886
+ const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');
2592
2887
  const actions = [];
2593
2888
  if (!preventAbort) {
2594
2889
  actions.push(() => {
@@ -2657,6 +2952,7 @@
2657
2952
  else {
2658
2953
  shutdown(true, storedError);
2659
2954
  }
2955
+ return null;
2660
2956
  });
2661
2957
  // Errors must be propagated backward
2662
2958
  isOrBecomesErrored(dest, writer._closedPromise, storedError => {
@@ -2666,6 +2962,7 @@
2666
2962
  else {
2667
2963
  shutdown(true, storedError);
2668
2964
  }
2965
+ return null;
2669
2966
  });
2670
2967
  // Closing must be propagated forward
2671
2968
  isOrBecomesClosed(source, reader._closedPromise, () => {
@@ -2675,6 +2972,7 @@
2675
2972
  else {
2676
2973
  shutdown();
2677
2974
  }
2975
+ return null;
2678
2976
  });
2679
2977
  // Closing must be propagated backward
2680
2978
  if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
@@ -2722,6 +3020,7 @@
2722
3020
  }
2723
3021
  function doTheRest() {
2724
3022
  uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
3023
+ return null;
2725
3024
  }
2726
3025
  }
2727
3026
  function shutdown(isError, error) {
@@ -2748,6 +3047,7 @@
2748
3047
  else {
2749
3048
  resolve(undefined);
2750
3049
  }
3050
+ return null;
2751
3051
  }
2752
3052
  });
2753
3053
  }
@@ -2828,6 +3128,10 @@
2828
3128
  ReadableStreamDefaultControllerCallPullIfNeeded(this);
2829
3129
  }
2830
3130
  }
3131
+ /** @internal */
3132
+ [ReleaseSteps]() {
3133
+ // Do nothing.
3134
+ }
2831
3135
  }
2832
3136
  Object.defineProperties(ReadableStreamDefaultController.prototype, {
2833
3137
  close: { enumerable: true },
@@ -2835,6 +3139,9 @@
2835
3139
  error: { enumerable: true },
2836
3140
  desiredSize: { enumerable: true }
2837
3141
  });
3142
+ setFunctionName(ReadableStreamDefaultController.prototype.close, 'close');
3143
+ setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');
3144
+ setFunctionName(ReadableStreamDefaultController.prototype.error, 'error');
2838
3145
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2839
3146
  Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
2840
3147
  value: 'ReadableStreamDefaultController',
@@ -2868,8 +3175,10 @@
2868
3175
  controller._pullAgain = false;
2869
3176
  ReadableStreamDefaultControllerCallPullIfNeeded(controller);
2870
3177
  }
3178
+ return null;
2871
3179
  }, e => {
2872
3180
  ReadableStreamDefaultControllerError(controller, e);
3181
+ return null;
2873
3182
  });
2874
3183
  }
2875
3184
  function ReadableStreamDefaultControllerShouldCallPull(controller) {
@@ -2984,24 +3293,35 @@
2984
3293
  uponPromise(promiseResolvedWith(startResult), () => {
2985
3294
  controller._started = true;
2986
3295
  ReadableStreamDefaultControllerCallPullIfNeeded(controller);
3296
+ return null;
2987
3297
  }, r => {
2988
3298
  ReadableStreamDefaultControllerError(controller, r);
3299
+ return null;
2989
3300
  });
2990
3301
  }
2991
3302
  function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
2992
3303
  const controller = Object.create(ReadableStreamDefaultController.prototype);
2993
- let startAlgorithm = () => undefined;
2994
- let pullAlgorithm = () => promiseResolvedWith(undefined);
2995
- let cancelAlgorithm = () => promiseResolvedWith(undefined);
3304
+ let startAlgorithm;
3305
+ let pullAlgorithm;
3306
+ let cancelAlgorithm;
2996
3307
  if (underlyingSource.start !== undefined) {
2997
3308
  startAlgorithm = () => underlyingSource.start(controller);
2998
3309
  }
3310
+ else {
3311
+ startAlgorithm = () => undefined;
3312
+ }
2999
3313
  if (underlyingSource.pull !== undefined) {
3000
3314
  pullAlgorithm = () => underlyingSource.pull(controller);
3001
3315
  }
3316
+ else {
3317
+ pullAlgorithm = () => promiseResolvedWith(undefined);
3318
+ }
3002
3319
  if (underlyingSource.cancel !== undefined) {
3003
3320
  cancelAlgorithm = reason => underlyingSource.cancel(reason);
3004
3321
  }
3322
+ else {
3323
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
3324
+ }
3005
3325
  SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
3006
3326
  }
3007
3327
  // Helper functions for the ReadableStreamDefaultController.
@@ -3040,7 +3360,7 @@
3040
3360
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3041
3361
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3042
3362
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3043
- queueMicrotask(() => {
3363
+ _queueMicrotask(() => {
3044
3364
  readAgain = false;
3045
3365
  const chunk1 = chunk;
3046
3366
  const chunk2 = chunk;
@@ -3111,6 +3431,7 @@
3111
3431
  if (!canceled1 || !canceled2) {
3112
3432
  resolveCancelPromise(undefined);
3113
3433
  }
3434
+ return null;
3114
3435
  });
3115
3436
  return [branch1, branch2];
3116
3437
  }
@@ -3132,13 +3453,14 @@
3132
3453
  function forwardReaderError(thisReader) {
3133
3454
  uponRejection(thisReader._closedPromise, r => {
3134
3455
  if (thisReader !== reader) {
3135
- return;
3456
+ return null;
3136
3457
  }
3137
3458
  ReadableByteStreamControllerError(branch1._readableStreamController, r);
3138
3459
  ReadableByteStreamControllerError(branch2._readableStreamController, r);
3139
3460
  if (!canceled1 || !canceled2) {
3140
3461
  resolveCancelPromise(undefined);
3141
3462
  }
3463
+ return null;
3142
3464
  });
3143
3465
  }
3144
3466
  function pullWithDefaultReader() {
@@ -3152,7 +3474,7 @@
3152
3474
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3153
3475
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3154
3476
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3155
- queueMicrotask(() => {
3477
+ _queueMicrotask(() => {
3156
3478
  readAgainForBranch1 = false;
3157
3479
  readAgainForBranch2 = false;
3158
3480
  const chunk1 = chunk;
@@ -3220,7 +3542,7 @@
3220
3542
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3221
3543
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3222
3544
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3223
- queueMicrotask(() => {
3545
+ _queueMicrotask(() => {
3224
3546
  readAgainForBranch1 = false;
3225
3547
  readAgainForBranch2 = false;
3226
3548
  const byobCanceled = forBranch2 ? canceled2 : canceled1;
@@ -3279,7 +3601,7 @@
3279
3601
  reading = false;
3280
3602
  }
3281
3603
  };
3282
- ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);
3604
+ ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);
3283
3605
  }
3284
3606
  function pull1Algorithm() {
3285
3607
  if (reading) {
@@ -3340,6 +3662,109 @@
3340
3662
  return [branch1, branch2];
3341
3663
  }
3342
3664
 
3665
+ function isReadableStreamLike(stream) {
3666
+ return typeIsObject(stream) && typeof stream.getReader !== 'undefined';
3667
+ }
3668
+
3669
+ function ReadableStreamFrom(source) {
3670
+ if (isReadableStreamLike(source)) {
3671
+ return ReadableStreamFromDefaultReader(source.getReader());
3672
+ }
3673
+ return ReadableStreamFromIterable(source);
3674
+ }
3675
+ function ReadableStreamFromIterable(asyncIterable) {
3676
+ let stream;
3677
+ const iteratorRecord = GetIterator(asyncIterable, 'async');
3678
+ const startAlgorithm = noop;
3679
+ function pullAlgorithm() {
3680
+ let nextResult;
3681
+ try {
3682
+ nextResult = IteratorNext(iteratorRecord);
3683
+ }
3684
+ catch (e) {
3685
+ return promiseRejectedWith(e);
3686
+ }
3687
+ const nextPromise = promiseResolvedWith(nextResult);
3688
+ return transformPromiseWith(nextPromise, iterResult => {
3689
+ if (!typeIsObject(iterResult)) {
3690
+ throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');
3691
+ }
3692
+ const done = IteratorComplete(iterResult);
3693
+ if (done) {
3694
+ ReadableStreamDefaultControllerClose(stream._readableStreamController);
3695
+ }
3696
+ else {
3697
+ const value = IteratorValue(iterResult);
3698
+ ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3699
+ }
3700
+ });
3701
+ }
3702
+ function cancelAlgorithm(reason) {
3703
+ const iterator = iteratorRecord.iterator;
3704
+ let returnMethod;
3705
+ try {
3706
+ returnMethod = GetMethod(iterator, 'return');
3707
+ }
3708
+ catch (e) {
3709
+ return promiseRejectedWith(e);
3710
+ }
3711
+ if (returnMethod === undefined) {
3712
+ return promiseResolvedWith(undefined);
3713
+ }
3714
+ let returnResult;
3715
+ try {
3716
+ returnResult = reflectCall(returnMethod, iterator, [reason]);
3717
+ }
3718
+ catch (e) {
3719
+ return promiseRejectedWith(e);
3720
+ }
3721
+ const returnPromise = promiseResolvedWith(returnResult);
3722
+ return transformPromiseWith(returnPromise, iterResult => {
3723
+ if (!typeIsObject(iterResult)) {
3724
+ throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');
3725
+ }
3726
+ return undefined;
3727
+ });
3728
+ }
3729
+ stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3730
+ return stream;
3731
+ }
3732
+ function ReadableStreamFromDefaultReader(reader) {
3733
+ let stream;
3734
+ const startAlgorithm = noop;
3735
+ function pullAlgorithm() {
3736
+ let readPromise;
3737
+ try {
3738
+ readPromise = reader.read();
3739
+ }
3740
+ catch (e) {
3741
+ return promiseRejectedWith(e);
3742
+ }
3743
+ return transformPromiseWith(readPromise, readResult => {
3744
+ if (!typeIsObject(readResult)) {
3745
+ throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');
3746
+ }
3747
+ if (readResult.done) {
3748
+ ReadableStreamDefaultControllerClose(stream._readableStreamController);
3749
+ }
3750
+ else {
3751
+ const value = readResult.value;
3752
+ ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3753
+ }
3754
+ });
3755
+ }
3756
+ function cancelAlgorithm(reason) {
3757
+ try {
3758
+ return promiseResolvedWith(reader.cancel(reason));
3759
+ }
3760
+ catch (e) {
3761
+ return promiseRejectedWith(e);
3762
+ }
3763
+ }
3764
+ stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3765
+ return stream;
3766
+ }
3767
+
3343
3768
  function convertUnderlyingDefaultOrByteSource(source, context) {
3344
3769
  assertDictionary(source, context);
3345
3770
  const original = source;
@@ -3384,21 +3809,6 @@
3384
3809
  return type;
3385
3810
  }
3386
3811
 
3387
- function convertReaderOptions(options, context) {
3388
- assertDictionary(options, context);
3389
- const mode = options === null || options === void 0 ? void 0 : options.mode;
3390
- return {
3391
- mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
3392
- };
3393
- }
3394
- function convertReadableStreamReaderMode(mode, context) {
3395
- mode = `${mode}`;
3396
- if (mode !== 'byob') {
3397
- throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
3398
- }
3399
- return mode;
3400
- }
3401
-
3402
3812
  function convertIteratorOptions(options, context) {
3403
3813
  assertDictionary(options, context);
3404
3814
  const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
@@ -3568,7 +3978,19 @@
3568
3978
  const options = convertIteratorOptions(rawOptions, 'First parameter');
3569
3979
  return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
3570
3980
  }
3981
+ /**
3982
+ * Creates a new ReadableStream wrapping the provided iterable or async iterable.
3983
+ *
3984
+ * This can be used to adapt various kinds of objects into a readable stream,
3985
+ * such as an array, an async generator, or a Node.js readable stream.
3986
+ */
3987
+ static from(asyncIterable) {
3988
+ return ReadableStreamFrom(asyncIterable);
3989
+ }
3571
3990
  }
3991
+ Object.defineProperties(ReadableStream, {
3992
+ from: { enumerable: true }
3993
+ });
3572
3994
  Object.defineProperties(ReadableStream.prototype, {
3573
3995
  cancel: { enumerable: true },
3574
3996
  getReader: { enumerable: true },
@@ -3578,6 +4000,13 @@
3578
4000
  values: { enumerable: true },
3579
4001
  locked: { enumerable: true }
3580
4002
  });
4003
+ setFunctionName(ReadableStream.from, 'from');
4004
+ setFunctionName(ReadableStream.prototype.cancel, 'cancel');
4005
+ setFunctionName(ReadableStream.prototype.getReader, 'getReader');
4006
+ setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');
4007
+ setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');
4008
+ setFunctionName(ReadableStream.prototype.tee, 'tee');
4009
+ setFunctionName(ReadableStream.prototype.values, 'values');
3581
4010
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
3582
4011
  Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {
3583
4012
  value: 'ReadableStream',
@@ -3641,10 +4070,11 @@
3641
4070
  ReadableStreamClose(stream);
3642
4071
  const reader = stream._reader;
3643
4072
  if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {
3644
- reader._readIntoRequests.forEach(readIntoRequest => {
4073
+ const readIntoRequests = reader._readIntoRequests;
4074
+ reader._readIntoRequests = new SimpleQueue();
4075
+ readIntoRequests.forEach(readIntoRequest => {
3645
4076
  readIntoRequest._closeSteps(undefined);
3646
4077
  });
3647
- reader._readIntoRequests = new SimpleQueue();
3648
4078
  }
3649
4079
  const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
3650
4080
  return transformPromiseWith(sourceCancelPromise, noop);
@@ -3657,10 +4087,11 @@
3657
4087
  }
3658
4088
  defaultReaderClosedPromiseResolve(reader);
3659
4089
  if (IsReadableStreamDefaultReader(reader)) {
3660
- reader._readRequests.forEach(readRequest => {
4090
+ const readRequests = reader._readRequests;
4091
+ reader._readRequests = new SimpleQueue();
4092
+ readRequests.forEach(readRequest => {
3661
4093
  readRequest._closeSteps();
3662
4094
  });
3663
- reader._readRequests = new SimpleQueue();
3664
4095
  }
3665
4096
  }
3666
4097
  function ReadableStreamError(stream, e) {
@@ -3672,16 +4103,10 @@
3672
4103
  }
3673
4104
  defaultReaderClosedPromiseReject(reader, e);
3674
4105
  if (IsReadableStreamDefaultReader(reader)) {
3675
- reader._readRequests.forEach(readRequest => {
3676
- readRequest._errorSteps(e);
3677
- });
3678
- reader._readRequests = new SimpleQueue();
4106
+ ReadableStreamDefaultReaderErrorReadRequests(reader, e);
3679
4107
  }
3680
4108
  else {
3681
- reader._readIntoRequests.forEach(readIntoRequest => {
3682
- readIntoRequest._errorSteps(e);
3683
- });
3684
- reader._readIntoRequests = new SimpleQueue();
4109
+ ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
3685
4110
  }
3686
4111
  }
3687
4112
  // Helper functions for the ReadableStream.
@@ -3702,10 +4127,7 @@
3702
4127
  const byteLengthSizeFunction = (chunk) => {
3703
4128
  return chunk.byteLength;
3704
4129
  };
3705
- Object.defineProperty(byteLengthSizeFunction, 'name', {
3706
- value: 'size',
3707
- configurable: true
3708
- });
4130
+ setFunctionName(byteLengthSizeFunction, 'size');
3709
4131
  /**
3710
4132
  * A queuing strategy that counts the number of bytes in each chunk.
3711
4133
  *
@@ -3764,10 +4186,7 @@
3764
4186
  const countSizeFunction = () => {
3765
4187
  return 1;
3766
4188
  };
3767
- Object.defineProperty(countSizeFunction, 'name', {
3768
- value: 'size',
3769
- configurable: true
3770
- });
4189
+ setFunctionName(countSizeFunction, 'size');
3771
4190
  /**
3772
4191
  * A queuing strategy that counts the number of chunks.
3773
4192
  *
@@ -3825,12 +4244,16 @@
3825
4244
 
3826
4245
  function convertTransformer(original, context) {
3827
4246
  assertDictionary(original, context);
4247
+ const cancel = original === null || original === void 0 ? void 0 : original.cancel;
3828
4248
  const flush = original === null || original === void 0 ? void 0 : original.flush;
3829
4249
  const readableType = original === null || original === void 0 ? void 0 : original.readableType;
3830
4250
  const start = original === null || original === void 0 ? void 0 : original.start;
3831
4251
  const transform = original === null || original === void 0 ? void 0 : original.transform;
3832
4252
  const writableType = original === null || original === void 0 ? void 0 : original.writableType;
3833
4253
  return {
4254
+ cancel: cancel === undefined ?
4255
+ undefined :
4256
+ convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`),
3834
4257
  flush: flush === undefined ?
3835
4258
  undefined :
3836
4259
  convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
@@ -3856,6 +4279,10 @@
3856
4279
  assertFunction(fn, context);
3857
4280
  return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
3858
4281
  }
4282
+ function convertTransformerCancelCallback(fn, original, context) {
4283
+ assertFunction(fn, context);
4284
+ return (reason) => promiseCall(fn, original, [reason]);
4285
+ }
3859
4286
 
3860
4287
  // Class TransformStream
3861
4288
  /**
@@ -3944,8 +4371,7 @@
3944
4371
  return TransformStreamDefaultSourcePullAlgorithm(stream);
3945
4372
  }
3946
4373
  function cancelAlgorithm(reason) {
3947
- TransformStreamErrorWritableAndUnblockWrite(stream, reason);
3948
- return promiseResolvedWith(undefined);
4374
+ return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);
3949
4375
  }
3950
4376
  stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
3951
4377
  // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
@@ -3972,6 +4398,9 @@
3972
4398
  function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
3973
4399
  TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
3974
4400
  WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
4401
+ TransformStreamUnblockWrite(stream);
4402
+ }
4403
+ function TransformStreamUnblockWrite(stream) {
3975
4404
  if (stream._backpressure) {
3976
4405
  // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
3977
4406
  // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
@@ -4042,6 +4471,9 @@
4042
4471
  terminate: { enumerable: true },
4043
4472
  desiredSize: { enumerable: true }
4044
4473
  });
4474
+ setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');
4475
+ setFunctionName(TransformStreamDefaultController.prototype.error, 'error');
4476
+ setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');
4045
4477
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4046
4478
  Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
4047
4479
  value: 'TransformStreamDefaultController',
@@ -4058,35 +4490,53 @@
4058
4490
  }
4059
4491
  return x instanceof TransformStreamDefaultController;
4060
4492
  }
4061
- function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
4493
+ function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
4062
4494
  controller._controlledTransformStream = stream;
4063
4495
  stream._transformStreamController = controller;
4064
4496
  controller._transformAlgorithm = transformAlgorithm;
4065
4497
  controller._flushAlgorithm = flushAlgorithm;
4498
+ controller._cancelAlgorithm = cancelAlgorithm;
4499
+ controller._finishPromise = undefined;
4500
+ controller._finishPromise_resolve = undefined;
4501
+ controller._finishPromise_reject = undefined;
4066
4502
  }
4067
4503
  function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
4068
4504
  const controller = Object.create(TransformStreamDefaultController.prototype);
4069
- let transformAlgorithm = (chunk) => {
4070
- try {
4071
- TransformStreamDefaultControllerEnqueue(controller, chunk);
4072
- return promiseResolvedWith(undefined);
4073
- }
4074
- catch (transformResultE) {
4075
- return promiseRejectedWith(transformResultE);
4076
- }
4077
- };
4078
- let flushAlgorithm = () => promiseResolvedWith(undefined);
4505
+ let transformAlgorithm;
4506
+ let flushAlgorithm;
4507
+ let cancelAlgorithm;
4079
4508
  if (transformer.transform !== undefined) {
4080
4509
  transformAlgorithm = chunk => transformer.transform(chunk, controller);
4081
4510
  }
4511
+ else {
4512
+ transformAlgorithm = chunk => {
4513
+ try {
4514
+ TransformStreamDefaultControllerEnqueue(controller, chunk);
4515
+ return promiseResolvedWith(undefined);
4516
+ }
4517
+ catch (transformResultE) {
4518
+ return promiseRejectedWith(transformResultE);
4519
+ }
4520
+ };
4521
+ }
4082
4522
  if (transformer.flush !== undefined) {
4083
4523
  flushAlgorithm = () => transformer.flush(controller);
4084
4524
  }
4085
- SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
4525
+ else {
4526
+ flushAlgorithm = () => promiseResolvedWith(undefined);
4527
+ }
4528
+ if (transformer.cancel !== undefined) {
4529
+ cancelAlgorithm = reason => transformer.cancel(reason);
4530
+ }
4531
+ else {
4532
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
4533
+ }
4534
+ SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);
4086
4535
  }
4087
4536
  function TransformStreamDefaultControllerClearAlgorithms(controller) {
4088
4537
  controller._transformAlgorithm = undefined;
4089
4538
  controller._flushAlgorithm = undefined;
4539
+ controller._cancelAlgorithm = undefined;
4090
4540
  }
4091
4541
  function TransformStreamDefaultControllerEnqueue(controller, chunk) {
4092
4542
  const stream = controller._controlledTransformStream;
@@ -4143,27 +4593,66 @@
4143
4593
  return TransformStreamDefaultControllerPerformTransform(controller, chunk);
4144
4594
  }
4145
4595
  function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
4146
- // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
4147
- // errored.
4148
- TransformStreamError(stream, reason);
4149
- return promiseResolvedWith(undefined);
4596
+ const controller = stream._transformStreamController;
4597
+ if (controller._finishPromise !== undefined) {
4598
+ return controller._finishPromise;
4599
+ }
4600
+ // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4601
+ const readable = stream._readable;
4602
+ // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,
4603
+ // we don't run the _cancelAlgorithm again.
4604
+ controller._finishPromise = newPromise((resolve, reject) => {
4605
+ controller._finishPromise_resolve = resolve;
4606
+ controller._finishPromise_reject = reject;
4607
+ });
4608
+ const cancelPromise = controller._cancelAlgorithm(reason);
4609
+ TransformStreamDefaultControllerClearAlgorithms(controller);
4610
+ uponPromise(cancelPromise, () => {
4611
+ if (readable._state === 'errored') {
4612
+ defaultControllerFinishPromiseReject(controller, readable._storedError);
4613
+ }
4614
+ else {
4615
+ ReadableStreamDefaultControllerError(readable._readableStreamController, reason);
4616
+ defaultControllerFinishPromiseResolve(controller);
4617
+ }
4618
+ return null;
4619
+ }, r => {
4620
+ ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4621
+ defaultControllerFinishPromiseReject(controller, r);
4622
+ return null;
4623
+ });
4624
+ return controller._finishPromise;
4150
4625
  }
4151
4626
  function TransformStreamDefaultSinkCloseAlgorithm(stream) {
4627
+ const controller = stream._transformStreamController;
4628
+ if (controller._finishPromise !== undefined) {
4629
+ return controller._finishPromise;
4630
+ }
4152
4631
  // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4153
4632
  const readable = stream._readable;
4154
- const controller = stream._transformStreamController;
4633
+ // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,
4634
+ // we don't also run the _cancelAlgorithm.
4635
+ controller._finishPromise = newPromise((resolve, reject) => {
4636
+ controller._finishPromise_resolve = resolve;
4637
+ controller._finishPromise_reject = reject;
4638
+ });
4155
4639
  const flushPromise = controller._flushAlgorithm();
4156
4640
  TransformStreamDefaultControllerClearAlgorithms(controller);
4157
- // Return a promise that is fulfilled with undefined on success.
4158
- return transformPromiseWith(flushPromise, () => {
4641
+ uponPromise(flushPromise, () => {
4159
4642
  if (readable._state === 'errored') {
4160
- throw readable._storedError;
4643
+ defaultControllerFinishPromiseReject(controller, readable._storedError);
4161
4644
  }
4162
- ReadableStreamDefaultControllerClose(readable._readableStreamController);
4645
+ else {
4646
+ ReadableStreamDefaultControllerClose(readable._readableStreamController);
4647
+ defaultControllerFinishPromiseResolve(controller);
4648
+ }
4649
+ return null;
4163
4650
  }, r => {
4164
- TransformStreamError(stream, r);
4165
- throw readable._storedError;
4651
+ ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4652
+ defaultControllerFinishPromiseReject(controller, r);
4653
+ return null;
4166
4654
  });
4655
+ return controller._finishPromise;
4167
4656
  }
4168
4657
  // TransformStreamDefaultSource Algorithms
4169
4658
  function TransformStreamDefaultSourcePullAlgorithm(stream) {
@@ -4172,10 +4661,61 @@
4172
4661
  // Prevent the next pull() call until there is backpressure.
4173
4662
  return stream._backpressureChangePromise;
4174
4663
  }
4664
+ function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) {
4665
+ const controller = stream._transformStreamController;
4666
+ if (controller._finishPromise !== undefined) {
4667
+ return controller._finishPromise;
4668
+ }
4669
+ // stream._writable cannot change after construction, so caching it across a call to user code is safe.
4670
+ const writable = stream._writable;
4671
+ // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or
4672
+ // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the
4673
+ // _flushAlgorithm.
4674
+ controller._finishPromise = newPromise((resolve, reject) => {
4675
+ controller._finishPromise_resolve = resolve;
4676
+ controller._finishPromise_reject = reject;
4677
+ });
4678
+ const cancelPromise = controller._cancelAlgorithm(reason);
4679
+ TransformStreamDefaultControllerClearAlgorithms(controller);
4680
+ uponPromise(cancelPromise, () => {
4681
+ if (writable._state === 'errored') {
4682
+ defaultControllerFinishPromiseReject(controller, writable._storedError);
4683
+ }
4684
+ else {
4685
+ WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);
4686
+ TransformStreamUnblockWrite(stream);
4687
+ defaultControllerFinishPromiseResolve(controller);
4688
+ }
4689
+ return null;
4690
+ }, r => {
4691
+ WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);
4692
+ TransformStreamUnblockWrite(stream);
4693
+ defaultControllerFinishPromiseReject(controller, r);
4694
+ return null;
4695
+ });
4696
+ return controller._finishPromise;
4697
+ }
4175
4698
  // Helper functions for the TransformStreamDefaultController.
4176
4699
  function defaultControllerBrandCheckException(name) {
4177
4700
  return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
4178
4701
  }
4702
+ function defaultControllerFinishPromiseResolve(controller) {
4703
+ if (controller._finishPromise_resolve === undefined) {
4704
+ return;
4705
+ }
4706
+ controller._finishPromise_resolve();
4707
+ controller._finishPromise_resolve = undefined;
4708
+ controller._finishPromise_reject = undefined;
4709
+ }
4710
+ function defaultControllerFinishPromiseReject(controller, reason) {
4711
+ if (controller._finishPromise_reject === undefined) {
4712
+ return;
4713
+ }
4714
+ setPromiseIsHandledToTrue(controller._finishPromise);
4715
+ controller._finishPromise_reject(reason);
4716
+ controller._finishPromise_resolve = undefined;
4717
+ controller._finishPromise_reject = undefined;
4718
+ }
4179
4719
  // Helper functions for the TransformStream.
4180
4720
  function streamBrandCheckException(name) {
4181
4721
  return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
@@ -4195,7 +4735,5 @@
4195
4735
  exports.WritableStreamDefaultController = WritableStreamDefaultController;
4196
4736
  exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
4197
4737
 
4198
- Object.defineProperty(exports, '__esModule', { value: true });
4199
-
4200
- })));
4738
+ }));
4201
4739
  //# sourceMappingURL=ponyfill.es2018.js.map