source: node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs@ d24f17c

main
Last change on this file since d24f17c was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 189.1 KB
RevLine 
[d24f17c]1/**
2 * @license
3 * web-streams-polyfill v3.3.2
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
7 */
8/// <reference lib="es2015.symbol" />
9const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
10 Symbol :
11 description => `Symbol(${description})`;
12
13function noop() {
14 return undefined;
15}
16
17function typeIsObject(x) {
18 return (typeof x === 'object' && x !== null) || typeof x === 'function';
19}
20const rethrowAssertionErrorRejection = noop;
21function setFunctionName(fn, name) {
22 try {
23 Object.defineProperty(fn, 'name', {
24 value: name,
25 configurable: true
26 });
27 }
28 catch (_a) {
29 // This property is non-configurable in older browsers, so ignore if this throws.
30 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
31 }
32}
33
34const originalPromise = Promise;
35const originalPromiseThen = Promise.prototype.then;
36const originalPromiseReject = Promise.reject.bind(originalPromise);
37// https://webidl.spec.whatwg.org/#a-new-promise
38function newPromise(executor) {
39 return new originalPromise(executor);
40}
41// https://webidl.spec.whatwg.org/#a-promise-resolved-with
42function promiseResolvedWith(value) {
43 return newPromise(resolve => resolve(value));
44}
45// https://webidl.spec.whatwg.org/#a-promise-rejected-with
46function promiseRejectedWith(reason) {
47 return originalPromiseReject(reason);
48}
49function PerformPromiseThen(promise, onFulfilled, onRejected) {
50 // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an
51 // approximation.
52 return originalPromiseThen.call(promise, onFulfilled, onRejected);
53}
54// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned
55// from that handler. To prevent this, return null instead of void from all handlers.
56// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it
57function uponPromise(promise, onFulfilled, onRejected) {
58 PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
59}
60function uponFulfillment(promise, onFulfilled) {
61 uponPromise(promise, onFulfilled);
62}
63function uponRejection(promise, onRejected) {
64 uponPromise(promise, undefined, onRejected);
65}
66function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
67 return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
68}
69function setPromiseIsHandledToTrue(promise) {
70 PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
71}
72let _queueMicrotask = callback => {
73 if (typeof queueMicrotask === 'function') {
74 _queueMicrotask = queueMicrotask;
75 }
76 else {
77 const resolvedPromise = promiseResolvedWith(undefined);
78 _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);
79 }
80 return _queueMicrotask(callback);
81};
82function reflectCall(F, V, args) {
83 if (typeof F !== 'function') {
84 throw new TypeError('Argument is not a function');
85 }
86 return Function.prototype.apply.call(F, V, args);
87}
88function promiseCall(F, V, args) {
89 try {
90 return promiseResolvedWith(reflectCall(F, V, args));
91 }
92 catch (value) {
93 return promiseRejectedWith(value);
94 }
95}
96
97// Original from Chromium
98// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js
99const QUEUE_MAX_ARRAY_SIZE = 16384;
100/**
101 * Simple queue structure.
102 *
103 * Avoids scalability issues with using a packed array directly by using
104 * multiple arrays in a linked list and keeping the array size bounded.
105 */
106class SimpleQueue {
107 constructor() {
108 this._cursor = 0;
109 this._size = 0;
110 // _front and _back are always defined.
111 this._front = {
112 _elements: [],
113 _next: undefined
114 };
115 this._back = this._front;
116 // The cursor is used to avoid calling Array.shift().
117 // It contains the index of the front element of the array inside the
118 // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).
119 this._cursor = 0;
120 // When there is only one node, size === elements.length - cursor.
121 this._size = 0;
122 }
123 get length() {
124 return this._size;
125 }
126 // For exception safety, this method is structured in order:
127 // 1. Read state
128 // 2. Calculate required state mutations
129 // 3. Perform state mutations
130 push(element) {
131 const oldBack = this._back;
132 let newBack = oldBack;
133 if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
134 newBack = {
135 _elements: [],
136 _next: undefined
137 };
138 }
139 // push() is the mutation most likely to throw an exception, so it
140 // goes first.
141 oldBack._elements.push(element);
142 if (newBack !== oldBack) {
143 this._back = newBack;
144 oldBack._next = newBack;
145 }
146 ++this._size;
147 }
148 // Like push(), shift() follows the read -> calculate -> mutate pattern for
149 // exception safety.
150 shift() { // must not be called on an empty queue
151 const oldFront = this._front;
152 let newFront = oldFront;
153 const oldCursor = this._cursor;
154 let newCursor = oldCursor + 1;
155 const elements = oldFront._elements;
156 const element = elements[oldCursor];
157 if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
158 newFront = oldFront._next;
159 newCursor = 0;
160 }
161 // No mutations before this point.
162 --this._size;
163 this._cursor = newCursor;
164 if (oldFront !== newFront) {
165 this._front = newFront;
166 }
167 // Permit shifted element to be garbage collected.
168 elements[oldCursor] = undefined;
169 return element;
170 }
171 // The tricky thing about forEach() is that it can be called
172 // re-entrantly. The queue may be mutated inside the callback. It is easy to
173 // see that push() within the callback has no negative effects since the end
174 // of the queue is checked for on every iteration. If shift() is called
175 // repeatedly within the callback then the next iteration may return an
176 // element that has been removed. In this case the callback will be called
177 // with undefined values until we either "catch up" with elements that still
178 // exist or reach the back of the queue.
179 forEach(callback) {
180 let i = this._cursor;
181 let node = this._front;
182 let elements = node._elements;
183 while (i !== elements.length || node._next !== undefined) {
184 if (i === elements.length) {
185 node = node._next;
186 elements = node._elements;
187 i = 0;
188 if (elements.length === 0) {
189 break;
190 }
191 }
192 callback(elements[i]);
193 ++i;
194 }
195 }
196 // Return the element that would be returned if shift() was called now,
197 // without modifying the queue.
198 peek() { // must not be called on an empty queue
199 const front = this._front;
200 const cursor = this._cursor;
201 return front._elements[cursor];
202 }
203}
204
205const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
206const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
207const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
208const PullSteps = SymbolPolyfill('[[PullSteps]]');
209const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]');
210
211function ReadableStreamReaderGenericInitialize(reader, stream) {
212 reader._ownerReadableStream = stream;
213 stream._reader = reader;
214 if (stream._state === 'readable') {
215 defaultReaderClosedPromiseInitialize(reader);
216 }
217 else if (stream._state === 'closed') {
218 defaultReaderClosedPromiseInitializeAsResolved(reader);
219 }
220 else {
221 defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
222 }
223}
224// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
225// check.
226function ReadableStreamReaderGenericCancel(reader, reason) {
227 const stream = reader._ownerReadableStream;
228 return ReadableStreamCancel(stream, reason);
229}
230function ReadableStreamReaderGenericRelease(reader) {
231 const stream = reader._ownerReadableStream;
232 if (stream._state === 'readable') {
233 defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
234 }
235 else {
236 defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
237 }
238 stream._readableStreamController[ReleaseSteps]();
239 stream._reader = undefined;
240 reader._ownerReadableStream = undefined;
241}
242// Helper functions for the readers.
243function readerLockException(name) {
244 return new TypeError('Cannot ' + name + ' a stream using a released reader');
245}
246// Helper functions for the ReadableStreamDefaultReader.
247function defaultReaderClosedPromiseInitialize(reader) {
248 reader._closedPromise = newPromise((resolve, reject) => {
249 reader._closedPromise_resolve = resolve;
250 reader._closedPromise_reject = reject;
251 });
252}
253function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
254 defaultReaderClosedPromiseInitialize(reader);
255 defaultReaderClosedPromiseReject(reader, reason);
256}
257function defaultReaderClosedPromiseInitializeAsResolved(reader) {
258 defaultReaderClosedPromiseInitialize(reader);
259 defaultReaderClosedPromiseResolve(reader);
260}
261function defaultReaderClosedPromiseReject(reader, reason) {
262 if (reader._closedPromise_reject === undefined) {
263 return;
264 }
265 setPromiseIsHandledToTrue(reader._closedPromise);
266 reader._closedPromise_reject(reason);
267 reader._closedPromise_resolve = undefined;
268 reader._closedPromise_reject = undefined;
269}
270function defaultReaderClosedPromiseResetToRejected(reader, reason) {
271 defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
272}
273function defaultReaderClosedPromiseResolve(reader) {
274 if (reader._closedPromise_resolve === undefined) {
275 return;
276 }
277 reader._closedPromise_resolve(undefined);
278 reader._closedPromise_resolve = undefined;
279 reader._closedPromise_reject = undefined;
280}
281
282/// <reference lib="es2015.core" />
283// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
284const NumberIsFinite = Number.isFinite || function (x) {
285 return typeof x === 'number' && isFinite(x);
286};
287
288/// <reference lib="es2015.core" />
289// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill
290const MathTrunc = Math.trunc || function (v) {
291 return v < 0 ? Math.ceil(v) : Math.floor(v);
292};
293
294// https://heycam.github.io/webidl/#idl-dictionaries
295function isDictionary(x) {
296 return typeof x === 'object' || typeof x === 'function';
297}
298function assertDictionary(obj, context) {
299 if (obj !== undefined && !isDictionary(obj)) {
300 throw new TypeError(`${context} is not an object.`);
301 }
302}
303// https://heycam.github.io/webidl/#idl-callback-functions
304function assertFunction(x, context) {
305 if (typeof x !== 'function') {
306 throw new TypeError(`${context} is not a function.`);
307 }
308}
309// https://heycam.github.io/webidl/#idl-object
310function isObject(x) {
311 return (typeof x === 'object' && x !== null) || typeof x === 'function';
312}
313function assertObject(x, context) {
314 if (!isObject(x)) {
315 throw new TypeError(`${context} is not an object.`);
316 }
317}
318function assertRequiredArgument(x, position, context) {
319 if (x === undefined) {
320 throw new TypeError(`Parameter ${position} is required in '${context}'.`);
321 }
322}
323function assertRequiredField(x, field, context) {
324 if (x === undefined) {
325 throw new TypeError(`${field} is required in '${context}'.`);
326 }
327}
328// https://heycam.github.io/webidl/#idl-unrestricted-double
329function convertUnrestrictedDouble(value) {
330 return Number(value);
331}
332function censorNegativeZero(x) {
333 return x === 0 ? 0 : x;
334}
335function integerPart(x) {
336 return censorNegativeZero(MathTrunc(x));
337}
338// https://heycam.github.io/webidl/#idl-unsigned-long-long
339function convertUnsignedLongLongWithEnforceRange(value, context) {
340 const lowerBound = 0;
341 const upperBound = Number.MAX_SAFE_INTEGER;
342 let x = Number(value);
343 x = censorNegativeZero(x);
344 if (!NumberIsFinite(x)) {
345 throw new TypeError(`${context} is not a finite number`);
346 }
347 x = integerPart(x);
348 if (x < lowerBound || x > upperBound) {
349 throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
350 }
351 if (!NumberIsFinite(x) || x === 0) {
352 return 0;
353 }
354 // TODO Use BigInt if supported?
355 // let xBigInt = BigInt(integerPart(x));
356 // xBigInt = BigInt.asUintN(64, xBigInt);
357 // return Number(xBigInt);
358 return x;
359}
360
361function assertReadableStream(x, context) {
362 if (!IsReadableStream(x)) {
363 throw new TypeError(`${context} is not a ReadableStream.`);
364 }
365}
366
367// Abstract operations for the ReadableStream.
368function AcquireReadableStreamDefaultReader(stream) {
369 return new ReadableStreamDefaultReader(stream);
370}
371// ReadableStream API exposed for controllers.
372function ReadableStreamAddReadRequest(stream, readRequest) {
373 stream._reader._readRequests.push(readRequest);
374}
375function ReadableStreamFulfillReadRequest(stream, chunk, done) {
376 const reader = stream._reader;
377 const readRequest = reader._readRequests.shift();
378 if (done) {
379 readRequest._closeSteps();
380 }
381 else {
382 readRequest._chunkSteps(chunk);
383 }
384}
385function ReadableStreamGetNumReadRequests(stream) {
386 return stream._reader._readRequests.length;
387}
388function ReadableStreamHasDefaultReader(stream) {
389 const reader = stream._reader;
390 if (reader === undefined) {
391 return false;
392 }
393 if (!IsReadableStreamDefaultReader(reader)) {
394 return false;
395 }
396 return true;
397}
398/**
399 * A default reader vended by a {@link ReadableStream}.
400 *
401 * @public
402 */
403class ReadableStreamDefaultReader {
404 constructor(stream) {
405 assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');
406 assertReadableStream(stream, 'First parameter');
407 if (IsReadableStreamLocked(stream)) {
408 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
409 }
410 ReadableStreamReaderGenericInitialize(this, stream);
411 this._readRequests = new SimpleQueue();
412 }
413 /**
414 * Returns a promise that will be fulfilled when the stream becomes closed,
415 * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
416 */
417 get closed() {
418 if (!IsReadableStreamDefaultReader(this)) {
419 return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
420 }
421 return this._closedPromise;
422 }
423 /**
424 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
425 */
426 cancel(reason = undefined) {
427 if (!IsReadableStreamDefaultReader(this)) {
428 return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
429 }
430 if (this._ownerReadableStream === undefined) {
431 return promiseRejectedWith(readerLockException('cancel'));
432 }
433 return ReadableStreamReaderGenericCancel(this, reason);
434 }
435 /**
436 * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
437 *
438 * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
439 */
440 read() {
441 if (!IsReadableStreamDefaultReader(this)) {
442 return promiseRejectedWith(defaultReaderBrandCheckException('read'));
443 }
444 if (this._ownerReadableStream === undefined) {
445 return promiseRejectedWith(readerLockException('read from'));
446 }
447 let resolvePromise;
448 let rejectPromise;
449 const promise = newPromise((resolve, reject) => {
450 resolvePromise = resolve;
451 rejectPromise = reject;
452 });
453 const readRequest = {
454 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
455 _closeSteps: () => resolvePromise({ value: undefined, done: true }),
456 _errorSteps: e => rejectPromise(e)
457 };
458 ReadableStreamDefaultReaderRead(this, readRequest);
459 return promise;
460 }
461 /**
462 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
463 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
464 * from now on; otherwise, the reader will appear closed.
465 *
466 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
467 * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
468 * do so will throw a `TypeError` and leave the reader locked to the stream.
469 */
470 releaseLock() {
471 if (!IsReadableStreamDefaultReader(this)) {
472 throw defaultReaderBrandCheckException('releaseLock');
473 }
474 if (this._ownerReadableStream === undefined) {
475 return;
476 }
477 ReadableStreamDefaultReaderRelease(this);
478 }
479}
480Object.defineProperties(ReadableStreamDefaultReader.prototype, {
481 cancel: { enumerable: true },
482 read: { enumerable: true },
483 releaseLock: { enumerable: true },
484 closed: { enumerable: true }
485});
486setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');
487setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');
488setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');
489if (typeof SymbolPolyfill.toStringTag === 'symbol') {
490 Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
491 value: 'ReadableStreamDefaultReader',
492 configurable: true
493 });
494}
495// Abstract operations for the readers.
496function IsReadableStreamDefaultReader(x) {
497 if (!typeIsObject(x)) {
498 return false;
499 }
500 if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
501 return false;
502 }
503 return x instanceof ReadableStreamDefaultReader;
504}
505function ReadableStreamDefaultReaderRead(reader, readRequest) {
506 const stream = reader._ownerReadableStream;
507 stream._disturbed = true;
508 if (stream._state === 'closed') {
509 readRequest._closeSteps();
510 }
511 else if (stream._state === 'errored') {
512 readRequest._errorSteps(stream._storedError);
513 }
514 else {
515 stream._readableStreamController[PullSteps](readRequest);
516 }
517}
518function ReadableStreamDefaultReaderRelease(reader) {
519 ReadableStreamReaderGenericRelease(reader);
520 const e = new TypeError('Reader was released');
521 ReadableStreamDefaultReaderErrorReadRequests(reader, e);
522}
523function ReadableStreamDefaultReaderErrorReadRequests(reader, e) {
524 const readRequests = reader._readRequests;
525 reader._readRequests = new SimpleQueue();
526 readRequests.forEach(readRequest => {
527 readRequest._errorSteps(e);
528 });
529}
530// Helper functions for the ReadableStreamDefaultReader.
531function defaultReaderBrandCheckException(name) {
532 return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
533}
534
535/// <reference lib="es2018.asynciterable" />
536/* eslint-disable @typescript-eslint/no-empty-function */
537const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype);
538
539/// <reference lib="es2018.asynciterable" />
540class ReadableStreamAsyncIteratorImpl {
541 constructor(reader, preventCancel) {
542 this._ongoingPromise = undefined;
543 this._isFinished = false;
544 this._reader = reader;
545 this._preventCancel = preventCancel;
546 }
547 next() {
548 const nextSteps = () => this._nextSteps();
549 this._ongoingPromise = this._ongoingPromise ?
550 transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :
551 nextSteps();
552 return this._ongoingPromise;
553 }
554 return(value) {
555 const returnSteps = () => this._returnSteps(value);
556 return this._ongoingPromise ?
557 transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :
558 returnSteps();
559 }
560 _nextSteps() {
561 if (this._isFinished) {
562 return Promise.resolve({ value: undefined, done: true });
563 }
564 const reader = this._reader;
565 let resolvePromise;
566 let rejectPromise;
567 const promise = newPromise((resolve, reject) => {
568 resolvePromise = resolve;
569 rejectPromise = reject;
570 });
571 const readRequest = {
572 _chunkSteps: chunk => {
573 this._ongoingPromise = undefined;
574 // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
575 // FIXME Is this a bug in the specification, or in the test?
576 _queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
577 },
578 _closeSteps: () => {
579 this._ongoingPromise = undefined;
580 this._isFinished = true;
581 ReadableStreamReaderGenericRelease(reader);
582 resolvePromise({ value: undefined, done: true });
583 },
584 _errorSteps: reason => {
585 this._ongoingPromise = undefined;
586 this._isFinished = true;
587 ReadableStreamReaderGenericRelease(reader);
588 rejectPromise(reason);
589 }
590 };
591 ReadableStreamDefaultReaderRead(reader, readRequest);
592 return promise;
593 }
594 _returnSteps(value) {
595 if (this._isFinished) {
596 return Promise.resolve({ value, done: true });
597 }
598 this._isFinished = true;
599 const reader = this._reader;
600 if (!this._preventCancel) {
601 const result = ReadableStreamReaderGenericCancel(reader, value);
602 ReadableStreamReaderGenericRelease(reader);
603 return transformPromiseWith(result, () => ({ value, done: true }));
604 }
605 ReadableStreamReaderGenericRelease(reader);
606 return promiseResolvedWith({ value, done: true });
607 }
608}
609const ReadableStreamAsyncIteratorPrototype = {
610 next() {
611 if (!IsReadableStreamAsyncIterator(this)) {
612 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
613 }
614 return this._asyncIteratorImpl.next();
615 },
616 return(value) {
617 if (!IsReadableStreamAsyncIterator(this)) {
618 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));
619 }
620 return this._asyncIteratorImpl.return(value);
621 }
622};
623if (AsyncIteratorPrototype !== undefined) {
624 Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
625}
626// Abstract operations for the ReadableStream.
627function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
628 const reader = AcquireReadableStreamDefaultReader(stream);
629 const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
630 const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
631 iterator._asyncIteratorImpl = impl;
632 return iterator;
633}
634function IsReadableStreamAsyncIterator(x) {
635 if (!typeIsObject(x)) {
636 return false;
637 }
638 if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {
639 return false;
640 }
641 try {
642 // noinspection SuspiciousTypeOfGuard
643 return x._asyncIteratorImpl instanceof
644 ReadableStreamAsyncIteratorImpl;
645 }
646 catch (_a) {
647 return false;
648 }
649}
650// Helper functions for the ReadableStream.
651function streamAsyncIteratorBrandCheckException(name) {
652 return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
653}
654
655/// <reference lib="es2015.core" />
656// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill
657const NumberIsNaN = Number.isNaN || function (x) {
658 // eslint-disable-next-line no-self-compare
659 return x !== x;
660};
661
662function CreateArrayFromList(elements) {
663 // We use arrays to represent lists, so this is basically a no-op.
664 // Do a slice though just in case we happen to depend on the unique-ness.
665 return elements.slice();
666}
667function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
668 new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
669}
670let TransferArrayBuffer = (O) => {
671 if (typeof O.transfer === 'function') {
672 TransferArrayBuffer = buffer => buffer.transfer();
673 }
674 else if (typeof structuredClone === 'function') {
675 TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });
676 }
677 else {
678 // Not implemented correctly
679 TransferArrayBuffer = buffer => buffer;
680 }
681 return TransferArrayBuffer(O);
682};
683let IsDetachedBuffer = (O) => {
684 if (typeof O.detached === 'boolean') {
685 IsDetachedBuffer = buffer => buffer.detached;
686 }
687 else {
688 // Not implemented correctly
689 IsDetachedBuffer = buffer => buffer.byteLength === 0;
690 }
691 return IsDetachedBuffer(O);
692};
693function ArrayBufferSlice(buffer, begin, end) {
694 // ArrayBuffer.prototype.slice is not available on IE10
695 // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice
696 if (buffer.slice) {
697 return buffer.slice(begin, end);
698 }
699 const length = end - begin;
700 const slice = new ArrayBuffer(length);
701 CopyDataBlockBytes(slice, 0, buffer, begin, length);
702 return slice;
703}
704function GetMethod(receiver, prop) {
705 const func = receiver[prop];
706 if (func === undefined || func === null) {
707 return undefined;
708 }
709 if (typeof func !== 'function') {
710 throw new TypeError(`${String(prop)} is not a function`);
711 }
712 return func;
713}
714function CreateAsyncFromSyncIterator(syncIteratorRecord) {
715 // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,
716 // we use yield* inside an async generator function to achieve the same result.
717 // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.
718 const syncIterable = {
719 [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator
720 };
721 // Create an async generator function and immediately invoke it.
722 const asyncIterator = (async function* () {
723 return yield* syncIterable;
724 }());
725 // Return as an async iterator record.
726 const nextMethod = asyncIterator.next;
727 return { iterator: asyncIterator, nextMethod, done: false };
728}
729function GetIterator(obj, hint = 'sync', method) {
730 if (method === undefined) {
731 if (hint === 'async') {
732 method = GetMethod(obj, SymbolPolyfill.asyncIterator);
733 if (method === undefined) {
734 const syncMethod = GetMethod(obj, SymbolPolyfill.iterator);
735 const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod);
736 return CreateAsyncFromSyncIterator(syncIteratorRecord);
737 }
738 }
739 else {
740 method = GetMethod(obj, SymbolPolyfill.iterator);
741 }
742 }
743 if (method === undefined) {
744 throw new TypeError('The object is not iterable');
745 }
746 const iterator = reflectCall(method, obj, []);
747 if (!typeIsObject(iterator)) {
748 throw new TypeError('The iterator method must return an object');
749 }
750 const nextMethod = iterator.next;
751 return { iterator, nextMethod, done: false };
752}
753function IteratorNext(iteratorRecord) {
754 const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);
755 if (!typeIsObject(result)) {
756 throw new TypeError('The iterator.next() method must return an object');
757 }
758 return result;
759}
760function IteratorComplete(iterResult) {
761 return Boolean(iterResult.done);
762}
763function IteratorValue(iterResult) {
764 return iterResult.value;
765}
766
767function IsNonNegativeNumber(v) {
768 if (typeof v !== 'number') {
769 return false;
770 }
771 if (NumberIsNaN(v)) {
772 return false;
773 }
774 if (v < 0) {
775 return false;
776 }
777 return true;
778}
779function CloneAsUint8Array(O) {
780 const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);
781 return new Uint8Array(buffer);
782}
783
784function DequeueValue(container) {
785 const pair = container._queue.shift();
786 container._queueTotalSize -= pair.size;
787 if (container._queueTotalSize < 0) {
788 container._queueTotalSize = 0;
789 }
790 return pair.value;
791}
792function EnqueueValueWithSize(container, value, size) {
793 if (!IsNonNegativeNumber(size) || size === Infinity) {
794 throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
795 }
796 container._queue.push({ value, size });
797 container._queueTotalSize += size;
798}
799function PeekQueueValue(container) {
800 const pair = container._queue.peek();
801 return pair.value;
802}
803function ResetQueue(container) {
804 container._queue = new SimpleQueue();
805 container._queueTotalSize = 0;
806}
807
808function isDataViewConstructor(ctor) {
809 return ctor === DataView;
810}
811function isDataView(view) {
812 return isDataViewConstructor(view.constructor);
813}
814function arrayBufferViewElementSize(ctor) {
815 if (isDataViewConstructor(ctor)) {
816 return 1;
817 }
818 return ctor.BYTES_PER_ELEMENT;
819}
820
821/**
822 * A pull-into request in a {@link ReadableByteStreamController}.
823 *
824 * @public
825 */
826class ReadableStreamBYOBRequest {
827 constructor() {
828 throw new TypeError('Illegal constructor');
829 }
830 /**
831 * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
832 */
833 get view() {
834 if (!IsReadableStreamBYOBRequest(this)) {
835 throw byobRequestBrandCheckException('view');
836 }
837 return this._view;
838 }
839 respond(bytesWritten) {
840 if (!IsReadableStreamBYOBRequest(this)) {
841 throw byobRequestBrandCheckException('respond');
842 }
843 assertRequiredArgument(bytesWritten, 1, 'respond');
844 bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');
845 if (this._associatedReadableByteStreamController === undefined) {
846 throw new TypeError('This BYOB request has been invalidated');
847 }
848 if (IsDetachedBuffer(this._view.buffer)) {
849 throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);
850 }
851 ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
852 }
853 respondWithNewView(view) {
854 if (!IsReadableStreamBYOBRequest(this)) {
855 throw byobRequestBrandCheckException('respondWithNewView');
856 }
857 assertRequiredArgument(view, 1, 'respondWithNewView');
858 if (!ArrayBuffer.isView(view)) {
859 throw new TypeError('You can only respond with array buffer views');
860 }
861 if (this._associatedReadableByteStreamController === undefined) {
862 throw new TypeError('This BYOB request has been invalidated');
863 }
864 if (IsDetachedBuffer(view.buffer)) {
865 throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response');
866 }
867 ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
868 }
869}
870Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
871 respond: { enumerable: true },
872 respondWithNewView: { enumerable: true },
873 view: { enumerable: true }
874});
875setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');
876setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');
877if (typeof SymbolPolyfill.toStringTag === 'symbol') {
878 Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
879 value: 'ReadableStreamBYOBRequest',
880 configurable: true
881 });
882}
883/**
884 * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
885 *
886 * @public
887 */
888class ReadableByteStreamController {
889 constructor() {
890 throw new TypeError('Illegal constructor');
891 }
892 /**
893 * Returns the current BYOB pull request, or `null` if there isn't one.
894 */
895 get byobRequest() {
896 if (!IsReadableByteStreamController(this)) {
897 throw byteStreamControllerBrandCheckException('byobRequest');
898 }
899 return ReadableByteStreamControllerGetBYOBRequest(this);
900 }
901 /**
902 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
903 * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
904 */
905 get desiredSize() {
906 if (!IsReadableByteStreamController(this)) {
907 throw byteStreamControllerBrandCheckException('desiredSize');
908 }
909 return ReadableByteStreamControllerGetDesiredSize(this);
910 }
911 /**
912 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
913 * the stream, but once those are read, the stream will become closed.
914 */
915 close() {
916 if (!IsReadableByteStreamController(this)) {
917 throw byteStreamControllerBrandCheckException('close');
918 }
919 if (this._closeRequested) {
920 throw new TypeError('The stream has already been closed; do not close it again!');
921 }
922 const state = this._controlledReadableByteStream._state;
923 if (state !== 'readable') {
924 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
925 }
926 ReadableByteStreamControllerClose(this);
927 }
928 enqueue(chunk) {
929 if (!IsReadableByteStreamController(this)) {
930 throw byteStreamControllerBrandCheckException('enqueue');
931 }
932 assertRequiredArgument(chunk, 1, 'enqueue');
933 if (!ArrayBuffer.isView(chunk)) {
934 throw new TypeError('chunk must be an array buffer view');
935 }
936 if (chunk.byteLength === 0) {
937 throw new TypeError('chunk must have non-zero byteLength');
938 }
939 if (chunk.buffer.byteLength === 0) {
940 throw new TypeError(`chunk's buffer must have non-zero byteLength`);
941 }
942 if (this._closeRequested) {
943 throw new TypeError('stream is closed or draining');
944 }
945 const state = this._controlledReadableByteStream._state;
946 if (state !== 'readable') {
947 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
948 }
949 ReadableByteStreamControllerEnqueue(this, chunk);
950 }
951 /**
952 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
953 */
954 error(e = undefined) {
955 if (!IsReadableByteStreamController(this)) {
956 throw byteStreamControllerBrandCheckException('error');
957 }
958 ReadableByteStreamControllerError(this, e);
959 }
960 /** @internal */
961 [CancelSteps](reason) {
962 ReadableByteStreamControllerClearPendingPullIntos(this);
963 ResetQueue(this);
964 const result = this._cancelAlgorithm(reason);
965 ReadableByteStreamControllerClearAlgorithms(this);
966 return result;
967 }
968 /** @internal */
969 [PullSteps](readRequest) {
970 const stream = this._controlledReadableByteStream;
971 if (this._queueTotalSize > 0) {
972 ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);
973 return;
974 }
975 const autoAllocateChunkSize = this._autoAllocateChunkSize;
976 if (autoAllocateChunkSize !== undefined) {
977 let buffer;
978 try {
979 buffer = new ArrayBuffer(autoAllocateChunkSize);
980 }
981 catch (bufferE) {
982 readRequest._errorSteps(bufferE);
983 return;
984 }
985 const pullIntoDescriptor = {
986 buffer,
987 bufferByteLength: autoAllocateChunkSize,
988 byteOffset: 0,
989 byteLength: autoAllocateChunkSize,
990 bytesFilled: 0,
991 minimumFill: 1,
992 elementSize: 1,
993 viewConstructor: Uint8Array,
994 readerType: 'default'
995 };
996 this._pendingPullIntos.push(pullIntoDescriptor);
997 }
998 ReadableStreamAddReadRequest(stream, readRequest);
999 ReadableByteStreamControllerCallPullIfNeeded(this);
1000 }
1001 /** @internal */
1002 [ReleaseSteps]() {
1003 if (this._pendingPullIntos.length > 0) {
1004 const firstPullInto = this._pendingPullIntos.peek();
1005 firstPullInto.readerType = 'none';
1006 this._pendingPullIntos = new SimpleQueue();
1007 this._pendingPullIntos.push(firstPullInto);
1008 }
1009 }
1010}
1011Object.defineProperties(ReadableByteStreamController.prototype, {
1012 close: { enumerable: true },
1013 enqueue: { enumerable: true },
1014 error: { enumerable: true },
1015 byobRequest: { enumerable: true },
1016 desiredSize: { enumerable: true }
1017});
1018setFunctionName(ReadableByteStreamController.prototype.close, 'close');
1019setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');
1020setFunctionName(ReadableByteStreamController.prototype.error, 'error');
1021if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1022 Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
1023 value: 'ReadableByteStreamController',
1024 configurable: true
1025 });
1026}
1027// Abstract operations for the ReadableByteStreamController.
1028function IsReadableByteStreamController(x) {
1029 if (!typeIsObject(x)) {
1030 return false;
1031 }
1032 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
1033 return false;
1034 }
1035 return x instanceof ReadableByteStreamController;
1036}
1037function IsReadableStreamBYOBRequest(x) {
1038 if (!typeIsObject(x)) {
1039 return false;
1040 }
1041 if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
1042 return false;
1043 }
1044 return x instanceof ReadableStreamBYOBRequest;
1045}
1046function ReadableByteStreamControllerCallPullIfNeeded(controller) {
1047 const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
1048 if (!shouldPull) {
1049 return;
1050 }
1051 if (controller._pulling) {
1052 controller._pullAgain = true;
1053 return;
1054 }
1055 controller._pulling = true;
1056 // TODO: Test controller argument
1057 const pullPromise = controller._pullAlgorithm();
1058 uponPromise(pullPromise, () => {
1059 controller._pulling = false;
1060 if (controller._pullAgain) {
1061 controller._pullAgain = false;
1062 ReadableByteStreamControllerCallPullIfNeeded(controller);
1063 }
1064 return null;
1065 }, e => {
1066 ReadableByteStreamControllerError(controller, e);
1067 return null;
1068 });
1069}
1070function ReadableByteStreamControllerClearPendingPullIntos(controller) {
1071 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1072 controller._pendingPullIntos = new SimpleQueue();
1073}
1074function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
1075 let done = false;
1076 if (stream._state === 'closed') {
1077 done = true;
1078 }
1079 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
1080 if (pullIntoDescriptor.readerType === 'default') {
1081 ReadableStreamFulfillReadRequest(stream, filledView, done);
1082 }
1083 else {
1084 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
1085 }
1086}
1087function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
1088 const bytesFilled = pullIntoDescriptor.bytesFilled;
1089 const elementSize = pullIntoDescriptor.elementSize;
1090 return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
1091}
1092function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
1093 controller._queue.push({ buffer, byteOffset, byteLength });
1094 controller._queueTotalSize += byteLength;
1095}
1096function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) {
1097 let clonedChunk;
1098 try {
1099 clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);
1100 }
1101 catch (cloneE) {
1102 ReadableByteStreamControllerError(controller, cloneE);
1103 throw cloneE;
1104 }
1105 ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);
1106}
1107function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) {
1108 if (firstDescriptor.bytesFilled > 0) {
1109 ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled);
1110 }
1111 ReadableByteStreamControllerShiftPendingPullInto(controller);
1112}
1113function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
1114 const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
1115 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
1116 let totalBytesToCopyRemaining = maxBytesToCopy;
1117 let ready = false;
1118 const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;
1119 const maxAlignedBytes = maxBytesFilled - remainderBytes;
1120 // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1121 // of the queue, so the underlying source can keep filling it.
1122 if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {
1123 totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
1124 ready = true;
1125 }
1126 const queue = controller._queue;
1127 while (totalBytesToCopyRemaining > 0) {
1128 const headOfQueue = queue.peek();
1129 const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
1130 const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
1131 CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
1132 if (headOfQueue.byteLength === bytesToCopy) {
1133 queue.shift();
1134 }
1135 else {
1136 headOfQueue.byteOffset += bytesToCopy;
1137 headOfQueue.byteLength -= bytesToCopy;
1138 }
1139 controller._queueTotalSize -= bytesToCopy;
1140 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
1141 totalBytesToCopyRemaining -= bytesToCopy;
1142 }
1143 return ready;
1144}
1145function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
1146 pullIntoDescriptor.bytesFilled += size;
1147}
1148function ReadableByteStreamControllerHandleQueueDrain(controller) {
1149 if (controller._queueTotalSize === 0 && controller._closeRequested) {
1150 ReadableByteStreamControllerClearAlgorithms(controller);
1151 ReadableStreamClose(controller._controlledReadableByteStream);
1152 }
1153 else {
1154 ReadableByteStreamControllerCallPullIfNeeded(controller);
1155 }
1156}
1157function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
1158 if (controller._byobRequest === null) {
1159 return;
1160 }
1161 controller._byobRequest._associatedReadableByteStreamController = undefined;
1162 controller._byobRequest._view = null;
1163 controller._byobRequest = null;
1164}
1165function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
1166 while (controller._pendingPullIntos.length > 0) {
1167 if (controller._queueTotalSize === 0) {
1168 return;
1169 }
1170 const pullIntoDescriptor = controller._pendingPullIntos.peek();
1171 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
1172 ReadableByteStreamControllerShiftPendingPullInto(controller);
1173 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
1174 }
1175 }
1176}
1177function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) {
1178 const reader = controller._controlledReadableByteStream._reader;
1179 while (reader._readRequests.length > 0) {
1180 if (controller._queueTotalSize === 0) {
1181 return;
1182 }
1183 const readRequest = reader._readRequests.shift();
1184 ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);
1185 }
1186}
1187function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) {
1188 const stream = controller._controlledReadableByteStream;
1189 const ctor = view.constructor;
1190 const elementSize = arrayBufferViewElementSize(ctor);
1191 const { byteOffset, byteLength } = view;
1192 const minimumFill = min * elementSize;
1193 let buffer;
1194 try {
1195 buffer = TransferArrayBuffer(view.buffer);
1196 }
1197 catch (e) {
1198 readIntoRequest._errorSteps(e);
1199 return;
1200 }
1201 const pullIntoDescriptor = {
1202 buffer,
1203 bufferByteLength: buffer.byteLength,
1204 byteOffset,
1205 byteLength,
1206 bytesFilled: 0,
1207 minimumFill,
1208 elementSize,
1209 viewConstructor: ctor,
1210 readerType: 'byob'
1211 };
1212 if (controller._pendingPullIntos.length > 0) {
1213 controller._pendingPullIntos.push(pullIntoDescriptor);
1214 // No ReadableByteStreamControllerCallPullIfNeeded() call since:
1215 // - No change happens on desiredSize
1216 // - The source has already been notified of that there's at least 1 pending read(view)
1217 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
1218 return;
1219 }
1220 if (stream._state === 'closed') {
1221 const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
1222 readIntoRequest._closeSteps(emptyView);
1223 return;
1224 }
1225 if (controller._queueTotalSize > 0) {
1226 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
1227 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
1228 ReadableByteStreamControllerHandleQueueDrain(controller);
1229 readIntoRequest._chunkSteps(filledView);
1230 return;
1231 }
1232 if (controller._closeRequested) {
1233 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
1234 ReadableByteStreamControllerError(controller, e);
1235 readIntoRequest._errorSteps(e);
1236 return;
1237 }
1238 }
1239 controller._pendingPullIntos.push(pullIntoDescriptor);
1240 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
1241 ReadableByteStreamControllerCallPullIfNeeded(controller);
1242}
1243function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
1244 if (firstDescriptor.readerType === 'none') {
1245 ReadableByteStreamControllerShiftPendingPullInto(controller);
1246 }
1247 const stream = controller._controlledReadableByteStream;
1248 if (ReadableStreamHasBYOBReader(stream)) {
1249 while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
1250 const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
1251 ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
1252 }
1253 }
1254}
1255function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
1256 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
1257 if (pullIntoDescriptor.readerType === 'none') {
1258 ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);
1259 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1260 return;
1261 }
1262 if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {
1263 // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1264 // of the queue, so the underlying source can keep filling it.
1265 return;
1266 }
1267 ReadableByteStreamControllerShiftPendingPullInto(controller);
1268 const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
1269 if (remainderSize > 0) {
1270 const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
1271 ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize);
1272 }
1273 pullIntoDescriptor.bytesFilled -= remainderSize;
1274 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
1275 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1276}
1277function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
1278 const firstDescriptor = controller._pendingPullIntos.peek();
1279 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1280 const state = controller._controlledReadableByteStream._state;
1281 if (state === 'closed') {
1282 ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
1283 }
1284 else {
1285 ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
1286 }
1287 ReadableByteStreamControllerCallPullIfNeeded(controller);
1288}
1289function ReadableByteStreamControllerShiftPendingPullInto(controller) {
1290 const descriptor = controller._pendingPullIntos.shift();
1291 return descriptor;
1292}
1293function ReadableByteStreamControllerShouldCallPull(controller) {
1294 const stream = controller._controlledReadableByteStream;
1295 if (stream._state !== 'readable') {
1296 return false;
1297 }
1298 if (controller._closeRequested) {
1299 return false;
1300 }
1301 if (!controller._started) {
1302 return false;
1303 }
1304 if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
1305 return true;
1306 }
1307 if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
1308 return true;
1309 }
1310 const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
1311 if (desiredSize > 0) {
1312 return true;
1313 }
1314 return false;
1315}
1316function ReadableByteStreamControllerClearAlgorithms(controller) {
1317 controller._pullAlgorithm = undefined;
1318 controller._cancelAlgorithm = undefined;
1319}
1320// A client of ReadableByteStreamController may use these functions directly to bypass state check.
1321function ReadableByteStreamControllerClose(controller) {
1322 const stream = controller._controlledReadableByteStream;
1323 if (controller._closeRequested || stream._state !== 'readable') {
1324 return;
1325 }
1326 if (controller._queueTotalSize > 0) {
1327 controller._closeRequested = true;
1328 return;
1329 }
1330 if (controller._pendingPullIntos.length > 0) {
1331 const firstPendingPullInto = controller._pendingPullIntos.peek();
1332 if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {
1333 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
1334 ReadableByteStreamControllerError(controller, e);
1335 throw e;
1336 }
1337 }
1338 ReadableByteStreamControllerClearAlgorithms(controller);
1339 ReadableStreamClose(stream);
1340}
1341function ReadableByteStreamControllerEnqueue(controller, chunk) {
1342 const stream = controller._controlledReadableByteStream;
1343 if (controller._closeRequested || stream._state !== 'readable') {
1344 return;
1345 }
1346 const { buffer, byteOffset, byteLength } = chunk;
1347 if (IsDetachedBuffer(buffer)) {
1348 throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued');
1349 }
1350 const transferredBuffer = TransferArrayBuffer(buffer);
1351 if (controller._pendingPullIntos.length > 0) {
1352 const firstPendingPullInto = controller._pendingPullIntos.peek();
1353 if (IsDetachedBuffer(firstPendingPullInto.buffer)) {
1354 throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk');
1355 }
1356 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1357 firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
1358 if (firstPendingPullInto.readerType === 'none') {
1359 ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);
1360 }
1361 }
1362 if (ReadableStreamHasDefaultReader(stream)) {
1363 ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
1364 if (ReadableStreamGetNumReadRequests(stream) === 0) {
1365 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1366 }
1367 else {
1368 if (controller._pendingPullIntos.length > 0) {
1369 ReadableByteStreamControllerShiftPendingPullInto(controller);
1370 }
1371 const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
1372 ReadableStreamFulfillReadRequest(stream, transferredView, false);
1373 }
1374 }
1375 else if (ReadableStreamHasBYOBReader(stream)) {
1376 // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.
1377 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1378 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1379 }
1380 else {
1381 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1382 }
1383 ReadableByteStreamControllerCallPullIfNeeded(controller);
1384}
1385function ReadableByteStreamControllerError(controller, e) {
1386 const stream = controller._controlledReadableByteStream;
1387 if (stream._state !== 'readable') {
1388 return;
1389 }
1390 ReadableByteStreamControllerClearPendingPullIntos(controller);
1391 ResetQueue(controller);
1392 ReadableByteStreamControllerClearAlgorithms(controller);
1393 ReadableStreamError(stream, e);
1394}
1395function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
1396 const entry = controller._queue.shift();
1397 controller._queueTotalSize -= entry.byteLength;
1398 ReadableByteStreamControllerHandleQueueDrain(controller);
1399 const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
1400 readRequest._chunkSteps(view);
1401}
1402function ReadableByteStreamControllerGetBYOBRequest(controller) {
1403 if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
1404 const firstDescriptor = controller._pendingPullIntos.peek();
1405 const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
1406 const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
1407 SetUpReadableStreamBYOBRequest(byobRequest, controller, view);
1408 controller._byobRequest = byobRequest;
1409 }
1410 return controller._byobRequest;
1411}
1412function ReadableByteStreamControllerGetDesiredSize(controller) {
1413 const state = controller._controlledReadableByteStream._state;
1414 if (state === 'errored') {
1415 return null;
1416 }
1417 if (state === 'closed') {
1418 return 0;
1419 }
1420 return controller._strategyHWM - controller._queueTotalSize;
1421}
1422function ReadableByteStreamControllerRespond(controller, bytesWritten) {
1423 const firstDescriptor = controller._pendingPullIntos.peek();
1424 const state = controller._controlledReadableByteStream._state;
1425 if (state === 'closed') {
1426 if (bytesWritten !== 0) {
1427 throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
1428 }
1429 }
1430 else {
1431 if (bytesWritten === 0) {
1432 throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');
1433 }
1434 if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {
1435 throw new RangeError('bytesWritten out of range');
1436 }
1437 }
1438 firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
1439 ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
1440}
1441function ReadableByteStreamControllerRespondWithNewView(controller, view) {
1442 const firstDescriptor = controller._pendingPullIntos.peek();
1443 const state = controller._controlledReadableByteStream._state;
1444 if (state === 'closed') {
1445 if (view.byteLength !== 0) {
1446 throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream');
1447 }
1448 }
1449 else {
1450 if (view.byteLength === 0) {
1451 throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream');
1452 }
1453 }
1454 if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
1455 throw new RangeError('The region specified by view does not match byobRequest');
1456 }
1457 if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {
1458 throw new RangeError('The buffer of view has different capacity than byobRequest');
1459 }
1460 if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {
1461 throw new RangeError('The region specified by view is larger than byobRequest');
1462 }
1463 const viewByteLength = view.byteLength;
1464 firstDescriptor.buffer = TransferArrayBuffer(view.buffer);
1465 ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
1466}
1467function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
1468 controller._controlledReadableByteStream = stream;
1469 controller._pullAgain = false;
1470 controller._pulling = false;
1471 controller._byobRequest = null;
1472 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
1473 controller._queue = controller._queueTotalSize = undefined;
1474 ResetQueue(controller);
1475 controller._closeRequested = false;
1476 controller._started = false;
1477 controller._strategyHWM = highWaterMark;
1478 controller._pullAlgorithm = pullAlgorithm;
1479 controller._cancelAlgorithm = cancelAlgorithm;
1480 controller._autoAllocateChunkSize = autoAllocateChunkSize;
1481 controller._pendingPullIntos = new SimpleQueue();
1482 stream._readableStreamController = controller;
1483 const startResult = startAlgorithm();
1484 uponPromise(promiseResolvedWith(startResult), () => {
1485 controller._started = true;
1486 ReadableByteStreamControllerCallPullIfNeeded(controller);
1487 return null;
1488 }, r => {
1489 ReadableByteStreamControllerError(controller, r);
1490 return null;
1491 });
1492}
1493function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
1494 const controller = Object.create(ReadableByteStreamController.prototype);
1495 let startAlgorithm;
1496 let pullAlgorithm;
1497 let cancelAlgorithm;
1498 if (underlyingByteSource.start !== undefined) {
1499 startAlgorithm = () => underlyingByteSource.start(controller);
1500 }
1501 else {
1502 startAlgorithm = () => undefined;
1503 }
1504 if (underlyingByteSource.pull !== undefined) {
1505 pullAlgorithm = () => underlyingByteSource.pull(controller);
1506 }
1507 else {
1508 pullAlgorithm = () => promiseResolvedWith(undefined);
1509 }
1510 if (underlyingByteSource.cancel !== undefined) {
1511 cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
1512 }
1513 else {
1514 cancelAlgorithm = () => promiseResolvedWith(undefined);
1515 }
1516 const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
1517 if (autoAllocateChunkSize === 0) {
1518 throw new TypeError('autoAllocateChunkSize must be greater than 0');
1519 }
1520 SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
1521}
1522function SetUpReadableStreamBYOBRequest(request, controller, view) {
1523 request._associatedReadableByteStreamController = controller;
1524 request._view = view;
1525}
1526// Helper functions for the ReadableStreamBYOBRequest.
1527function byobRequestBrandCheckException(name) {
1528 return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
1529}
1530// Helper functions for the ReadableByteStreamController.
1531function byteStreamControllerBrandCheckException(name) {
1532 return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
1533}
1534
1535function convertReaderOptions(options, context) {
1536 assertDictionary(options, context);
1537 const mode = options === null || options === void 0 ? void 0 : options.mode;
1538 return {
1539 mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
1540 };
1541}
1542function convertReadableStreamReaderMode(mode, context) {
1543 mode = `${mode}`;
1544 if (mode !== 'byob') {
1545 throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
1546 }
1547 return mode;
1548}
1549function convertByobReadOptions(options, context) {
1550 var _a;
1551 assertDictionary(options, context);
1552 const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1;
1553 return {
1554 min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`)
1555 };
1556}
1557
1558// Abstract operations for the ReadableStream.
1559function AcquireReadableStreamBYOBReader(stream) {
1560 return new ReadableStreamBYOBReader(stream);
1561}
1562// ReadableStream API exposed for controllers.
1563function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
1564 stream._reader._readIntoRequests.push(readIntoRequest);
1565}
1566function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
1567 const reader = stream._reader;
1568 const readIntoRequest = reader._readIntoRequests.shift();
1569 if (done) {
1570 readIntoRequest._closeSteps(chunk);
1571 }
1572 else {
1573 readIntoRequest._chunkSteps(chunk);
1574 }
1575}
1576function ReadableStreamGetNumReadIntoRequests(stream) {
1577 return stream._reader._readIntoRequests.length;
1578}
1579function ReadableStreamHasBYOBReader(stream) {
1580 const reader = stream._reader;
1581 if (reader === undefined) {
1582 return false;
1583 }
1584 if (!IsReadableStreamBYOBReader(reader)) {
1585 return false;
1586 }
1587 return true;
1588}
1589/**
1590 * A BYOB reader vended by a {@link ReadableStream}.
1591 *
1592 * @public
1593 */
1594class ReadableStreamBYOBReader {
1595 constructor(stream) {
1596 assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');
1597 assertReadableStream(stream, 'First parameter');
1598 if (IsReadableStreamLocked(stream)) {
1599 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
1600 }
1601 if (!IsReadableByteStreamController(stream._readableStreamController)) {
1602 throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
1603 'source');
1604 }
1605 ReadableStreamReaderGenericInitialize(this, stream);
1606 this._readIntoRequests = new SimpleQueue();
1607 }
1608 /**
1609 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
1610 * the reader's lock is released before the stream finishes closing.
1611 */
1612 get closed() {
1613 if (!IsReadableStreamBYOBReader(this)) {
1614 return promiseRejectedWith(byobReaderBrandCheckException('closed'));
1615 }
1616 return this._closedPromise;
1617 }
1618 /**
1619 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
1620 */
1621 cancel(reason = undefined) {
1622 if (!IsReadableStreamBYOBReader(this)) {
1623 return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
1624 }
1625 if (this._ownerReadableStream === undefined) {
1626 return promiseRejectedWith(readerLockException('cancel'));
1627 }
1628 return ReadableStreamReaderGenericCancel(this, reason);
1629 }
1630 read(view, rawOptions = {}) {
1631 if (!IsReadableStreamBYOBReader(this)) {
1632 return promiseRejectedWith(byobReaderBrandCheckException('read'));
1633 }
1634 if (!ArrayBuffer.isView(view)) {
1635 return promiseRejectedWith(new TypeError('view must be an array buffer view'));
1636 }
1637 if (view.byteLength === 0) {
1638 return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));
1639 }
1640 if (view.buffer.byteLength === 0) {
1641 return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
1642 }
1643 if (IsDetachedBuffer(view.buffer)) {
1644 return promiseRejectedWith(new TypeError('view\'s buffer has been detached'));
1645 }
1646 let options;
1647 try {
1648 options = convertByobReadOptions(rawOptions, 'options');
1649 }
1650 catch (e) {
1651 return promiseRejectedWith(e);
1652 }
1653 const min = options.min;
1654 if (min === 0) {
1655 return promiseRejectedWith(new TypeError('options.min must be greater than 0'));
1656 }
1657 if (!isDataView(view)) {
1658 if (min > view.length) {
1659 return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length'));
1660 }
1661 }
1662 else if (min > view.byteLength) {
1663 return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength'));
1664 }
1665 if (this._ownerReadableStream === undefined) {
1666 return promiseRejectedWith(readerLockException('read from'));
1667 }
1668 let resolvePromise;
1669 let rejectPromise;
1670 const promise = newPromise((resolve, reject) => {
1671 resolvePromise = resolve;
1672 rejectPromise = reject;
1673 });
1674 const readIntoRequest = {
1675 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
1676 _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
1677 _errorSteps: e => rejectPromise(e)
1678 };
1679 ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);
1680 return promise;
1681 }
1682 /**
1683 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
1684 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
1685 * from now on; otherwise, the reader will appear closed.
1686 *
1687 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
1688 * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
1689 * do so will throw a `TypeError` and leave the reader locked to the stream.
1690 */
1691 releaseLock() {
1692 if (!IsReadableStreamBYOBReader(this)) {
1693 throw byobReaderBrandCheckException('releaseLock');
1694 }
1695 if (this._ownerReadableStream === undefined) {
1696 return;
1697 }
1698 ReadableStreamBYOBReaderRelease(this);
1699 }
1700}
1701Object.defineProperties(ReadableStreamBYOBReader.prototype, {
1702 cancel: { enumerable: true },
1703 read: { enumerable: true },
1704 releaseLock: { enumerable: true },
1705 closed: { enumerable: true }
1706});
1707setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');
1708setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');
1709setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');
1710if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1711 Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
1712 value: 'ReadableStreamBYOBReader',
1713 configurable: true
1714 });
1715}
1716// Abstract operations for the readers.
1717function IsReadableStreamBYOBReader(x) {
1718 if (!typeIsObject(x)) {
1719 return false;
1720 }
1721 if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
1722 return false;
1723 }
1724 return x instanceof ReadableStreamBYOBReader;
1725}
1726function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) {
1727 const stream = reader._ownerReadableStream;
1728 stream._disturbed = true;
1729 if (stream._state === 'errored') {
1730 readIntoRequest._errorSteps(stream._storedError);
1731 }
1732 else {
1733 ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest);
1734 }
1735}
1736function ReadableStreamBYOBReaderRelease(reader) {
1737 ReadableStreamReaderGenericRelease(reader);
1738 const e = new TypeError('Reader was released');
1739 ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
1740}
1741function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) {
1742 const readIntoRequests = reader._readIntoRequests;
1743 reader._readIntoRequests = new SimpleQueue();
1744 readIntoRequests.forEach(readIntoRequest => {
1745 readIntoRequest._errorSteps(e);
1746 });
1747}
1748// Helper functions for the ReadableStreamBYOBReader.
1749function byobReaderBrandCheckException(name) {
1750 return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
1751}
1752
1753function ExtractHighWaterMark(strategy, defaultHWM) {
1754 const { highWaterMark } = strategy;
1755 if (highWaterMark === undefined) {
1756 return defaultHWM;
1757 }
1758 if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
1759 throw new RangeError('Invalid highWaterMark');
1760 }
1761 return highWaterMark;
1762}
1763function ExtractSizeAlgorithm(strategy) {
1764 const { size } = strategy;
1765 if (!size) {
1766 return () => 1;
1767 }
1768 return size;
1769}
1770
1771function convertQueuingStrategy(init, context) {
1772 assertDictionary(init, context);
1773 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
1774 const size = init === null || init === void 0 ? void 0 : init.size;
1775 return {
1776 highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),
1777 size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)
1778 };
1779}
1780function convertQueuingStrategySize(fn, context) {
1781 assertFunction(fn, context);
1782 return chunk => convertUnrestrictedDouble(fn(chunk));
1783}
1784
1785function convertUnderlyingSink(original, context) {
1786 assertDictionary(original, context);
1787 const abort = original === null || original === void 0 ? void 0 : original.abort;
1788 const close = original === null || original === void 0 ? void 0 : original.close;
1789 const start = original === null || original === void 0 ? void 0 : original.start;
1790 const type = original === null || original === void 0 ? void 0 : original.type;
1791 const write = original === null || original === void 0 ? void 0 : original.write;
1792 return {
1793 abort: abort === undefined ?
1794 undefined :
1795 convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
1796 close: close === undefined ?
1797 undefined :
1798 convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
1799 start: start === undefined ?
1800 undefined :
1801 convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
1802 write: write === undefined ?
1803 undefined :
1804 convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
1805 type
1806 };
1807}
1808function convertUnderlyingSinkAbortCallback(fn, original, context) {
1809 assertFunction(fn, context);
1810 return (reason) => promiseCall(fn, original, [reason]);
1811}
1812function convertUnderlyingSinkCloseCallback(fn, original, context) {
1813 assertFunction(fn, context);
1814 return () => promiseCall(fn, original, []);
1815}
1816function convertUnderlyingSinkStartCallback(fn, original, context) {
1817 assertFunction(fn, context);
1818 return (controller) => reflectCall(fn, original, [controller]);
1819}
1820function convertUnderlyingSinkWriteCallback(fn, original, context) {
1821 assertFunction(fn, context);
1822 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
1823}
1824
1825function assertWritableStream(x, context) {
1826 if (!IsWritableStream(x)) {
1827 throw new TypeError(`${context} is not a WritableStream.`);
1828 }
1829}
1830
1831function isAbortSignal(value) {
1832 if (typeof value !== 'object' || value === null) {
1833 return false;
1834 }
1835 try {
1836 return typeof value.aborted === 'boolean';
1837 }
1838 catch (_a) {
1839 // AbortSignal.prototype.aborted throws if its brand check fails
1840 return false;
1841 }
1842}
1843const supportsAbortController = typeof AbortController === 'function';
1844/**
1845 * Construct a new AbortController, if supported by the platform.
1846 *
1847 * @internal
1848 */
1849function createAbortController() {
1850 if (supportsAbortController) {
1851 return new AbortController();
1852 }
1853 return undefined;
1854}
1855
1856/**
1857 * A writable stream represents a destination for data, into which you can write.
1858 *
1859 * @public
1860 */
1861class WritableStream {
1862 constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
1863 if (rawUnderlyingSink === undefined) {
1864 rawUnderlyingSink = null;
1865 }
1866 else {
1867 assertObject(rawUnderlyingSink, 'First parameter');
1868 }
1869 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
1870 const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');
1871 InitializeWritableStream(this);
1872 const type = underlyingSink.type;
1873 if (type !== undefined) {
1874 throw new RangeError('Invalid type is specified');
1875 }
1876 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
1877 const highWaterMark = ExtractHighWaterMark(strategy, 1);
1878 SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
1879 }
1880 /**
1881 * Returns whether or not the writable stream is locked to a writer.
1882 */
1883 get locked() {
1884 if (!IsWritableStream(this)) {
1885 throw streamBrandCheckException$2('locked');
1886 }
1887 return IsWritableStreamLocked(this);
1888 }
1889 /**
1890 * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
1891 * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
1892 * mechanism of the underlying sink.
1893 *
1894 * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
1895 * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
1896 * the stream) if the stream is currently locked.
1897 */
1898 abort(reason = undefined) {
1899 if (!IsWritableStream(this)) {
1900 return promiseRejectedWith(streamBrandCheckException$2('abort'));
1901 }
1902 if (IsWritableStreamLocked(this)) {
1903 return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
1904 }
1905 return WritableStreamAbort(this, reason);
1906 }
1907 /**
1908 * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
1909 * close behavior. During this time any further attempts to write will fail (without erroring the stream).
1910 *
1911 * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
1912 * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
1913 * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
1914 */
1915 close() {
1916 if (!IsWritableStream(this)) {
1917 return promiseRejectedWith(streamBrandCheckException$2('close'));
1918 }
1919 if (IsWritableStreamLocked(this)) {
1920 return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
1921 }
1922 if (WritableStreamCloseQueuedOrInFlight(this)) {
1923 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
1924 }
1925 return WritableStreamClose(this);
1926 }
1927 /**
1928 * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
1929 * is locked, no other writer can be acquired until this one is released.
1930 *
1931 * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
1932 * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
1933 * the same time, which would cause the resulting written data to be unpredictable and probably useless.
1934 */
1935 getWriter() {
1936 if (!IsWritableStream(this)) {
1937 throw streamBrandCheckException$2('getWriter');
1938 }
1939 return AcquireWritableStreamDefaultWriter(this);
1940 }
1941}
1942Object.defineProperties(WritableStream.prototype, {
1943 abort: { enumerable: true },
1944 close: { enumerable: true },
1945 getWriter: { enumerable: true },
1946 locked: { enumerable: true }
1947});
1948setFunctionName(WritableStream.prototype.abort, 'abort');
1949setFunctionName(WritableStream.prototype.close, 'close');
1950setFunctionName(WritableStream.prototype.getWriter, 'getWriter');
1951if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1952 Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
1953 value: 'WritableStream',
1954 configurable: true
1955 });
1956}
1957// Abstract operations for the WritableStream.
1958function AcquireWritableStreamDefaultWriter(stream) {
1959 return new WritableStreamDefaultWriter(stream);
1960}
1961// Throws if and only if startAlgorithm throws.
1962function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
1963 const stream = Object.create(WritableStream.prototype);
1964 InitializeWritableStream(stream);
1965 const controller = Object.create(WritableStreamDefaultController.prototype);
1966 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
1967 return stream;
1968}
1969function InitializeWritableStream(stream) {
1970 stream._state = 'writable';
1971 // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is
1972 // 'erroring' or 'errored'. May be set to an undefined value.
1973 stream._storedError = undefined;
1974 stream._writer = undefined;
1975 // Initialize to undefined first because the constructor of the controller checks this
1976 // variable to validate the caller.
1977 stream._writableStreamController = undefined;
1978 // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data
1979 // producer without waiting for the queued writes to finish.
1980 stream._writeRequests = new SimpleQueue();
1981 // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents
1982 // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.
1983 stream._inFlightWriteRequest = undefined;
1984 // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer
1985 // has been detached.
1986 stream._closeRequest = undefined;
1987 // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it
1988 // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.
1989 stream._inFlightCloseRequest = undefined;
1990 // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.
1991 stream._pendingAbortRequest = undefined;
1992 // The backpressure signal set by the controller.
1993 stream._backpressure = false;
1994}
1995function IsWritableStream(x) {
1996 if (!typeIsObject(x)) {
1997 return false;
1998 }
1999 if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
2000 return false;
2001 }
2002 return x instanceof WritableStream;
2003}
2004function IsWritableStreamLocked(stream) {
2005 if (stream._writer === undefined) {
2006 return false;
2007 }
2008 return true;
2009}
2010function WritableStreamAbort(stream, reason) {
2011 var _a;
2012 if (stream._state === 'closed' || stream._state === 'errored') {
2013 return promiseResolvedWith(undefined);
2014 }
2015 stream._writableStreamController._abortReason = reason;
2016 (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason);
2017 // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',
2018 // but it doesn't know that signaling abort runs author code that might have changed the state.
2019 // Widen the type again by casting to WritableStreamState.
2020 const state = stream._state;
2021 if (state === 'closed' || state === 'errored') {
2022 return promiseResolvedWith(undefined);
2023 }
2024 if (stream._pendingAbortRequest !== undefined) {
2025 return stream._pendingAbortRequest._promise;
2026 }
2027 let wasAlreadyErroring = false;
2028 if (state === 'erroring') {
2029 wasAlreadyErroring = true;
2030 // reason will not be used, so don't keep a reference to it.
2031 reason = undefined;
2032 }
2033 const promise = newPromise((resolve, reject) => {
2034 stream._pendingAbortRequest = {
2035 _promise: undefined,
2036 _resolve: resolve,
2037 _reject: reject,
2038 _reason: reason,
2039 _wasAlreadyErroring: wasAlreadyErroring
2040 };
2041 });
2042 stream._pendingAbortRequest._promise = promise;
2043 if (!wasAlreadyErroring) {
2044 WritableStreamStartErroring(stream, reason);
2045 }
2046 return promise;
2047}
2048function WritableStreamClose(stream) {
2049 const state = stream._state;
2050 if (state === 'closed' || state === 'errored') {
2051 return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
2052 }
2053 const promise = newPromise((resolve, reject) => {
2054 const closeRequest = {
2055 _resolve: resolve,
2056 _reject: reject
2057 };
2058 stream._closeRequest = closeRequest;
2059 });
2060 const writer = stream._writer;
2061 if (writer !== undefined && stream._backpressure && state === 'writable') {
2062 defaultWriterReadyPromiseResolve(writer);
2063 }
2064 WritableStreamDefaultControllerClose(stream._writableStreamController);
2065 return promise;
2066}
2067// WritableStream API exposed for controllers.
2068function WritableStreamAddWriteRequest(stream) {
2069 const promise = newPromise((resolve, reject) => {
2070 const writeRequest = {
2071 _resolve: resolve,
2072 _reject: reject
2073 };
2074 stream._writeRequests.push(writeRequest);
2075 });
2076 return promise;
2077}
2078function WritableStreamDealWithRejection(stream, error) {
2079 const state = stream._state;
2080 if (state === 'writable') {
2081 WritableStreamStartErroring(stream, error);
2082 return;
2083 }
2084 WritableStreamFinishErroring(stream);
2085}
2086function WritableStreamStartErroring(stream, reason) {
2087 const controller = stream._writableStreamController;
2088 stream._state = 'erroring';
2089 stream._storedError = reason;
2090 const writer = stream._writer;
2091 if (writer !== undefined) {
2092 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
2093 }
2094 if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
2095 WritableStreamFinishErroring(stream);
2096 }
2097}
2098function WritableStreamFinishErroring(stream) {
2099 stream._state = 'errored';
2100 stream._writableStreamController[ErrorSteps]();
2101 const storedError = stream._storedError;
2102 stream._writeRequests.forEach(writeRequest => {
2103 writeRequest._reject(storedError);
2104 });
2105 stream._writeRequests = new SimpleQueue();
2106 if (stream._pendingAbortRequest === undefined) {
2107 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2108 return;
2109 }
2110 const abortRequest = stream._pendingAbortRequest;
2111 stream._pendingAbortRequest = undefined;
2112 if (abortRequest._wasAlreadyErroring) {
2113 abortRequest._reject(storedError);
2114 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2115 return;
2116 }
2117 const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
2118 uponPromise(promise, () => {
2119 abortRequest._resolve();
2120 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2121 return null;
2122 }, (reason) => {
2123 abortRequest._reject(reason);
2124 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2125 return null;
2126 });
2127}
2128function WritableStreamFinishInFlightWrite(stream) {
2129 stream._inFlightWriteRequest._resolve(undefined);
2130 stream._inFlightWriteRequest = undefined;
2131}
2132function WritableStreamFinishInFlightWriteWithError(stream, error) {
2133 stream._inFlightWriteRequest._reject(error);
2134 stream._inFlightWriteRequest = undefined;
2135 WritableStreamDealWithRejection(stream, error);
2136}
2137function WritableStreamFinishInFlightClose(stream) {
2138 stream._inFlightCloseRequest._resolve(undefined);
2139 stream._inFlightCloseRequest = undefined;
2140 const state = stream._state;
2141 if (state === 'erroring') {
2142 // The error was too late to do anything, so it is ignored.
2143 stream._storedError = undefined;
2144 if (stream._pendingAbortRequest !== undefined) {
2145 stream._pendingAbortRequest._resolve();
2146 stream._pendingAbortRequest = undefined;
2147 }
2148 }
2149 stream._state = 'closed';
2150 const writer = stream._writer;
2151 if (writer !== undefined) {
2152 defaultWriterClosedPromiseResolve(writer);
2153 }
2154}
2155function WritableStreamFinishInFlightCloseWithError(stream, error) {
2156 stream._inFlightCloseRequest._reject(error);
2157 stream._inFlightCloseRequest = undefined;
2158 // Never execute sink abort() after sink close().
2159 if (stream._pendingAbortRequest !== undefined) {
2160 stream._pendingAbortRequest._reject(error);
2161 stream._pendingAbortRequest = undefined;
2162 }
2163 WritableStreamDealWithRejection(stream, error);
2164}
2165// TODO(ricea): Fix alphabetical order.
2166function WritableStreamCloseQueuedOrInFlight(stream) {
2167 if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
2168 return false;
2169 }
2170 return true;
2171}
2172function WritableStreamHasOperationMarkedInFlight(stream) {
2173 if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
2174 return false;
2175 }
2176 return true;
2177}
2178function WritableStreamMarkCloseRequestInFlight(stream) {
2179 stream._inFlightCloseRequest = stream._closeRequest;
2180 stream._closeRequest = undefined;
2181}
2182function WritableStreamMarkFirstWriteRequestInFlight(stream) {
2183 stream._inFlightWriteRequest = stream._writeRequests.shift();
2184}
2185function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
2186 if (stream._closeRequest !== undefined) {
2187 stream._closeRequest._reject(stream._storedError);
2188 stream._closeRequest = undefined;
2189 }
2190 const writer = stream._writer;
2191 if (writer !== undefined) {
2192 defaultWriterClosedPromiseReject(writer, stream._storedError);
2193 }
2194}
2195function WritableStreamUpdateBackpressure(stream, backpressure) {
2196 const writer = stream._writer;
2197 if (writer !== undefined && backpressure !== stream._backpressure) {
2198 if (backpressure) {
2199 defaultWriterReadyPromiseReset(writer);
2200 }
2201 else {
2202 defaultWriterReadyPromiseResolve(writer);
2203 }
2204 }
2205 stream._backpressure = backpressure;
2206}
2207/**
2208 * A default writer vended by a {@link WritableStream}.
2209 *
2210 * @public
2211 */
2212class WritableStreamDefaultWriter {
2213 constructor(stream) {
2214 assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');
2215 assertWritableStream(stream, 'First parameter');
2216 if (IsWritableStreamLocked(stream)) {
2217 throw new TypeError('This stream has already been locked for exclusive writing by another writer');
2218 }
2219 this._ownerWritableStream = stream;
2220 stream._writer = this;
2221 const state = stream._state;
2222 if (state === 'writable') {
2223 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
2224 defaultWriterReadyPromiseInitialize(this);
2225 }
2226 else {
2227 defaultWriterReadyPromiseInitializeAsResolved(this);
2228 }
2229 defaultWriterClosedPromiseInitialize(this);
2230 }
2231 else if (state === 'erroring') {
2232 defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
2233 defaultWriterClosedPromiseInitialize(this);
2234 }
2235 else if (state === 'closed') {
2236 defaultWriterReadyPromiseInitializeAsResolved(this);
2237 defaultWriterClosedPromiseInitializeAsResolved(this);
2238 }
2239 else {
2240 const storedError = stream._storedError;
2241 defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
2242 defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
2243 }
2244 }
2245 /**
2246 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
2247 * the writer’s lock is released before the stream finishes closing.
2248 */
2249 get closed() {
2250 if (!IsWritableStreamDefaultWriter(this)) {
2251 return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
2252 }
2253 return this._closedPromise;
2254 }
2255 /**
2256 * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
2257 * A producer can use this information to determine the right amount of data to write.
2258 *
2259 * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
2260 * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
2261 * the writer’s lock is released.
2262 */
2263 get desiredSize() {
2264 if (!IsWritableStreamDefaultWriter(this)) {
2265 throw defaultWriterBrandCheckException('desiredSize');
2266 }
2267 if (this._ownerWritableStream === undefined) {
2268 throw defaultWriterLockException('desiredSize');
2269 }
2270 return WritableStreamDefaultWriterGetDesiredSize(this);
2271 }
2272 /**
2273 * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
2274 * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
2275 * back to zero or below, the getter will return a new promise that stays pending until the next transition.
2276 *
2277 * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
2278 * rejected.
2279 */
2280 get ready() {
2281 if (!IsWritableStreamDefaultWriter(this)) {
2282 return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
2283 }
2284 return this._readyPromise;
2285 }
2286 /**
2287 * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
2288 */
2289 abort(reason = undefined) {
2290 if (!IsWritableStreamDefaultWriter(this)) {
2291 return promiseRejectedWith(defaultWriterBrandCheckException('abort'));
2292 }
2293 if (this._ownerWritableStream === undefined) {
2294 return promiseRejectedWith(defaultWriterLockException('abort'));
2295 }
2296 return WritableStreamDefaultWriterAbort(this, reason);
2297 }
2298 /**
2299 * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
2300 */
2301 close() {
2302 if (!IsWritableStreamDefaultWriter(this)) {
2303 return promiseRejectedWith(defaultWriterBrandCheckException('close'));
2304 }
2305 const stream = this._ownerWritableStream;
2306 if (stream === undefined) {
2307 return promiseRejectedWith(defaultWriterLockException('close'));
2308 }
2309 if (WritableStreamCloseQueuedOrInFlight(stream)) {
2310 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
2311 }
2312 return WritableStreamDefaultWriterClose(this);
2313 }
2314 /**
2315 * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
2316 * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
2317 * now on; otherwise, the writer will appear closed.
2318 *
2319 * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
2320 * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
2321 * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
2322 * other producers from writing in an interleaved manner.
2323 */
2324 releaseLock() {
2325 if (!IsWritableStreamDefaultWriter(this)) {
2326 throw defaultWriterBrandCheckException('releaseLock');
2327 }
2328 const stream = this._ownerWritableStream;
2329 if (stream === undefined) {
2330 return;
2331 }
2332 WritableStreamDefaultWriterRelease(this);
2333 }
2334 write(chunk = undefined) {
2335 if (!IsWritableStreamDefaultWriter(this)) {
2336 return promiseRejectedWith(defaultWriterBrandCheckException('write'));
2337 }
2338 if (this._ownerWritableStream === undefined) {
2339 return promiseRejectedWith(defaultWriterLockException('write to'));
2340 }
2341 return WritableStreamDefaultWriterWrite(this, chunk);
2342 }
2343}
2344Object.defineProperties(WritableStreamDefaultWriter.prototype, {
2345 abort: { enumerable: true },
2346 close: { enumerable: true },
2347 releaseLock: { enumerable: true },
2348 write: { enumerable: true },
2349 closed: { enumerable: true },
2350 desiredSize: { enumerable: true },
2351 ready: { enumerable: true }
2352});
2353setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');
2354setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');
2355setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');
2356setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');
2357if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2358 Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
2359 value: 'WritableStreamDefaultWriter',
2360 configurable: true
2361 });
2362}
2363// Abstract operations for the WritableStreamDefaultWriter.
2364function IsWritableStreamDefaultWriter(x) {
2365 if (!typeIsObject(x)) {
2366 return false;
2367 }
2368 if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
2369 return false;
2370 }
2371 return x instanceof WritableStreamDefaultWriter;
2372}
2373// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.
2374function WritableStreamDefaultWriterAbort(writer, reason) {
2375 const stream = writer._ownerWritableStream;
2376 return WritableStreamAbort(stream, reason);
2377}
2378function WritableStreamDefaultWriterClose(writer) {
2379 const stream = writer._ownerWritableStream;
2380 return WritableStreamClose(stream);
2381}
2382function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
2383 const stream = writer._ownerWritableStream;
2384 const state = stream._state;
2385 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
2386 return promiseResolvedWith(undefined);
2387 }
2388 if (state === 'errored') {
2389 return promiseRejectedWith(stream._storedError);
2390 }
2391 return WritableStreamDefaultWriterClose(writer);
2392}
2393function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
2394 if (writer._closedPromiseState === 'pending') {
2395 defaultWriterClosedPromiseReject(writer, error);
2396 }
2397 else {
2398 defaultWriterClosedPromiseResetToRejected(writer, error);
2399 }
2400}
2401function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
2402 if (writer._readyPromiseState === 'pending') {
2403 defaultWriterReadyPromiseReject(writer, error);
2404 }
2405 else {
2406 defaultWriterReadyPromiseResetToRejected(writer, error);
2407 }
2408}
2409function WritableStreamDefaultWriterGetDesiredSize(writer) {
2410 const stream = writer._ownerWritableStream;
2411 const state = stream._state;
2412 if (state === 'errored' || state === 'erroring') {
2413 return null;
2414 }
2415 if (state === 'closed') {
2416 return 0;
2417 }
2418 return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
2419}
2420function WritableStreamDefaultWriterRelease(writer) {
2421 const stream = writer._ownerWritableStream;
2422 const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
2423 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
2424 // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not
2425 // rejected until afterwards. This means that simply testing state will not work.
2426 WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
2427 stream._writer = undefined;
2428 writer._ownerWritableStream = undefined;
2429}
2430function WritableStreamDefaultWriterWrite(writer, chunk) {
2431 const stream = writer._ownerWritableStream;
2432 const controller = stream._writableStreamController;
2433 const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
2434 if (stream !== writer._ownerWritableStream) {
2435 return promiseRejectedWith(defaultWriterLockException('write to'));
2436 }
2437 const state = stream._state;
2438 if (state === 'errored') {
2439 return promiseRejectedWith(stream._storedError);
2440 }
2441 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
2442 return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));
2443 }
2444 if (state === 'erroring') {
2445 return promiseRejectedWith(stream._storedError);
2446 }
2447 const promise = WritableStreamAddWriteRequest(stream);
2448 WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
2449 return promise;
2450}
2451const closeSentinel = {};
2452/**
2453 * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
2454 *
2455 * @public
2456 */
2457class WritableStreamDefaultController {
2458 constructor() {
2459 throw new TypeError('Illegal constructor');
2460 }
2461 /**
2462 * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
2463 *
2464 * @deprecated
2465 * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
2466 * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
2467 */
2468 get abortReason() {
2469 if (!IsWritableStreamDefaultController(this)) {
2470 throw defaultControllerBrandCheckException$2('abortReason');
2471 }
2472 return this._abortReason;
2473 }
2474 /**
2475 * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
2476 */
2477 get signal() {
2478 if (!IsWritableStreamDefaultController(this)) {
2479 throw defaultControllerBrandCheckException$2('signal');
2480 }
2481 if (this._abortController === undefined) {
2482 // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.
2483 // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,
2484 // so instead we only implement support for `signal` if we find a global `AbortController` constructor.
2485 throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');
2486 }
2487 return this._abortController.signal;
2488 }
2489 /**
2490 * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
2491 *
2492 * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
2493 * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
2494 * normal lifecycle of interactions with the underlying sink.
2495 */
2496 error(e = undefined) {
2497 if (!IsWritableStreamDefaultController(this)) {
2498 throw defaultControllerBrandCheckException$2('error');
2499 }
2500 const state = this._controlledWritableStream._state;
2501 if (state !== 'writable') {
2502 // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so
2503 // just treat it as a no-op.
2504 return;
2505 }
2506 WritableStreamDefaultControllerError(this, e);
2507 }
2508 /** @internal */
2509 [AbortSteps](reason) {
2510 const result = this._abortAlgorithm(reason);
2511 WritableStreamDefaultControllerClearAlgorithms(this);
2512 return result;
2513 }
2514 /** @internal */
2515 [ErrorSteps]() {
2516 ResetQueue(this);
2517 }
2518}
2519Object.defineProperties(WritableStreamDefaultController.prototype, {
2520 abortReason: { enumerable: true },
2521 signal: { enumerable: true },
2522 error: { enumerable: true }
2523});
2524if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2525 Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
2526 value: 'WritableStreamDefaultController',
2527 configurable: true
2528 });
2529}
2530// Abstract operations implementing interface required by the WritableStream.
2531function IsWritableStreamDefaultController(x) {
2532 if (!typeIsObject(x)) {
2533 return false;
2534 }
2535 if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
2536 return false;
2537 }
2538 return x instanceof WritableStreamDefaultController;
2539}
2540function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
2541 controller._controlledWritableStream = stream;
2542 stream._writableStreamController = controller;
2543 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
2544 controller._queue = undefined;
2545 controller._queueTotalSize = undefined;
2546 ResetQueue(controller);
2547 controller._abortReason = undefined;
2548 controller._abortController = createAbortController();
2549 controller._started = false;
2550 controller._strategySizeAlgorithm = sizeAlgorithm;
2551 controller._strategyHWM = highWaterMark;
2552 controller._writeAlgorithm = writeAlgorithm;
2553 controller._closeAlgorithm = closeAlgorithm;
2554 controller._abortAlgorithm = abortAlgorithm;
2555 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
2556 WritableStreamUpdateBackpressure(stream, backpressure);
2557 const startResult = startAlgorithm();
2558 const startPromise = promiseResolvedWith(startResult);
2559 uponPromise(startPromise, () => {
2560 controller._started = true;
2561 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2562 return null;
2563 }, r => {
2564 controller._started = true;
2565 WritableStreamDealWithRejection(stream, r);
2566 return null;
2567 });
2568}
2569function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
2570 const controller = Object.create(WritableStreamDefaultController.prototype);
2571 let startAlgorithm;
2572 let writeAlgorithm;
2573 let closeAlgorithm;
2574 let abortAlgorithm;
2575 if (underlyingSink.start !== undefined) {
2576 startAlgorithm = () => underlyingSink.start(controller);
2577 }
2578 else {
2579 startAlgorithm = () => undefined;
2580 }
2581 if (underlyingSink.write !== undefined) {
2582 writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
2583 }
2584 else {
2585 writeAlgorithm = () => promiseResolvedWith(undefined);
2586 }
2587 if (underlyingSink.close !== undefined) {
2588 closeAlgorithm = () => underlyingSink.close();
2589 }
2590 else {
2591 closeAlgorithm = () => promiseResolvedWith(undefined);
2592 }
2593 if (underlyingSink.abort !== undefined) {
2594 abortAlgorithm = reason => underlyingSink.abort(reason);
2595 }
2596 else {
2597 abortAlgorithm = () => promiseResolvedWith(undefined);
2598 }
2599 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
2600}
2601// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
2602function WritableStreamDefaultControllerClearAlgorithms(controller) {
2603 controller._writeAlgorithm = undefined;
2604 controller._closeAlgorithm = undefined;
2605 controller._abortAlgorithm = undefined;
2606 controller._strategySizeAlgorithm = undefined;
2607}
2608function WritableStreamDefaultControllerClose(controller) {
2609 EnqueueValueWithSize(controller, closeSentinel, 0);
2610 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2611}
2612function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
2613 try {
2614 return controller._strategySizeAlgorithm(chunk);
2615 }
2616 catch (chunkSizeE) {
2617 WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
2618 return 1;
2619 }
2620}
2621function WritableStreamDefaultControllerGetDesiredSize(controller) {
2622 return controller._strategyHWM - controller._queueTotalSize;
2623}
2624function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
2625 try {
2626 EnqueueValueWithSize(controller, chunk, chunkSize);
2627 }
2628 catch (enqueueE) {
2629 WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
2630 return;
2631 }
2632 const stream = controller._controlledWritableStream;
2633 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {
2634 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
2635 WritableStreamUpdateBackpressure(stream, backpressure);
2636 }
2637 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2638}
2639// Abstract operations for the WritableStreamDefaultController.
2640function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
2641 const stream = controller._controlledWritableStream;
2642 if (!controller._started) {
2643 return;
2644 }
2645 if (stream._inFlightWriteRequest !== undefined) {
2646 return;
2647 }
2648 const state = stream._state;
2649 if (state === 'erroring') {
2650 WritableStreamFinishErroring(stream);
2651 return;
2652 }
2653 if (controller._queue.length === 0) {
2654 return;
2655 }
2656 const value = PeekQueueValue(controller);
2657 if (value === closeSentinel) {
2658 WritableStreamDefaultControllerProcessClose(controller);
2659 }
2660 else {
2661 WritableStreamDefaultControllerProcessWrite(controller, value);
2662 }
2663}
2664function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
2665 if (controller._controlledWritableStream._state === 'writable') {
2666 WritableStreamDefaultControllerError(controller, error);
2667 }
2668}
2669function WritableStreamDefaultControllerProcessClose(controller) {
2670 const stream = controller._controlledWritableStream;
2671 WritableStreamMarkCloseRequestInFlight(stream);
2672 DequeueValue(controller);
2673 const sinkClosePromise = controller._closeAlgorithm();
2674 WritableStreamDefaultControllerClearAlgorithms(controller);
2675 uponPromise(sinkClosePromise, () => {
2676 WritableStreamFinishInFlightClose(stream);
2677 return null;
2678 }, reason => {
2679 WritableStreamFinishInFlightCloseWithError(stream, reason);
2680 return null;
2681 });
2682}
2683function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
2684 const stream = controller._controlledWritableStream;
2685 WritableStreamMarkFirstWriteRequestInFlight(stream);
2686 const sinkWritePromise = controller._writeAlgorithm(chunk);
2687 uponPromise(sinkWritePromise, () => {
2688 WritableStreamFinishInFlightWrite(stream);
2689 const state = stream._state;
2690 DequeueValue(controller);
2691 if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {
2692 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
2693 WritableStreamUpdateBackpressure(stream, backpressure);
2694 }
2695 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2696 return null;
2697 }, reason => {
2698 if (stream._state === 'writable') {
2699 WritableStreamDefaultControllerClearAlgorithms(controller);
2700 }
2701 WritableStreamFinishInFlightWriteWithError(stream, reason);
2702 return null;
2703 });
2704}
2705function WritableStreamDefaultControllerGetBackpressure(controller) {
2706 const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
2707 return desiredSize <= 0;
2708}
2709// A client of WritableStreamDefaultController may use these functions directly to bypass state check.
2710function WritableStreamDefaultControllerError(controller, error) {
2711 const stream = controller._controlledWritableStream;
2712 WritableStreamDefaultControllerClearAlgorithms(controller);
2713 WritableStreamStartErroring(stream, error);
2714}
2715// Helper functions for the WritableStream.
2716function streamBrandCheckException$2(name) {
2717 return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
2718}
2719// Helper functions for the WritableStreamDefaultController.
2720function defaultControllerBrandCheckException$2(name) {
2721 return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);
2722}
2723// Helper functions for the WritableStreamDefaultWriter.
2724function defaultWriterBrandCheckException(name) {
2725 return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
2726}
2727function defaultWriterLockException(name) {
2728 return new TypeError('Cannot ' + name + ' a stream using a released writer');
2729}
2730function defaultWriterClosedPromiseInitialize(writer) {
2731 writer._closedPromise = newPromise((resolve, reject) => {
2732 writer._closedPromise_resolve = resolve;
2733 writer._closedPromise_reject = reject;
2734 writer._closedPromiseState = 'pending';
2735 });
2736}
2737function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
2738 defaultWriterClosedPromiseInitialize(writer);
2739 defaultWriterClosedPromiseReject(writer, reason);
2740}
2741function defaultWriterClosedPromiseInitializeAsResolved(writer) {
2742 defaultWriterClosedPromiseInitialize(writer);
2743 defaultWriterClosedPromiseResolve(writer);
2744}
2745function defaultWriterClosedPromiseReject(writer, reason) {
2746 if (writer._closedPromise_reject === undefined) {
2747 return;
2748 }
2749 setPromiseIsHandledToTrue(writer._closedPromise);
2750 writer._closedPromise_reject(reason);
2751 writer._closedPromise_resolve = undefined;
2752 writer._closedPromise_reject = undefined;
2753 writer._closedPromiseState = 'rejected';
2754}
2755function defaultWriterClosedPromiseResetToRejected(writer, reason) {
2756 defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
2757}
2758function defaultWriterClosedPromiseResolve(writer) {
2759 if (writer._closedPromise_resolve === undefined) {
2760 return;
2761 }
2762 writer._closedPromise_resolve(undefined);
2763 writer._closedPromise_resolve = undefined;
2764 writer._closedPromise_reject = undefined;
2765 writer._closedPromiseState = 'resolved';
2766}
2767function defaultWriterReadyPromiseInitialize(writer) {
2768 writer._readyPromise = newPromise((resolve, reject) => {
2769 writer._readyPromise_resolve = resolve;
2770 writer._readyPromise_reject = reject;
2771 });
2772 writer._readyPromiseState = 'pending';
2773}
2774function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
2775 defaultWriterReadyPromiseInitialize(writer);
2776 defaultWriterReadyPromiseReject(writer, reason);
2777}
2778function defaultWriterReadyPromiseInitializeAsResolved(writer) {
2779 defaultWriterReadyPromiseInitialize(writer);
2780 defaultWriterReadyPromiseResolve(writer);
2781}
2782function defaultWriterReadyPromiseReject(writer, reason) {
2783 if (writer._readyPromise_reject === undefined) {
2784 return;
2785 }
2786 setPromiseIsHandledToTrue(writer._readyPromise);
2787 writer._readyPromise_reject(reason);
2788 writer._readyPromise_resolve = undefined;
2789 writer._readyPromise_reject = undefined;
2790 writer._readyPromiseState = 'rejected';
2791}
2792function defaultWriterReadyPromiseReset(writer) {
2793 defaultWriterReadyPromiseInitialize(writer);
2794}
2795function defaultWriterReadyPromiseResetToRejected(writer, reason) {
2796 defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
2797}
2798function defaultWriterReadyPromiseResolve(writer) {
2799 if (writer._readyPromise_resolve === undefined) {
2800 return;
2801 }
2802 writer._readyPromise_resolve(undefined);
2803 writer._readyPromise_resolve = undefined;
2804 writer._readyPromise_reject = undefined;
2805 writer._readyPromiseState = 'fulfilled';
2806}
2807
2808/// <reference lib="dom" />
2809function getGlobals() {
2810 if (typeof globalThis !== 'undefined') {
2811 return globalThis;
2812 }
2813 else if (typeof self !== 'undefined') {
2814 return self;
2815 }
2816 else if (typeof global !== 'undefined') {
2817 return global;
2818 }
2819 return undefined;
2820}
2821const globals = getGlobals();
2822
2823/// <reference types="node" />
2824function isDOMExceptionConstructor(ctor) {
2825 if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
2826 return false;
2827 }
2828 if (ctor.name !== 'DOMException') {
2829 return false;
2830 }
2831 try {
2832 new ctor();
2833 return true;
2834 }
2835 catch (_a) {
2836 return false;
2837 }
2838}
2839/**
2840 * Support:
2841 * - Web browsers
2842 * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)
2843 */
2844function getFromGlobal() {
2845 const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException;
2846 return isDOMExceptionConstructor(ctor) ? ctor : undefined;
2847}
2848/**
2849 * Support:
2850 * - All platforms
2851 */
2852function createPolyfill() {
2853 // eslint-disable-next-line @typescript-eslint/no-shadow
2854 const ctor = function DOMException(message, name) {
2855 this.message = message || '';
2856 this.name = name || 'Error';
2857 if (Error.captureStackTrace) {
2858 Error.captureStackTrace(this, this.constructor);
2859 }
2860 };
2861 setFunctionName(ctor, 'DOMException');
2862 ctor.prototype = Object.create(Error.prototype);
2863 Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
2864 return ctor;
2865}
2866// eslint-disable-next-line @typescript-eslint/no-redeclare
2867const DOMException = getFromGlobal() || createPolyfill();
2868
2869function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
2870 const reader = AcquireReadableStreamDefaultReader(source);
2871 const writer = AcquireWritableStreamDefaultWriter(dest);
2872 source._disturbed = true;
2873 let shuttingDown = false;
2874 // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
2875 let currentWrite = promiseResolvedWith(undefined);
2876 return newPromise((resolve, reject) => {
2877 let abortAlgorithm;
2878 if (signal !== undefined) {
2879 abortAlgorithm = () => {
2880 const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');
2881 const actions = [];
2882 if (!preventAbort) {
2883 actions.push(() => {
2884 if (dest._state === 'writable') {
2885 return WritableStreamAbort(dest, error);
2886 }
2887 return promiseResolvedWith(undefined);
2888 });
2889 }
2890 if (!preventCancel) {
2891 actions.push(() => {
2892 if (source._state === 'readable') {
2893 return ReadableStreamCancel(source, error);
2894 }
2895 return promiseResolvedWith(undefined);
2896 });
2897 }
2898 shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
2899 };
2900 if (signal.aborted) {
2901 abortAlgorithm();
2902 return;
2903 }
2904 signal.addEventListener('abort', abortAlgorithm);
2905 }
2906 // Using reader and writer, read all chunks from this and write them to dest
2907 // - Backpressure must be enforced
2908 // - Shutdown must stop all activity
2909 function pipeLoop() {
2910 return newPromise((resolveLoop, rejectLoop) => {
2911 function next(done) {
2912 if (done) {
2913 resolveLoop();
2914 }
2915 else {
2916 // Use `PerformPromiseThen` instead of `uponPromise` to avoid
2917 // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
2918 PerformPromiseThen(pipeStep(), next, rejectLoop);
2919 }
2920 }
2921 next(false);
2922 });
2923 }
2924 function pipeStep() {
2925 if (shuttingDown) {
2926 return promiseResolvedWith(true);
2927 }
2928 return PerformPromiseThen(writer._readyPromise, () => {
2929 return newPromise((resolveRead, rejectRead) => {
2930 ReadableStreamDefaultReaderRead(reader, {
2931 _chunkSteps: chunk => {
2932 currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);
2933 resolveRead(false);
2934 },
2935 _closeSteps: () => resolveRead(true),
2936 _errorSteps: rejectRead
2937 });
2938 });
2939 });
2940 }
2941 // Errors must be propagated forward
2942 isOrBecomesErrored(source, reader._closedPromise, storedError => {
2943 if (!preventAbort) {
2944 shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
2945 }
2946 else {
2947 shutdown(true, storedError);
2948 }
2949 return null;
2950 });
2951 // Errors must be propagated backward
2952 isOrBecomesErrored(dest, writer._closedPromise, storedError => {
2953 if (!preventCancel) {
2954 shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
2955 }
2956 else {
2957 shutdown(true, storedError);
2958 }
2959 return null;
2960 });
2961 // Closing must be propagated forward
2962 isOrBecomesClosed(source, reader._closedPromise, () => {
2963 if (!preventClose) {
2964 shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
2965 }
2966 else {
2967 shutdown();
2968 }
2969 return null;
2970 });
2971 // Closing must be propagated backward
2972 if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
2973 const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
2974 if (!preventCancel) {
2975 shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
2976 }
2977 else {
2978 shutdown(true, destClosed);
2979 }
2980 }
2981 setPromiseIsHandledToTrue(pipeLoop());
2982 function waitForWritesToFinish() {
2983 // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
2984 // for that too.
2985 const oldCurrentWrite = currentWrite;
2986 return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
2987 }
2988 function isOrBecomesErrored(stream, promise, action) {
2989 if (stream._state === 'errored') {
2990 action(stream._storedError);
2991 }
2992 else {
2993 uponRejection(promise, action);
2994 }
2995 }
2996 function isOrBecomesClosed(stream, promise, action) {
2997 if (stream._state === 'closed') {
2998 action();
2999 }
3000 else {
3001 uponFulfillment(promise, action);
3002 }
3003 }
3004 function shutdownWithAction(action, originalIsError, originalError) {
3005 if (shuttingDown) {
3006 return;
3007 }
3008 shuttingDown = true;
3009 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
3010 uponFulfillment(waitForWritesToFinish(), doTheRest);
3011 }
3012 else {
3013 doTheRest();
3014 }
3015 function doTheRest() {
3016 uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
3017 return null;
3018 }
3019 }
3020 function shutdown(isError, error) {
3021 if (shuttingDown) {
3022 return;
3023 }
3024 shuttingDown = true;
3025 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
3026 uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
3027 }
3028 else {
3029 finalize(isError, error);
3030 }
3031 }
3032 function finalize(isError, error) {
3033 WritableStreamDefaultWriterRelease(writer);
3034 ReadableStreamReaderGenericRelease(reader);
3035 if (signal !== undefined) {
3036 signal.removeEventListener('abort', abortAlgorithm);
3037 }
3038 if (isError) {
3039 reject(error);
3040 }
3041 else {
3042 resolve(undefined);
3043 }
3044 return null;
3045 }
3046 });
3047}
3048
3049/**
3050 * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
3051 *
3052 * @public
3053 */
3054class ReadableStreamDefaultController {
3055 constructor() {
3056 throw new TypeError('Illegal constructor');
3057 }
3058 /**
3059 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
3060 * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
3061 */
3062 get desiredSize() {
3063 if (!IsReadableStreamDefaultController(this)) {
3064 throw defaultControllerBrandCheckException$1('desiredSize');
3065 }
3066 return ReadableStreamDefaultControllerGetDesiredSize(this);
3067 }
3068 /**
3069 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
3070 * the stream, but once those are read, the stream will become closed.
3071 */
3072 close() {
3073 if (!IsReadableStreamDefaultController(this)) {
3074 throw defaultControllerBrandCheckException$1('close');
3075 }
3076 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
3077 throw new TypeError('The stream is not in a state that permits close');
3078 }
3079 ReadableStreamDefaultControllerClose(this);
3080 }
3081 enqueue(chunk = undefined) {
3082 if (!IsReadableStreamDefaultController(this)) {
3083 throw defaultControllerBrandCheckException$1('enqueue');
3084 }
3085 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
3086 throw new TypeError('The stream is not in a state that permits enqueue');
3087 }
3088 return ReadableStreamDefaultControllerEnqueue(this, chunk);
3089 }
3090 /**
3091 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
3092 */
3093 error(e = undefined) {
3094 if (!IsReadableStreamDefaultController(this)) {
3095 throw defaultControllerBrandCheckException$1('error');
3096 }
3097 ReadableStreamDefaultControllerError(this, e);
3098 }
3099 /** @internal */
3100 [CancelSteps](reason) {
3101 ResetQueue(this);
3102 const result = this._cancelAlgorithm(reason);
3103 ReadableStreamDefaultControllerClearAlgorithms(this);
3104 return result;
3105 }
3106 /** @internal */
3107 [PullSteps](readRequest) {
3108 const stream = this._controlledReadableStream;
3109 if (this._queue.length > 0) {
3110 const chunk = DequeueValue(this);
3111 if (this._closeRequested && this._queue.length === 0) {
3112 ReadableStreamDefaultControllerClearAlgorithms(this);
3113 ReadableStreamClose(stream);
3114 }
3115 else {
3116 ReadableStreamDefaultControllerCallPullIfNeeded(this);
3117 }
3118 readRequest._chunkSteps(chunk);
3119 }
3120 else {
3121 ReadableStreamAddReadRequest(stream, readRequest);
3122 ReadableStreamDefaultControllerCallPullIfNeeded(this);
3123 }
3124 }
3125 /** @internal */
3126 [ReleaseSteps]() {
3127 // Do nothing.
3128 }
3129}
3130Object.defineProperties(ReadableStreamDefaultController.prototype, {
3131 close: { enumerable: true },
3132 enqueue: { enumerable: true },
3133 error: { enumerable: true },
3134 desiredSize: { enumerable: true }
3135});
3136setFunctionName(ReadableStreamDefaultController.prototype.close, 'close');
3137setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');
3138setFunctionName(ReadableStreamDefaultController.prototype.error, 'error');
3139if (typeof SymbolPolyfill.toStringTag === 'symbol') {
3140 Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
3141 value: 'ReadableStreamDefaultController',
3142 configurable: true
3143 });
3144}
3145// Abstract operations for the ReadableStreamDefaultController.
3146function IsReadableStreamDefaultController(x) {
3147 if (!typeIsObject(x)) {
3148 return false;
3149 }
3150 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
3151 return false;
3152 }
3153 return x instanceof ReadableStreamDefaultController;
3154}
3155function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
3156 const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
3157 if (!shouldPull) {
3158 return;
3159 }
3160 if (controller._pulling) {
3161 controller._pullAgain = true;
3162 return;
3163 }
3164 controller._pulling = true;
3165 const pullPromise = controller._pullAlgorithm();
3166 uponPromise(pullPromise, () => {
3167 controller._pulling = false;
3168 if (controller._pullAgain) {
3169 controller._pullAgain = false;
3170 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
3171 }
3172 return null;
3173 }, e => {
3174 ReadableStreamDefaultControllerError(controller, e);
3175 return null;
3176 });
3177}
3178function ReadableStreamDefaultControllerShouldCallPull(controller) {
3179 const stream = controller._controlledReadableStream;
3180 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
3181 return false;
3182 }
3183 if (!controller._started) {
3184 return false;
3185 }
3186 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
3187 return true;
3188 }
3189 const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
3190 if (desiredSize > 0) {
3191 return true;
3192 }
3193 return false;
3194}
3195function ReadableStreamDefaultControllerClearAlgorithms(controller) {
3196 controller._pullAlgorithm = undefined;
3197 controller._cancelAlgorithm = undefined;
3198 controller._strategySizeAlgorithm = undefined;
3199}
3200// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.
3201function ReadableStreamDefaultControllerClose(controller) {
3202 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
3203 return;
3204 }
3205 const stream = controller._controlledReadableStream;
3206 controller._closeRequested = true;
3207 if (controller._queue.length === 0) {
3208 ReadableStreamDefaultControllerClearAlgorithms(controller);
3209 ReadableStreamClose(stream);
3210 }
3211}
3212function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
3213 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
3214 return;
3215 }
3216 const stream = controller._controlledReadableStream;
3217 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
3218 ReadableStreamFulfillReadRequest(stream, chunk, false);
3219 }
3220 else {
3221 let chunkSize;
3222 try {
3223 chunkSize = controller._strategySizeAlgorithm(chunk);
3224 }
3225 catch (chunkSizeE) {
3226 ReadableStreamDefaultControllerError(controller, chunkSizeE);
3227 throw chunkSizeE;
3228 }
3229 try {
3230 EnqueueValueWithSize(controller, chunk, chunkSize);
3231 }
3232 catch (enqueueE) {
3233 ReadableStreamDefaultControllerError(controller, enqueueE);
3234 throw enqueueE;
3235 }
3236 }
3237 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
3238}
3239function ReadableStreamDefaultControllerError(controller, e) {
3240 const stream = controller._controlledReadableStream;
3241 if (stream._state !== 'readable') {
3242 return;
3243 }
3244 ResetQueue(controller);
3245 ReadableStreamDefaultControllerClearAlgorithms(controller);
3246 ReadableStreamError(stream, e);
3247}
3248function ReadableStreamDefaultControllerGetDesiredSize(controller) {
3249 const state = controller._controlledReadableStream._state;
3250 if (state === 'errored') {
3251 return null;
3252 }
3253 if (state === 'closed') {
3254 return 0;
3255 }
3256 return controller._strategyHWM - controller._queueTotalSize;
3257}
3258// This is used in the implementation of TransformStream.
3259function ReadableStreamDefaultControllerHasBackpressure(controller) {
3260 if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
3261 return false;
3262 }
3263 return true;
3264}
3265function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
3266 const state = controller._controlledReadableStream._state;
3267 if (!controller._closeRequested && state === 'readable') {
3268 return true;
3269 }
3270 return false;
3271}
3272function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
3273 controller._controlledReadableStream = stream;
3274 controller._queue = undefined;
3275 controller._queueTotalSize = undefined;
3276 ResetQueue(controller);
3277 controller._started = false;
3278 controller._closeRequested = false;
3279 controller._pullAgain = false;
3280 controller._pulling = false;
3281 controller._strategySizeAlgorithm = sizeAlgorithm;
3282 controller._strategyHWM = highWaterMark;
3283 controller._pullAlgorithm = pullAlgorithm;
3284 controller._cancelAlgorithm = cancelAlgorithm;
3285 stream._readableStreamController = controller;
3286 const startResult = startAlgorithm();
3287 uponPromise(promiseResolvedWith(startResult), () => {
3288 controller._started = true;
3289 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
3290 return null;
3291 }, r => {
3292 ReadableStreamDefaultControllerError(controller, r);
3293 return null;
3294 });
3295}
3296function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
3297 const controller = Object.create(ReadableStreamDefaultController.prototype);
3298 let startAlgorithm;
3299 let pullAlgorithm;
3300 let cancelAlgorithm;
3301 if (underlyingSource.start !== undefined) {
3302 startAlgorithm = () => underlyingSource.start(controller);
3303 }
3304 else {
3305 startAlgorithm = () => undefined;
3306 }
3307 if (underlyingSource.pull !== undefined) {
3308 pullAlgorithm = () => underlyingSource.pull(controller);
3309 }
3310 else {
3311 pullAlgorithm = () => promiseResolvedWith(undefined);
3312 }
3313 if (underlyingSource.cancel !== undefined) {
3314 cancelAlgorithm = reason => underlyingSource.cancel(reason);
3315 }
3316 else {
3317 cancelAlgorithm = () => promiseResolvedWith(undefined);
3318 }
3319 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
3320}
3321// Helper functions for the ReadableStreamDefaultController.
3322function defaultControllerBrandCheckException$1(name) {
3323 return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
3324}
3325
3326function ReadableStreamTee(stream, cloneForBranch2) {
3327 if (IsReadableByteStreamController(stream._readableStreamController)) {
3328 return ReadableByteStreamTee(stream);
3329 }
3330 return ReadableStreamDefaultTee(stream);
3331}
3332function ReadableStreamDefaultTee(stream, cloneForBranch2) {
3333 const reader = AcquireReadableStreamDefaultReader(stream);
3334 let reading = false;
3335 let readAgain = false;
3336 let canceled1 = false;
3337 let canceled2 = false;
3338 let reason1;
3339 let reason2;
3340 let branch1;
3341 let branch2;
3342 let resolveCancelPromise;
3343 const cancelPromise = newPromise(resolve => {
3344 resolveCancelPromise = resolve;
3345 });
3346 function pullAlgorithm() {
3347 if (reading) {
3348 readAgain = true;
3349 return promiseResolvedWith(undefined);
3350 }
3351 reading = true;
3352 const readRequest = {
3353 _chunkSteps: chunk => {
3354 // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3355 // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3356 // successful synchronously-available reads get ahead of asynchronously-available errors.
3357 _queueMicrotask(() => {
3358 readAgain = false;
3359 const chunk1 = chunk;
3360 const chunk2 = chunk;
3361 // There is no way to access the cloning code right now in the reference implementation.
3362 // If we add one then we'll need an implementation for serializable objects.
3363 // if (!canceled2 && cloneForBranch2) {
3364 // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));
3365 // }
3366 if (!canceled1) {
3367 ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);
3368 }
3369 if (!canceled2) {
3370 ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);
3371 }
3372 reading = false;
3373 if (readAgain) {
3374 pullAlgorithm();
3375 }
3376 });
3377 },
3378 _closeSteps: () => {
3379 reading = false;
3380 if (!canceled1) {
3381 ReadableStreamDefaultControllerClose(branch1._readableStreamController);
3382 }
3383 if (!canceled2) {
3384 ReadableStreamDefaultControllerClose(branch2._readableStreamController);
3385 }
3386 if (!canceled1 || !canceled2) {
3387 resolveCancelPromise(undefined);
3388 }
3389 },
3390 _errorSteps: () => {
3391 reading = false;
3392 }
3393 };
3394 ReadableStreamDefaultReaderRead(reader, readRequest);
3395 return promiseResolvedWith(undefined);
3396 }
3397 function cancel1Algorithm(reason) {
3398 canceled1 = true;
3399 reason1 = reason;
3400 if (canceled2) {
3401 const compositeReason = CreateArrayFromList([reason1, reason2]);
3402 const cancelResult = ReadableStreamCancel(stream, compositeReason);
3403 resolveCancelPromise(cancelResult);
3404 }
3405 return cancelPromise;
3406 }
3407 function cancel2Algorithm(reason) {
3408 canceled2 = true;
3409 reason2 = reason;
3410 if (canceled1) {
3411 const compositeReason = CreateArrayFromList([reason1, reason2]);
3412 const cancelResult = ReadableStreamCancel(stream, compositeReason);
3413 resolveCancelPromise(cancelResult);
3414 }
3415 return cancelPromise;
3416 }
3417 function startAlgorithm() {
3418 // do nothing
3419 }
3420 branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
3421 branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
3422 uponRejection(reader._closedPromise, (r) => {
3423 ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
3424 ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
3425 if (!canceled1 || !canceled2) {
3426 resolveCancelPromise(undefined);
3427 }
3428 return null;
3429 });
3430 return [branch1, branch2];
3431}
3432function ReadableByteStreamTee(stream) {
3433 let reader = AcquireReadableStreamDefaultReader(stream);
3434 let reading = false;
3435 let readAgainForBranch1 = false;
3436 let readAgainForBranch2 = false;
3437 let canceled1 = false;
3438 let canceled2 = false;
3439 let reason1;
3440 let reason2;
3441 let branch1;
3442 let branch2;
3443 let resolveCancelPromise;
3444 const cancelPromise = newPromise(resolve => {
3445 resolveCancelPromise = resolve;
3446 });
3447 function forwardReaderError(thisReader) {
3448 uponRejection(thisReader._closedPromise, r => {
3449 if (thisReader !== reader) {
3450 return null;
3451 }
3452 ReadableByteStreamControllerError(branch1._readableStreamController, r);
3453 ReadableByteStreamControllerError(branch2._readableStreamController, r);
3454 if (!canceled1 || !canceled2) {
3455 resolveCancelPromise(undefined);
3456 }
3457 return null;
3458 });
3459 }
3460 function pullWithDefaultReader() {
3461 if (IsReadableStreamBYOBReader(reader)) {
3462 ReadableStreamReaderGenericRelease(reader);
3463 reader = AcquireReadableStreamDefaultReader(stream);
3464 forwardReaderError(reader);
3465 }
3466 const readRequest = {
3467 _chunkSteps: chunk => {
3468 // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3469 // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3470 // successful synchronously-available reads get ahead of asynchronously-available errors.
3471 _queueMicrotask(() => {
3472 readAgainForBranch1 = false;
3473 readAgainForBranch2 = false;
3474 const chunk1 = chunk;
3475 let chunk2 = chunk;
3476 if (!canceled1 && !canceled2) {
3477 try {
3478 chunk2 = CloneAsUint8Array(chunk);
3479 }
3480 catch (cloneE) {
3481 ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);
3482 ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);
3483 resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
3484 return;
3485 }
3486 }
3487 if (!canceled1) {
3488 ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);
3489 }
3490 if (!canceled2) {
3491 ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);
3492 }
3493 reading = false;
3494 if (readAgainForBranch1) {
3495 pull1Algorithm();
3496 }
3497 else if (readAgainForBranch2) {
3498 pull2Algorithm();
3499 }
3500 });
3501 },
3502 _closeSteps: () => {
3503 reading = false;
3504 if (!canceled1) {
3505 ReadableByteStreamControllerClose(branch1._readableStreamController);
3506 }
3507 if (!canceled2) {
3508 ReadableByteStreamControllerClose(branch2._readableStreamController);
3509 }
3510 if (branch1._readableStreamController._pendingPullIntos.length > 0) {
3511 ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);
3512 }
3513 if (branch2._readableStreamController._pendingPullIntos.length > 0) {
3514 ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);
3515 }
3516 if (!canceled1 || !canceled2) {
3517 resolveCancelPromise(undefined);
3518 }
3519 },
3520 _errorSteps: () => {
3521 reading = false;
3522 }
3523 };
3524 ReadableStreamDefaultReaderRead(reader, readRequest);
3525 }
3526 function pullWithBYOBReader(view, forBranch2) {
3527 if (IsReadableStreamDefaultReader(reader)) {
3528 ReadableStreamReaderGenericRelease(reader);
3529 reader = AcquireReadableStreamBYOBReader(stream);
3530 forwardReaderError(reader);
3531 }
3532 const byobBranch = forBranch2 ? branch2 : branch1;
3533 const otherBranch = forBranch2 ? branch1 : branch2;
3534 const readIntoRequest = {
3535 _chunkSteps: chunk => {
3536 // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3537 // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3538 // successful synchronously-available reads get ahead of asynchronously-available errors.
3539 _queueMicrotask(() => {
3540 readAgainForBranch1 = false;
3541 readAgainForBranch2 = false;
3542 const byobCanceled = forBranch2 ? canceled2 : canceled1;
3543 const otherCanceled = forBranch2 ? canceled1 : canceled2;
3544 if (!otherCanceled) {
3545 let clonedChunk;
3546 try {
3547 clonedChunk = CloneAsUint8Array(chunk);
3548 }
3549 catch (cloneE) {
3550 ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);
3551 ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);
3552 resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
3553 return;
3554 }
3555 if (!byobCanceled) {
3556 ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
3557 }
3558 ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);
3559 }
3560 else if (!byobCanceled) {
3561 ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
3562 }
3563 reading = false;
3564 if (readAgainForBranch1) {
3565 pull1Algorithm();
3566 }
3567 else if (readAgainForBranch2) {
3568 pull2Algorithm();
3569 }
3570 });
3571 },
3572 _closeSteps: chunk => {
3573 reading = false;
3574 const byobCanceled = forBranch2 ? canceled2 : canceled1;
3575 const otherCanceled = forBranch2 ? canceled1 : canceled2;
3576 if (!byobCanceled) {
3577 ReadableByteStreamControllerClose(byobBranch._readableStreamController);
3578 }
3579 if (!otherCanceled) {
3580 ReadableByteStreamControllerClose(otherBranch._readableStreamController);
3581 }
3582 if (chunk !== undefined) {
3583 if (!byobCanceled) {
3584 ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
3585 }
3586 if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {
3587 ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);
3588 }
3589 }
3590 if (!byobCanceled || !otherCanceled) {
3591 resolveCancelPromise(undefined);
3592 }
3593 },
3594 _errorSteps: () => {
3595 reading = false;
3596 }
3597 };
3598 ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);
3599 }
3600 function pull1Algorithm() {
3601 if (reading) {
3602 readAgainForBranch1 = true;
3603 return promiseResolvedWith(undefined);
3604 }
3605 reading = true;
3606 const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);
3607 if (byobRequest === null) {
3608 pullWithDefaultReader();
3609 }
3610 else {
3611 pullWithBYOBReader(byobRequest._view, false);
3612 }
3613 return promiseResolvedWith(undefined);
3614 }
3615 function pull2Algorithm() {
3616 if (reading) {
3617 readAgainForBranch2 = true;
3618 return promiseResolvedWith(undefined);
3619 }
3620 reading = true;
3621 const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);
3622 if (byobRequest === null) {
3623 pullWithDefaultReader();
3624 }
3625 else {
3626 pullWithBYOBReader(byobRequest._view, true);
3627 }
3628 return promiseResolvedWith(undefined);
3629 }
3630 function cancel1Algorithm(reason) {
3631 canceled1 = true;
3632 reason1 = reason;
3633 if (canceled2) {
3634 const compositeReason = CreateArrayFromList([reason1, reason2]);
3635 const cancelResult = ReadableStreamCancel(stream, compositeReason);
3636 resolveCancelPromise(cancelResult);
3637 }
3638 return cancelPromise;
3639 }
3640 function cancel2Algorithm(reason) {
3641 canceled2 = true;
3642 reason2 = reason;
3643 if (canceled1) {
3644 const compositeReason = CreateArrayFromList([reason1, reason2]);
3645 const cancelResult = ReadableStreamCancel(stream, compositeReason);
3646 resolveCancelPromise(cancelResult);
3647 }
3648 return cancelPromise;
3649 }
3650 function startAlgorithm() {
3651 return;
3652 }
3653 branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);
3654 branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);
3655 forwardReaderError(reader);
3656 return [branch1, branch2];
3657}
3658
3659function isReadableStreamLike(stream) {
3660 return typeIsObject(stream) && typeof stream.getReader !== 'undefined';
3661}
3662
3663function ReadableStreamFrom(source) {
3664 if (isReadableStreamLike(source)) {
3665 return ReadableStreamFromDefaultReader(source.getReader());
3666 }
3667 return ReadableStreamFromIterable(source);
3668}
3669function ReadableStreamFromIterable(asyncIterable) {
3670 let stream;
3671 const iteratorRecord = GetIterator(asyncIterable, 'async');
3672 const startAlgorithm = noop;
3673 function pullAlgorithm() {
3674 let nextResult;
3675 try {
3676 nextResult = IteratorNext(iteratorRecord);
3677 }
3678 catch (e) {
3679 return promiseRejectedWith(e);
3680 }
3681 const nextPromise = promiseResolvedWith(nextResult);
3682 return transformPromiseWith(nextPromise, iterResult => {
3683 if (!typeIsObject(iterResult)) {
3684 throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');
3685 }
3686 const done = IteratorComplete(iterResult);
3687 if (done) {
3688 ReadableStreamDefaultControllerClose(stream._readableStreamController);
3689 }
3690 else {
3691 const value = IteratorValue(iterResult);
3692 ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3693 }
3694 });
3695 }
3696 function cancelAlgorithm(reason) {
3697 const iterator = iteratorRecord.iterator;
3698 let returnMethod;
3699 try {
3700 returnMethod = GetMethod(iterator, 'return');
3701 }
3702 catch (e) {
3703 return promiseRejectedWith(e);
3704 }
3705 if (returnMethod === undefined) {
3706 return promiseResolvedWith(undefined);
3707 }
3708 let returnResult;
3709 try {
3710 returnResult = reflectCall(returnMethod, iterator, [reason]);
3711 }
3712 catch (e) {
3713 return promiseRejectedWith(e);
3714 }
3715 const returnPromise = promiseResolvedWith(returnResult);
3716 return transformPromiseWith(returnPromise, iterResult => {
3717 if (!typeIsObject(iterResult)) {
3718 throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');
3719 }
3720 return undefined;
3721 });
3722 }
3723 stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3724 return stream;
3725}
3726function ReadableStreamFromDefaultReader(reader) {
3727 let stream;
3728 const startAlgorithm = noop;
3729 function pullAlgorithm() {
3730 let readPromise;
3731 try {
3732 readPromise = reader.read();
3733 }
3734 catch (e) {
3735 return promiseRejectedWith(e);
3736 }
3737 return transformPromiseWith(readPromise, readResult => {
3738 if (!typeIsObject(readResult)) {
3739 throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');
3740 }
3741 if (readResult.done) {
3742 ReadableStreamDefaultControllerClose(stream._readableStreamController);
3743 }
3744 else {
3745 const value = readResult.value;
3746 ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3747 }
3748 });
3749 }
3750 function cancelAlgorithm(reason) {
3751 try {
3752 return promiseResolvedWith(reader.cancel(reason));
3753 }
3754 catch (e) {
3755 return promiseRejectedWith(e);
3756 }
3757 }
3758 stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3759 return stream;
3760}
3761
3762function convertUnderlyingDefaultOrByteSource(source, context) {
3763 assertDictionary(source, context);
3764 const original = source;
3765 const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
3766 const cancel = original === null || original === void 0 ? void 0 : original.cancel;
3767 const pull = original === null || original === void 0 ? void 0 : original.pull;
3768 const start = original === null || original === void 0 ? void 0 : original.start;
3769 const type = original === null || original === void 0 ? void 0 : original.type;
3770 return {
3771 autoAllocateChunkSize: autoAllocateChunkSize === undefined ?
3772 undefined :
3773 convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
3774 cancel: cancel === undefined ?
3775 undefined :
3776 convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
3777 pull: pull === undefined ?
3778 undefined :
3779 convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
3780 start: start === undefined ?
3781 undefined :
3782 convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
3783 type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)
3784 };
3785}
3786function convertUnderlyingSourceCancelCallback(fn, original, context) {
3787 assertFunction(fn, context);
3788 return (reason) => promiseCall(fn, original, [reason]);
3789}
3790function convertUnderlyingSourcePullCallback(fn, original, context) {
3791 assertFunction(fn, context);
3792 return (controller) => promiseCall(fn, original, [controller]);
3793}
3794function convertUnderlyingSourceStartCallback(fn, original, context) {
3795 assertFunction(fn, context);
3796 return (controller) => reflectCall(fn, original, [controller]);
3797}
3798function convertReadableStreamType(type, context) {
3799 type = `${type}`;
3800 if (type !== 'bytes') {
3801 throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
3802 }
3803 return type;
3804}
3805
3806function convertIteratorOptions(options, context) {
3807 assertDictionary(options, context);
3808 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
3809 return { preventCancel: Boolean(preventCancel) };
3810}
3811
3812function convertPipeOptions(options, context) {
3813 assertDictionary(options, context);
3814 const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
3815 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
3816 const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
3817 const signal = options === null || options === void 0 ? void 0 : options.signal;
3818 if (signal !== undefined) {
3819 assertAbortSignal(signal, `${context} has member 'signal' that`);
3820 }
3821 return {
3822 preventAbort: Boolean(preventAbort),
3823 preventCancel: Boolean(preventCancel),
3824 preventClose: Boolean(preventClose),
3825 signal
3826 };
3827}
3828function assertAbortSignal(signal, context) {
3829 if (!isAbortSignal(signal)) {
3830 throw new TypeError(`${context} is not an AbortSignal.`);
3831 }
3832}
3833
3834function convertReadableWritablePair(pair, context) {
3835 assertDictionary(pair, context);
3836 const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
3837 assertRequiredField(readable, 'readable', 'ReadableWritablePair');
3838 assertReadableStream(readable, `${context} has member 'readable' that`);
3839 const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
3840 assertRequiredField(writable, 'writable', 'ReadableWritablePair');
3841 assertWritableStream(writable, `${context} has member 'writable' that`);
3842 return { readable, writable };
3843}
3844
3845/**
3846 * A readable stream represents a source of data, from which you can read.
3847 *
3848 * @public
3849 */
3850class ReadableStream {
3851 constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
3852 if (rawUnderlyingSource === undefined) {
3853 rawUnderlyingSource = null;
3854 }
3855 else {
3856 assertObject(rawUnderlyingSource, 'First parameter');
3857 }
3858 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
3859 const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');
3860 InitializeReadableStream(this);
3861 if (underlyingSource.type === 'bytes') {
3862 if (strategy.size !== undefined) {
3863 throw new RangeError('The strategy for a byte stream cannot have a size function');
3864 }
3865 const highWaterMark = ExtractHighWaterMark(strategy, 0);
3866 SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
3867 }
3868 else {
3869 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
3870 const highWaterMark = ExtractHighWaterMark(strategy, 1);
3871 SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
3872 }
3873 }
3874 /**
3875 * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
3876 */
3877 get locked() {
3878 if (!IsReadableStream(this)) {
3879 throw streamBrandCheckException$1('locked');
3880 }
3881 return IsReadableStreamLocked(this);
3882 }
3883 /**
3884 * Cancels the stream, signaling a loss of interest in the stream by a consumer.
3885 *
3886 * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
3887 * method, which might or might not use it.
3888 */
3889 cancel(reason = undefined) {
3890 if (!IsReadableStream(this)) {
3891 return promiseRejectedWith(streamBrandCheckException$1('cancel'));
3892 }
3893 if (IsReadableStreamLocked(this)) {
3894 return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
3895 }
3896 return ReadableStreamCancel(this, reason);
3897 }
3898 getReader(rawOptions = undefined) {
3899 if (!IsReadableStream(this)) {
3900 throw streamBrandCheckException$1('getReader');
3901 }
3902 const options = convertReaderOptions(rawOptions, 'First parameter');
3903 if (options.mode === undefined) {
3904 return AcquireReadableStreamDefaultReader(this);
3905 }
3906 return AcquireReadableStreamBYOBReader(this);
3907 }
3908 pipeThrough(rawTransform, rawOptions = {}) {
3909 if (!IsReadableStream(this)) {
3910 throw streamBrandCheckException$1('pipeThrough');
3911 }
3912 assertRequiredArgument(rawTransform, 1, 'pipeThrough');
3913 const transform = convertReadableWritablePair(rawTransform, 'First parameter');
3914 const options = convertPipeOptions(rawOptions, 'Second parameter');
3915 if (IsReadableStreamLocked(this)) {
3916 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
3917 }
3918 if (IsWritableStreamLocked(transform.writable)) {
3919 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
3920 }
3921 const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
3922 setPromiseIsHandledToTrue(promise);
3923 return transform.readable;
3924 }
3925 pipeTo(destination, rawOptions = {}) {
3926 if (!IsReadableStream(this)) {
3927 return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));
3928 }
3929 if (destination === undefined) {
3930 return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
3931 }
3932 if (!IsWritableStream(destination)) {
3933 return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
3934 }
3935 let options;
3936 try {
3937 options = convertPipeOptions(rawOptions, 'Second parameter');
3938 }
3939 catch (e) {
3940 return promiseRejectedWith(e);
3941 }
3942 if (IsReadableStreamLocked(this)) {
3943 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
3944 }
3945 if (IsWritableStreamLocked(destination)) {
3946 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
3947 }
3948 return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
3949 }
3950 /**
3951 * Tees this readable stream, returning a two-element array containing the two resulting branches as
3952 * new {@link ReadableStream} instances.
3953 *
3954 * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
3955 * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
3956 * propagated to the stream's underlying source.
3957 *
3958 * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
3959 * this could allow interference between the two branches.
3960 */
3961 tee() {
3962 if (!IsReadableStream(this)) {
3963 throw streamBrandCheckException$1('tee');
3964 }
3965 const branches = ReadableStreamTee(this);
3966 return CreateArrayFromList(branches);
3967 }
3968 values(rawOptions = undefined) {
3969 if (!IsReadableStream(this)) {
3970 throw streamBrandCheckException$1('values');
3971 }
3972 const options = convertIteratorOptions(rawOptions, 'First parameter');
3973 return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
3974 }
3975 /**
3976 * Creates a new ReadableStream wrapping the provided iterable or async iterable.
3977 *
3978 * This can be used to adapt various kinds of objects into a readable stream,
3979 * such as an array, an async generator, or a Node.js readable stream.
3980 */
3981 static from(asyncIterable) {
3982 return ReadableStreamFrom(asyncIterable);
3983 }
3984}
3985Object.defineProperties(ReadableStream, {
3986 from: { enumerable: true }
3987});
3988Object.defineProperties(ReadableStream.prototype, {
3989 cancel: { enumerable: true },
3990 getReader: { enumerable: true },
3991 pipeThrough: { enumerable: true },
3992 pipeTo: { enumerable: true },
3993 tee: { enumerable: true },
3994 values: { enumerable: true },
3995 locked: { enumerable: true }
3996});
3997setFunctionName(ReadableStream.from, 'from');
3998setFunctionName(ReadableStream.prototype.cancel, 'cancel');
3999setFunctionName(ReadableStream.prototype.getReader, 'getReader');
4000setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');
4001setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');
4002setFunctionName(ReadableStream.prototype.tee, 'tee');
4003setFunctionName(ReadableStream.prototype.values, 'values');
4004if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4005 Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {
4006 value: 'ReadableStream',
4007 configurable: true
4008 });
4009}
4010if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
4011 Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {
4012 value: ReadableStream.prototype.values,
4013 writable: true,
4014 configurable: true
4015 });
4016}
4017// Abstract operations for the ReadableStream.
4018// Throws if and only if startAlgorithm throws.
4019function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
4020 const stream = Object.create(ReadableStream.prototype);
4021 InitializeReadableStream(stream);
4022 const controller = Object.create(ReadableStreamDefaultController.prototype);
4023 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
4024 return stream;
4025}
4026// Throws if and only if startAlgorithm throws.
4027function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
4028 const stream = Object.create(ReadableStream.prototype);
4029 InitializeReadableStream(stream);
4030 const controller = Object.create(ReadableByteStreamController.prototype);
4031 SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);
4032 return stream;
4033}
4034function InitializeReadableStream(stream) {
4035 stream._state = 'readable';
4036 stream._reader = undefined;
4037 stream._storedError = undefined;
4038 stream._disturbed = false;
4039}
4040function IsReadableStream(x) {
4041 if (!typeIsObject(x)) {
4042 return false;
4043 }
4044 if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
4045 return false;
4046 }
4047 return x instanceof ReadableStream;
4048}
4049function IsReadableStreamLocked(stream) {
4050 if (stream._reader === undefined) {
4051 return false;
4052 }
4053 return true;
4054}
4055// ReadableStream API exposed for controllers.
4056function ReadableStreamCancel(stream, reason) {
4057 stream._disturbed = true;
4058 if (stream._state === 'closed') {
4059 return promiseResolvedWith(undefined);
4060 }
4061 if (stream._state === 'errored') {
4062 return promiseRejectedWith(stream._storedError);
4063 }
4064 ReadableStreamClose(stream);
4065 const reader = stream._reader;
4066 if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {
4067 const readIntoRequests = reader._readIntoRequests;
4068 reader._readIntoRequests = new SimpleQueue();
4069 readIntoRequests.forEach(readIntoRequest => {
4070 readIntoRequest._closeSteps(undefined);
4071 });
4072 }
4073 const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
4074 return transformPromiseWith(sourceCancelPromise, noop);
4075}
4076function ReadableStreamClose(stream) {
4077 stream._state = 'closed';
4078 const reader = stream._reader;
4079 if (reader === undefined) {
4080 return;
4081 }
4082 defaultReaderClosedPromiseResolve(reader);
4083 if (IsReadableStreamDefaultReader(reader)) {
4084 const readRequests = reader._readRequests;
4085 reader._readRequests = new SimpleQueue();
4086 readRequests.forEach(readRequest => {
4087 readRequest._closeSteps();
4088 });
4089 }
4090}
4091function ReadableStreamError(stream, e) {
4092 stream._state = 'errored';
4093 stream._storedError = e;
4094 const reader = stream._reader;
4095 if (reader === undefined) {
4096 return;
4097 }
4098 defaultReaderClosedPromiseReject(reader, e);
4099 if (IsReadableStreamDefaultReader(reader)) {
4100 ReadableStreamDefaultReaderErrorReadRequests(reader, e);
4101 }
4102 else {
4103 ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
4104 }
4105}
4106// Helper functions for the ReadableStream.
4107function streamBrandCheckException$1(name) {
4108 return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
4109}
4110
4111function convertQueuingStrategyInit(init, context) {
4112 assertDictionary(init, context);
4113 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
4114 assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');
4115 return {
4116 highWaterMark: convertUnrestrictedDouble(highWaterMark)
4117 };
4118}
4119
4120// The size function must not have a prototype property nor be a constructor
4121const byteLengthSizeFunction = (chunk) => {
4122 return chunk.byteLength;
4123};
4124setFunctionName(byteLengthSizeFunction, 'size');
4125/**
4126 * A queuing strategy that counts the number of bytes in each chunk.
4127 *
4128 * @public
4129 */
4130class ByteLengthQueuingStrategy {
4131 constructor(options) {
4132 assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');
4133 options = convertQueuingStrategyInit(options, 'First parameter');
4134 this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
4135 }
4136 /**
4137 * Returns the high water mark provided to the constructor.
4138 */
4139 get highWaterMark() {
4140 if (!IsByteLengthQueuingStrategy(this)) {
4141 throw byteLengthBrandCheckException('highWaterMark');
4142 }
4143 return this._byteLengthQueuingStrategyHighWaterMark;
4144 }
4145 /**
4146 * Measures the size of `chunk` by returning the value of its `byteLength` property.
4147 */
4148 get size() {
4149 if (!IsByteLengthQueuingStrategy(this)) {
4150 throw byteLengthBrandCheckException('size');
4151 }
4152 return byteLengthSizeFunction;
4153 }
4154}
4155Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
4156 highWaterMark: { enumerable: true },
4157 size: { enumerable: true }
4158});
4159if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4160 Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
4161 value: 'ByteLengthQueuingStrategy',
4162 configurable: true
4163 });
4164}
4165// Helper functions for the ByteLengthQueuingStrategy.
4166function byteLengthBrandCheckException(name) {
4167 return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
4168}
4169function IsByteLengthQueuingStrategy(x) {
4170 if (!typeIsObject(x)) {
4171 return false;
4172 }
4173 if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {
4174 return false;
4175 }
4176 return x instanceof ByteLengthQueuingStrategy;
4177}
4178
4179// The size function must not have a prototype property nor be a constructor
4180const countSizeFunction = () => {
4181 return 1;
4182};
4183setFunctionName(countSizeFunction, 'size');
4184/**
4185 * A queuing strategy that counts the number of chunks.
4186 *
4187 * @public
4188 */
4189class CountQueuingStrategy {
4190 constructor(options) {
4191 assertRequiredArgument(options, 1, 'CountQueuingStrategy');
4192 options = convertQueuingStrategyInit(options, 'First parameter');
4193 this._countQueuingStrategyHighWaterMark = options.highWaterMark;
4194 }
4195 /**
4196 * Returns the high water mark provided to the constructor.
4197 */
4198 get highWaterMark() {
4199 if (!IsCountQueuingStrategy(this)) {
4200 throw countBrandCheckException('highWaterMark');
4201 }
4202 return this._countQueuingStrategyHighWaterMark;
4203 }
4204 /**
4205 * Measures the size of `chunk` by always returning 1.
4206 * This ensures that the total queue size is a count of the number of chunks in the queue.
4207 */
4208 get size() {
4209 if (!IsCountQueuingStrategy(this)) {
4210 throw countBrandCheckException('size');
4211 }
4212 return countSizeFunction;
4213 }
4214}
4215Object.defineProperties(CountQueuingStrategy.prototype, {
4216 highWaterMark: { enumerable: true },
4217 size: { enumerable: true }
4218});
4219if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4220 Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
4221 value: 'CountQueuingStrategy',
4222 configurable: true
4223 });
4224}
4225// Helper functions for the CountQueuingStrategy.
4226function countBrandCheckException(name) {
4227 return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
4228}
4229function IsCountQueuingStrategy(x) {
4230 if (!typeIsObject(x)) {
4231 return false;
4232 }
4233 if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {
4234 return false;
4235 }
4236 return x instanceof CountQueuingStrategy;
4237}
4238
4239function convertTransformer(original, context) {
4240 assertDictionary(original, context);
4241 const cancel = original === null || original === void 0 ? void 0 : original.cancel;
4242 const flush = original === null || original === void 0 ? void 0 : original.flush;
4243 const readableType = original === null || original === void 0 ? void 0 : original.readableType;
4244 const start = original === null || original === void 0 ? void 0 : original.start;
4245 const transform = original === null || original === void 0 ? void 0 : original.transform;
4246 const writableType = original === null || original === void 0 ? void 0 : original.writableType;
4247 return {
4248 cancel: cancel === undefined ?
4249 undefined :
4250 convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`),
4251 flush: flush === undefined ?
4252 undefined :
4253 convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
4254 readableType,
4255 start: start === undefined ?
4256 undefined :
4257 convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
4258 transform: transform === undefined ?
4259 undefined :
4260 convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
4261 writableType
4262 };
4263}
4264function convertTransformerFlushCallback(fn, original, context) {
4265 assertFunction(fn, context);
4266 return (controller) => promiseCall(fn, original, [controller]);
4267}
4268function convertTransformerStartCallback(fn, original, context) {
4269 assertFunction(fn, context);
4270 return (controller) => reflectCall(fn, original, [controller]);
4271}
4272function convertTransformerTransformCallback(fn, original, context) {
4273 assertFunction(fn, context);
4274 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
4275}
4276function convertTransformerCancelCallback(fn, original, context) {
4277 assertFunction(fn, context);
4278 return (reason) => promiseCall(fn, original, [reason]);
4279}
4280
4281// Class TransformStream
4282/**
4283 * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
4284 * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
4285 * In a manner specific to the transform stream in question, writes to the writable side result in new data being
4286 * made available for reading from the readable side.
4287 *
4288 * @public
4289 */
4290class TransformStream {
4291 constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
4292 if (rawTransformer === undefined) {
4293 rawTransformer = null;
4294 }
4295 const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');
4296 const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');
4297 const transformer = convertTransformer(rawTransformer, 'First parameter');
4298 if (transformer.readableType !== undefined) {
4299 throw new RangeError('Invalid readableType specified');
4300 }
4301 if (transformer.writableType !== undefined) {
4302 throw new RangeError('Invalid writableType specified');
4303 }
4304 const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
4305 const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
4306 const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
4307 const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
4308 let startPromise_resolve;
4309 const startPromise = newPromise(resolve => {
4310 startPromise_resolve = resolve;
4311 });
4312 InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
4313 SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
4314 if (transformer.start !== undefined) {
4315 startPromise_resolve(transformer.start(this._transformStreamController));
4316 }
4317 else {
4318 startPromise_resolve(undefined);
4319 }
4320 }
4321 /**
4322 * The readable side of the transform stream.
4323 */
4324 get readable() {
4325 if (!IsTransformStream(this)) {
4326 throw streamBrandCheckException('readable');
4327 }
4328 return this._readable;
4329 }
4330 /**
4331 * The writable side of the transform stream.
4332 */
4333 get writable() {
4334 if (!IsTransformStream(this)) {
4335 throw streamBrandCheckException('writable');
4336 }
4337 return this._writable;
4338 }
4339}
4340Object.defineProperties(TransformStream.prototype, {
4341 readable: { enumerable: true },
4342 writable: { enumerable: true }
4343});
4344if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4345 Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, {
4346 value: 'TransformStream',
4347 configurable: true
4348 });
4349}
4350function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
4351 function startAlgorithm() {
4352 return startPromise;
4353 }
4354 function writeAlgorithm(chunk) {
4355 return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
4356 }
4357 function abortAlgorithm(reason) {
4358 return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
4359 }
4360 function closeAlgorithm() {
4361 return TransformStreamDefaultSinkCloseAlgorithm(stream);
4362 }
4363 stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
4364 function pullAlgorithm() {
4365 return TransformStreamDefaultSourcePullAlgorithm(stream);
4366 }
4367 function cancelAlgorithm(reason) {
4368 return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);
4369 }
4370 stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
4371 // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
4372 stream._backpressure = undefined;
4373 stream._backpressureChangePromise = undefined;
4374 stream._backpressureChangePromise_resolve = undefined;
4375 TransformStreamSetBackpressure(stream, true);
4376 stream._transformStreamController = undefined;
4377}
4378function IsTransformStream(x) {
4379 if (!typeIsObject(x)) {
4380 return false;
4381 }
4382 if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
4383 return false;
4384 }
4385 return x instanceof TransformStream;
4386}
4387// This is a no-op if both sides are already errored.
4388function TransformStreamError(stream, e) {
4389 ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
4390 TransformStreamErrorWritableAndUnblockWrite(stream, e);
4391}
4392function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
4393 TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
4394 WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
4395 TransformStreamUnblockWrite(stream);
4396}
4397function TransformStreamUnblockWrite(stream) {
4398 if (stream._backpressure) {
4399 // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
4400 // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
4401 // _backpressure is set.
4402 TransformStreamSetBackpressure(stream, false);
4403 }
4404}
4405function TransformStreamSetBackpressure(stream, backpressure) {
4406 // Passes also when called during construction.
4407 if (stream._backpressureChangePromise !== undefined) {
4408 stream._backpressureChangePromise_resolve();
4409 }
4410 stream._backpressureChangePromise = newPromise(resolve => {
4411 stream._backpressureChangePromise_resolve = resolve;
4412 });
4413 stream._backpressure = backpressure;
4414}
4415// Class TransformStreamDefaultController
4416/**
4417 * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
4418 *
4419 * @public
4420 */
4421class TransformStreamDefaultController {
4422 constructor() {
4423 throw new TypeError('Illegal constructor');
4424 }
4425 /**
4426 * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
4427 */
4428 get desiredSize() {
4429 if (!IsTransformStreamDefaultController(this)) {
4430 throw defaultControllerBrandCheckException('desiredSize');
4431 }
4432 const readableController = this._controlledTransformStream._readable._readableStreamController;
4433 return ReadableStreamDefaultControllerGetDesiredSize(readableController);
4434 }
4435 enqueue(chunk = undefined) {
4436 if (!IsTransformStreamDefaultController(this)) {
4437 throw defaultControllerBrandCheckException('enqueue');
4438 }
4439 TransformStreamDefaultControllerEnqueue(this, chunk);
4440 }
4441 /**
4442 * Errors both the readable side and the writable side of the controlled transform stream, making all future
4443 * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
4444 */
4445 error(reason = undefined) {
4446 if (!IsTransformStreamDefaultController(this)) {
4447 throw defaultControllerBrandCheckException('error');
4448 }
4449 TransformStreamDefaultControllerError(this, reason);
4450 }
4451 /**
4452 * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
4453 * transformer only needs to consume a portion of the chunks written to the writable side.
4454 */
4455 terminate() {
4456 if (!IsTransformStreamDefaultController(this)) {
4457 throw defaultControllerBrandCheckException('terminate');
4458 }
4459 TransformStreamDefaultControllerTerminate(this);
4460 }
4461}
4462Object.defineProperties(TransformStreamDefaultController.prototype, {
4463 enqueue: { enumerable: true },
4464 error: { enumerable: true },
4465 terminate: { enumerable: true },
4466 desiredSize: { enumerable: true }
4467});
4468setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');
4469setFunctionName(TransformStreamDefaultController.prototype.error, 'error');
4470setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');
4471if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4472 Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
4473 value: 'TransformStreamDefaultController',
4474 configurable: true
4475 });
4476}
4477// Transform Stream Default Controller Abstract Operations
4478function IsTransformStreamDefaultController(x) {
4479 if (!typeIsObject(x)) {
4480 return false;
4481 }
4482 if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
4483 return false;
4484 }
4485 return x instanceof TransformStreamDefaultController;
4486}
4487function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
4488 controller._controlledTransformStream = stream;
4489 stream._transformStreamController = controller;
4490 controller._transformAlgorithm = transformAlgorithm;
4491 controller._flushAlgorithm = flushAlgorithm;
4492 controller._cancelAlgorithm = cancelAlgorithm;
4493 controller._finishPromise = undefined;
4494 controller._finishPromise_resolve = undefined;
4495 controller._finishPromise_reject = undefined;
4496}
4497function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
4498 const controller = Object.create(TransformStreamDefaultController.prototype);
4499 let transformAlgorithm;
4500 let flushAlgorithm;
4501 let cancelAlgorithm;
4502 if (transformer.transform !== undefined) {
4503 transformAlgorithm = chunk => transformer.transform(chunk, controller);
4504 }
4505 else {
4506 transformAlgorithm = chunk => {
4507 try {
4508 TransformStreamDefaultControllerEnqueue(controller, chunk);
4509 return promiseResolvedWith(undefined);
4510 }
4511 catch (transformResultE) {
4512 return promiseRejectedWith(transformResultE);
4513 }
4514 };
4515 }
4516 if (transformer.flush !== undefined) {
4517 flushAlgorithm = () => transformer.flush(controller);
4518 }
4519 else {
4520 flushAlgorithm = () => promiseResolvedWith(undefined);
4521 }
4522 if (transformer.cancel !== undefined) {
4523 cancelAlgorithm = reason => transformer.cancel(reason);
4524 }
4525 else {
4526 cancelAlgorithm = () => promiseResolvedWith(undefined);
4527 }
4528 SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);
4529}
4530function TransformStreamDefaultControllerClearAlgorithms(controller) {
4531 controller._transformAlgorithm = undefined;
4532 controller._flushAlgorithm = undefined;
4533 controller._cancelAlgorithm = undefined;
4534}
4535function TransformStreamDefaultControllerEnqueue(controller, chunk) {
4536 const stream = controller._controlledTransformStream;
4537 const readableController = stream._readable._readableStreamController;
4538 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
4539 throw new TypeError('Readable side is not in a state that permits enqueue');
4540 }
4541 // We throttle transform invocations based on the backpressure of the ReadableStream, but we still
4542 // accept TransformStreamDefaultControllerEnqueue() calls.
4543 try {
4544 ReadableStreamDefaultControllerEnqueue(readableController, chunk);
4545 }
4546 catch (e) {
4547 // This happens when readableStrategy.size() throws.
4548 TransformStreamErrorWritableAndUnblockWrite(stream, e);
4549 throw stream._readable._storedError;
4550 }
4551 const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
4552 if (backpressure !== stream._backpressure) {
4553 TransformStreamSetBackpressure(stream, true);
4554 }
4555}
4556function TransformStreamDefaultControllerError(controller, e) {
4557 TransformStreamError(controller._controlledTransformStream, e);
4558}
4559function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
4560 const transformPromise = controller._transformAlgorithm(chunk);
4561 return transformPromiseWith(transformPromise, undefined, r => {
4562 TransformStreamError(controller._controlledTransformStream, r);
4563 throw r;
4564 });
4565}
4566function TransformStreamDefaultControllerTerminate(controller) {
4567 const stream = controller._controlledTransformStream;
4568 const readableController = stream._readable._readableStreamController;
4569 ReadableStreamDefaultControllerClose(readableController);
4570 const error = new TypeError('TransformStream terminated');
4571 TransformStreamErrorWritableAndUnblockWrite(stream, error);
4572}
4573// TransformStreamDefaultSink Algorithms
4574function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
4575 const controller = stream._transformStreamController;
4576 if (stream._backpressure) {
4577 const backpressureChangePromise = stream._backpressureChangePromise;
4578 return transformPromiseWith(backpressureChangePromise, () => {
4579 const writable = stream._writable;
4580 const state = writable._state;
4581 if (state === 'erroring') {
4582 throw writable._storedError;
4583 }
4584 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
4585 });
4586 }
4587 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
4588}
4589function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
4590 const controller = stream._transformStreamController;
4591 if (controller._finishPromise !== undefined) {
4592 return controller._finishPromise;
4593 }
4594 // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4595 const readable = stream._readable;
4596 // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,
4597 // we don't run the _cancelAlgorithm again.
4598 controller._finishPromise = newPromise((resolve, reject) => {
4599 controller._finishPromise_resolve = resolve;
4600 controller._finishPromise_reject = reject;
4601 });
4602 const cancelPromise = controller._cancelAlgorithm(reason);
4603 TransformStreamDefaultControllerClearAlgorithms(controller);
4604 uponPromise(cancelPromise, () => {
4605 if (readable._state === 'errored') {
4606 defaultControllerFinishPromiseReject(controller, readable._storedError);
4607 }
4608 else {
4609 ReadableStreamDefaultControllerError(readable._readableStreamController, reason);
4610 defaultControllerFinishPromiseResolve(controller);
4611 }
4612 return null;
4613 }, r => {
4614 ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4615 defaultControllerFinishPromiseReject(controller, r);
4616 return null;
4617 });
4618 return controller._finishPromise;
4619}
4620function TransformStreamDefaultSinkCloseAlgorithm(stream) {
4621 const controller = stream._transformStreamController;
4622 if (controller._finishPromise !== undefined) {
4623 return controller._finishPromise;
4624 }
4625 // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4626 const readable = stream._readable;
4627 // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,
4628 // we don't also run the _cancelAlgorithm.
4629 controller._finishPromise = newPromise((resolve, reject) => {
4630 controller._finishPromise_resolve = resolve;
4631 controller._finishPromise_reject = reject;
4632 });
4633 const flushPromise = controller._flushAlgorithm();
4634 TransformStreamDefaultControllerClearAlgorithms(controller);
4635 uponPromise(flushPromise, () => {
4636 if (readable._state === 'errored') {
4637 defaultControllerFinishPromiseReject(controller, readable._storedError);
4638 }
4639 else {
4640 ReadableStreamDefaultControllerClose(readable._readableStreamController);
4641 defaultControllerFinishPromiseResolve(controller);
4642 }
4643 return null;
4644 }, r => {
4645 ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4646 defaultControllerFinishPromiseReject(controller, r);
4647 return null;
4648 });
4649 return controller._finishPromise;
4650}
4651// TransformStreamDefaultSource Algorithms
4652function TransformStreamDefaultSourcePullAlgorithm(stream) {
4653 // Invariant. Enforced by the promises returned by start() and pull().
4654 TransformStreamSetBackpressure(stream, false);
4655 // Prevent the next pull() call until there is backpressure.
4656 return stream._backpressureChangePromise;
4657}
4658function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) {
4659 const controller = stream._transformStreamController;
4660 if (controller._finishPromise !== undefined) {
4661 return controller._finishPromise;
4662 }
4663 // stream._writable cannot change after construction, so caching it across a call to user code is safe.
4664 const writable = stream._writable;
4665 // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or
4666 // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the
4667 // _flushAlgorithm.
4668 controller._finishPromise = newPromise((resolve, reject) => {
4669 controller._finishPromise_resolve = resolve;
4670 controller._finishPromise_reject = reject;
4671 });
4672 const cancelPromise = controller._cancelAlgorithm(reason);
4673 TransformStreamDefaultControllerClearAlgorithms(controller);
4674 uponPromise(cancelPromise, () => {
4675 if (writable._state === 'errored') {
4676 defaultControllerFinishPromiseReject(controller, writable._storedError);
4677 }
4678 else {
4679 WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);
4680 TransformStreamUnblockWrite(stream);
4681 defaultControllerFinishPromiseResolve(controller);
4682 }
4683 return null;
4684 }, r => {
4685 WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);
4686 TransformStreamUnblockWrite(stream);
4687 defaultControllerFinishPromiseReject(controller, r);
4688 return null;
4689 });
4690 return controller._finishPromise;
4691}
4692// Helper functions for the TransformStreamDefaultController.
4693function defaultControllerBrandCheckException(name) {
4694 return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
4695}
4696function defaultControllerFinishPromiseResolve(controller) {
4697 if (controller._finishPromise_resolve === undefined) {
4698 return;
4699 }
4700 controller._finishPromise_resolve();
4701 controller._finishPromise_resolve = undefined;
4702 controller._finishPromise_reject = undefined;
4703}
4704function defaultControllerFinishPromiseReject(controller, reason) {
4705 if (controller._finishPromise_reject === undefined) {
4706 return;
4707 }
4708 setPromiseIsHandledToTrue(controller._finishPromise);
4709 controller._finishPromise_reject(reason);
4710 controller._finishPromise_resolve = undefined;
4711 controller._finishPromise_reject = undefined;
4712}
4713// Helper functions for the TransformStream.
4714function streamBrandCheckException(name) {
4715 return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
4716}
4717
4718const exports = {
4719 ReadableStream,
4720 ReadableStreamDefaultController,
4721 ReadableByteStreamController,
4722 ReadableStreamBYOBRequest,
4723 ReadableStreamDefaultReader,
4724 ReadableStreamBYOBReader,
4725 WritableStream,
4726 WritableStreamDefaultController,
4727 WritableStreamDefaultWriter,
4728 ByteLengthQueuingStrategy,
4729 CountQueuingStrategy,
4730 TransformStream,
4731 TransformStreamDefaultController
4732};
4733// Add classes to global scope
4734if (typeof globals !== 'undefined') {
4735 for (const prop in exports) {
4736 if (Object.prototype.hasOwnProperty.call(exports, prop)) {
4737 Object.defineProperty(globals, prop, {
4738 value: exports[prop],
4739 writable: true,
4740 configurable: true
4741 });
4742 }
4743 }
4744}
4745
4746export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter };
4747//# sourceMappingURL=polyfill.es2018.mjs.map
Note: See TracBrowser for help on using the repository browser.