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