source: node_modules/web-streams-polyfill/dist/polyfill.es6.mjs

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

Initial commit

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