Best JavaScript code snippet using wpt
readable-stream.js
Source:readable-stream.js
...67 throw new RangeError('Invalid mode is specified');68 }69 pipeThrough({ writable, readable }, options) {70 const promise = this.pipeTo(writable, options);71 ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);72 return readable;73 }74 pipeTo(dest, { preventClose, preventAbort, preventCancel } = {}) {75 if (IsReadableStream(this) === false) {76 return Promise.reject(streamBrandCheckException('pipeTo'));77 }78 if (IsWritableStream(dest) === false) {79 return Promise.reject(80 new TypeError('ReadableStream.prototype.pipeTo\'s first argument must be a WritableStream'));81 }82 preventClose = Boolean(preventClose);83 preventAbort = Boolean(preventAbort);84 preventCancel = Boolean(preventCancel);85 if (IsReadableStreamLocked(this) === true) {86 return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));87 }88 if (IsWritableStreamLocked(dest) === true) {89 return Promise.reject(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));90 }91 const reader = AcquireReadableStreamDefaultReader(this);92 const writer = AcquireWritableStreamDefaultWriter(dest);93 let shuttingDown = false;94 // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.95 let currentWrite = Promise.resolve();96 return new Promise((resolve, reject) => {97 // Using reader and writer, read all chunks from this and write them to dest98 // - Backpressure must be enforced99 // - Shutdown must stop all activity100 function pipeLoop() {101 currentWrite = Promise.resolve();102 if (shuttingDown === true) {103 return Promise.resolve();104 }105 return writer._readyPromise.then(() => {106 return ReadableStreamDefaultReaderRead(reader).then(({ value, done }) => {107 if (done === true) {108 return;109 }110 currentWrite = WritableStreamDefaultWriterWrite(writer, value).catch(() => {});111 });112 })113 .then(pipeLoop);114 }115 // Errors must be propagated forward116 isOrBecomesErrored(this, reader._closedPromise, storedError => {117 if (preventAbort === false) {118 shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);119 } else {120 shutdown(true, storedError);121 }122 });123 // Errors must be propagated backward124 isOrBecomesErrored(dest, writer._closedPromise, storedError => {125 if (preventCancel === false) {126 shutdownWithAction(() => ReadableStreamCancel(this, storedError), true, storedError);127 } else {128 shutdown(true, storedError);129 }130 });131 // Closing must be propagated forward132 isOrBecomesClosed(this, reader._closedPromise, () => {133 if (preventClose === false) {134 shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));135 } else {136 shutdown();137 }138 });139 // Closing must be propagated backward140 if (WritableStreamCloseQueuedOrInFlight(dest) === true || dest._state === 'closed') {141 const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');142 if (preventCancel === false) {143 shutdownWithAction(() => ReadableStreamCancel(this, destClosed), true, destClosed);144 } else {145 shutdown(true, destClosed);146 }147 }148 pipeLoop().catch(err => {149 currentWrite = Promise.resolve();150 rethrowAssertionErrorRejection(err);151 });152 function waitForWritesToFinish() {153 // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait154 // for that too.155 const oldCurrentWrite = currentWrite;156 return currentWrite.then(() => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);157 }158 function isOrBecomesErrored(stream, promise, action) {159 if (stream._state === 'errored') {160 action(stream._storedError);161 } else {162 promise.catch(action).catch(rethrowAssertionErrorRejection);163 }164 }165 function isOrBecomesClosed(stream, promise, action) {166 if (stream._state === 'closed') {167 action();168 } else {169 promise.then(action).catch(rethrowAssertionErrorRejection);170 }171 }172 function shutdownWithAction(action, originalIsError, originalError) {173 if (shuttingDown === true) {174 return;175 }176 shuttingDown = true;177 if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) {178 waitForWritesToFinish().then(doTheRest);179 } else {180 doTheRest();181 }182 function doTheRest() {183 action().then(184 () => finalize(originalIsError, originalError),185 newError => finalize(true, newError)186 )187 .catch(rethrowAssertionErrorRejection);188 }189 }190 function shutdown(isError, error) {191 if (shuttingDown === true) {192 return;193 }194 shuttingDown = true;195 if (dest._state === 'writable' && WritableStreamCloseQueuedOrInFlight(dest) === false) {196 waitForWritesToFinish().then(() => finalize(isError, error)).catch(rethrowAssertionErrorRejection);197 } else {198 finalize(isError, error);199 }200 }201 function finalize(isError, error) {202 WritableStreamDefaultWriterRelease(writer);203 ReadableStreamReaderGenericRelease(reader);204 if (isError) {205 reject(error);206 } else {207 resolve(undefined);208 }209 }210 });211 }212 tee() {213 if (IsReadableStream(this) === false) {214 throw streamBrandCheckException('tee');215 }216 const branches = ReadableStreamTee(this, false);217 return createArrayFromList(branches);218 }219}220module.exports = {221 ReadableStream,222 IsReadableStreamDisturbed,223 ReadableStreamDefaultControllerClose,224 ReadableStreamDefaultControllerEnqueue,225 ReadableStreamDefaultControllerError,226 ReadableStreamDefaultControllerGetDesiredSize227};228// Abstract operations for the ReadableStream.229function AcquireReadableStreamBYOBReader(stream) {230 return new ReadableStreamBYOBReader(stream);231}232function AcquireReadableStreamDefaultReader(stream) {233 return new ReadableStreamDefaultReader(stream);234}235function IsReadableStream(x) {236 if (!typeIsObject(x)) {237 return false;238 }239 if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {240 return false;241 }242 return true;243}244function IsReadableStreamDisturbed(stream) {245 assert(IsReadableStream(stream) === true, 'IsReadableStreamDisturbed should only be used on known readable streams');246 return stream._disturbed;247}248function IsReadableStreamLocked(stream) {249 assert(IsReadableStream(stream) === true, 'IsReadableStreamLocked should only be used on known readable streams');250 if (stream._reader === undefined) {251 return false;252 }253 return true;254}255function ReadableStreamTee(stream, cloneForBranch2) {256 assert(IsReadableStream(stream) === true);257 assert(typeof cloneForBranch2 === 'boolean');258 const reader = AcquireReadableStreamDefaultReader(stream);259 const teeState = {260 closedOrErrored: false,261 canceled1: false,262 canceled2: false,263 reason1: undefined,264 reason2: undefined265 };266 teeState.promise = new Promise(resolve => {267 teeState._resolve = resolve;268 });269 const pull = create_ReadableStreamTeePullFunction();270 pull._reader = reader;271 pull._teeState = teeState;272 pull._cloneForBranch2 = cloneForBranch2;273 const cancel1 = create_ReadableStreamTeeBranch1CancelFunction();274 cancel1._stream = stream;275 cancel1._teeState = teeState;276 const cancel2 = create_ReadableStreamTeeBranch2CancelFunction();277 cancel2._stream = stream;278 cancel2._teeState = teeState;279 const underlyingSource1 = Object.create(Object.prototype);280 createDataProperty(underlyingSource1, 'pull', pull);281 createDataProperty(underlyingSource1, 'cancel', cancel1);282 const branch1Stream = new ReadableStream(underlyingSource1);283 const underlyingSource2 = Object.create(Object.prototype);284 createDataProperty(underlyingSource2, 'pull', pull);285 createDataProperty(underlyingSource2, 'cancel', cancel2);286 const branch2Stream = new ReadableStream(underlyingSource2);287 pull._branch1 = branch1Stream._readableStreamController;288 pull._branch2 = branch2Stream._readableStreamController;289 reader._closedPromise.catch(r => {290 if (teeState.closedOrErrored === true) {291 return;292 }293 ReadableStreamDefaultControllerError(pull._branch1, r);294 ReadableStreamDefaultControllerError(pull._branch2, r);295 teeState.closedOrErrored = true;296 });297 return [branch1Stream, branch2Stream];298}299function create_ReadableStreamTeePullFunction() {300 function f() {301 const { _reader: reader, _branch1: branch1, _branch2: branch2, _teeState: teeState/* ,302 _cloneForBranch2: cloneForBranch2*/ } = f;303 return ReadableStreamDefaultReaderRead(reader).then(result => {304 assert(typeIsObject(result));305 const value = result.value;306 const done = result.done;307 assert(typeof done === 'boolean');308 if (done === true && teeState.closedOrErrored === false) {309 if (teeState.canceled1 === false) {310 ReadableStreamDefaultControllerClose(branch1);311 }312 if (teeState.canceled2 === false) {313 ReadableStreamDefaultControllerClose(branch2);314 }315 teeState.closedOrErrored = true;316 }317 if (teeState.closedOrErrored === true) {318 return;319 }320 const value1 = value;321 const value2 = value;322 // There is no way to access the cloning code right now in the reference implementation.323 // If we add one then we'll need an implementation for serializable objects.324 // if (teeState.canceled2 === false && cloneForBranch2 === true) {325 // value2 = StructuredDeserialize(StructuredSerialize(value2));326 // }327 if (teeState.canceled1 === false) {328 ReadableStreamDefaultControllerEnqueue(branch1, value1);329 }330 if (teeState.canceled2 === false) {331 ReadableStreamDefaultControllerEnqueue(branch2, value2);332 }333 });334 }335 return f;336}337function create_ReadableStreamTeeBranch1CancelFunction() {338 function f(reason) {339 const { _stream: stream, _teeState: teeState } = f;340 teeState.canceled1 = true;341 teeState.reason1 = reason;342 if (teeState.canceled2 === true) {343 const compositeReason = createArrayFromList([teeState.reason1, teeState.reason2]);344 const cancelResult = ReadableStreamCancel(stream, compositeReason);345 teeState._resolve(cancelResult);346 }347 return teeState.promise;348 }349 return f;350}351function create_ReadableStreamTeeBranch2CancelFunction() {352 function f(reason) {353 const { _stream: stream, _teeState: teeState } = f;354 teeState.canceled2 = true;355 teeState.reason2 = reason;356 if (teeState.canceled1 === true) {357 const compositeReason = createArrayFromList([teeState.reason1, teeState.reason2]);358 const cancelResult = ReadableStreamCancel(stream, compositeReason);359 teeState._resolve(cancelResult);360 }361 return teeState.promise;362 }363 return f;364}365// ReadableStream API exposed for controllers.366function ReadableStreamAddReadIntoRequest(stream) {367 assert(IsReadableStreamBYOBReader(stream._reader) === true);368 assert(stream._state === 'readable' || stream._state === 'closed');369 const promise = new Promise((resolve, reject) => {370 const readIntoRequest = {371 _resolve: resolve,372 _reject: reject373 };374 stream._reader._readIntoRequests.push(readIntoRequest);375 });376 return promise;377}378function ReadableStreamAddReadRequest(stream) {379 assert(IsReadableStreamDefaultReader(stream._reader) === true);380 assert(stream._state === 'readable');381 const promise = new Promise((resolve, reject) => {382 const readRequest = {383 _resolve: resolve,384 _reject: reject385 };386 stream._reader._readRequests.push(readRequest);387 });388 return promise;389}390function ReadableStreamCancel(stream, reason) {391 stream._disturbed = true;392 if (stream._state === 'closed') {393 return Promise.resolve(undefined);394 }395 if (stream._state === 'errored') {396 return Promise.reject(stream._storedError);397 }398 ReadableStreamClose(stream);399 const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);400 return sourceCancelPromise.then(() => undefined);401}402function ReadableStreamClose(stream) {403 assert(stream._state === 'readable');404 stream._state = 'closed';405 const reader = stream._reader;406 if (reader === undefined) {407 return undefined;408 }409 if (IsReadableStreamDefaultReader(reader) === true) {410 for (const { _resolve } of reader._readRequests) {411 _resolve(CreateIterResultObject(undefined, true));412 }413 reader._readRequests = [];414 }415 defaultReaderClosedPromiseResolve(reader);416 return undefined;417}418function ReadableStreamError(stream, e) {419 assert(IsReadableStream(stream) === true, 'stream must be ReadableStream');420 assert(stream._state === 'readable', 'state must be readable');421 stream._state = 'errored';422 stream._storedError = e;423 const reader = stream._reader;424 if (reader === undefined) {425 return undefined;426 }427 if (IsReadableStreamDefaultReader(reader) === true) {428 for (const readRequest of reader._readRequests) {429 readRequest._reject(e);430 }431 reader._readRequests = [];432 } else {433 assert(IsReadableStreamBYOBReader(reader), 'reader must be ReadableStreamBYOBReader');434 for (const readIntoRequest of reader._readIntoRequests) {435 readIntoRequest._reject(e);436 }437 reader._readIntoRequests = [];438 }439 defaultReaderClosedPromiseReject(reader, e);440 reader._closedPromise.catch(() => {});441}442function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {443 const reader = stream._reader;444 assert(reader._readIntoRequests.length > 0);445 const readIntoRequest = reader._readIntoRequests.shift();446 readIntoRequest._resolve(CreateIterResultObject(chunk, done));447}448function ReadableStreamFulfillReadRequest(stream, chunk, done) {449 const reader = stream._reader;450 assert(reader._readRequests.length > 0);451 const readRequest = reader._readRequests.shift();452 readRequest._resolve(CreateIterResultObject(chunk, done));453}454function ReadableStreamGetNumReadIntoRequests(stream) {455 return stream._reader._readIntoRequests.length;456}457function ReadableStreamGetNumReadRequests(stream) {458 return stream._reader._readRequests.length;459}460function ReadableStreamHasBYOBReader(stream) {461 const reader = stream._reader;462 if (reader === undefined) {463 return false;464 }465 if (IsReadableStreamBYOBReader(reader) === false) {466 return false;467 }468 return true;469}470function ReadableStreamHasDefaultReader(stream) {471 const reader = stream._reader;472 if (reader === undefined) {473 return false;474 }475 if (IsReadableStreamDefaultReader(reader) === false) {476 return false;477 }478 return true;479}480// Readers481class ReadableStreamDefaultReader {482 constructor(stream) {483 if (IsReadableStream(stream) === false) {484 throw new TypeError('ReadableStreamDefaultReader can only be constructed with a ReadableStream instance');485 }486 if (IsReadableStreamLocked(stream) === true) {487 throw new TypeError('This stream has already been locked for exclusive reading by another reader');488 }489 ReadableStreamReaderGenericInitialize(this, stream);490 this._readRequests = [];491 }492 get closed() {493 if (IsReadableStreamDefaultReader(this) === false) {494 return Promise.reject(defaultReaderBrandCheckException('closed'));495 }496 return this._closedPromise;497 }498 cancel(reason) {499 if (IsReadableStreamDefaultReader(this) === false) {500 return Promise.reject(defaultReaderBrandCheckException('cancel'));501 }502 if (this._ownerReadableStream === undefined) {503 return Promise.reject(readerLockException('cancel'));504 }505 return ReadableStreamReaderGenericCancel(this, reason);506 }507 read() {508 if (IsReadableStreamDefaultReader(this) === false) {509 return Promise.reject(defaultReaderBrandCheckException('read'));510 }511 if (this._ownerReadableStream === undefined) {512 return Promise.reject(readerLockException('read from'));513 }514 return ReadableStreamDefaultReaderRead(this);515 }516 releaseLock() {517 if (IsReadableStreamDefaultReader(this) === false) {518 throw defaultReaderBrandCheckException('releaseLock');519 }520 if (this._ownerReadableStream === undefined) {521 return;522 }523 if (this._readRequests.length > 0) {524 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');525 }526 ReadableStreamReaderGenericRelease(this);527 }528}529class ReadableStreamBYOBReader {530 constructor(stream) {531 if (!IsReadableStream(stream)) {532 throw new TypeError('ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a ' +533 'byte source');534 }535 if (IsReadableByteStreamController(stream._readableStreamController) === false) {536 throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +537 'source');538 }539 if (IsReadableStreamLocked(stream)) {540 throw new TypeError('This stream has already been locked for exclusive reading by another reader');541 }542 ReadableStreamReaderGenericInitialize(this, stream);543 this._readIntoRequests = [];544 }545 get closed() {546 if (!IsReadableStreamBYOBReader(this)) {547 return Promise.reject(byobReaderBrandCheckException('closed'));548 }549 return this._closedPromise;550 }551 cancel(reason) {552 if (!IsReadableStreamBYOBReader(this)) {553 return Promise.reject(byobReaderBrandCheckException('cancel'));554 }555 if (this._ownerReadableStream === undefined) {556 return Promise.reject(readerLockException('cancel'));557 }558 return ReadableStreamReaderGenericCancel(this, reason);559 }560 read(view) {561 if (!IsReadableStreamBYOBReader(this)) {562 return Promise.reject(byobReaderBrandCheckException('read'));563 }564 if (this._ownerReadableStream === undefined) {565 return Promise.reject(readerLockException('read from'));566 }567 if (!ArrayBuffer.isView(view)) {568 return Promise.reject(new TypeError('view must be an array buffer view'));569 }570 if (view.byteLength === 0) {571 return Promise.reject(new TypeError('view must have non-zero byteLength'));572 }573 return ReadableStreamBYOBReaderRead(this, view);574 }575 releaseLock() {576 if (!IsReadableStreamBYOBReader(this)) {577 throw byobReaderBrandCheckException('releaseLock');578 }579 if (this._ownerReadableStream === undefined) {580 return;581 }582 if (this._readIntoRequests.length > 0) {583 throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');584 }585 ReadableStreamReaderGenericRelease(this);586 }587}588// Abstract operations for the readers.589function IsReadableStreamBYOBReader(x) {590 if (!typeIsObject(x)) {591 return false;592 }593 if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {594 return false;595 }596 return true;597}598function IsReadableStreamDefaultReader(x) {599 if (!typeIsObject(x)) {600 return false;601 }602 if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {603 return false;604 }605 return true;606}607function ReadableStreamReaderGenericInitialize(reader, stream) {608 reader._ownerReadableStream = stream;609 stream._reader = reader;610 if (stream._state === 'readable') {611 defaultReaderClosedPromiseInitialize(reader);612 } else if (stream._state === 'closed') {613 defaultReaderClosedPromiseInitializeAsResolved(reader);614 } else {615 assert(stream._state === 'errored', 'state must be errored');616 defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);617 reader._closedPromise.catch(() => {});618 }619}620// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state621// check.622function ReadableStreamReaderGenericCancel(reader, reason) {623 const stream = reader._ownerReadableStream;624 assert(stream !== undefined);625 return ReadableStreamCancel(stream, reason);626}627function ReadableStreamReaderGenericRelease(reader) {628 assert(reader._ownerReadableStream !== undefined);629 assert(reader._ownerReadableStream._reader === reader);630 if (reader._ownerReadableStream._state === 'readable') {631 defaultReaderClosedPromiseReject(632 reader,633 new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness'));634 } else {635 defaultReaderClosedPromiseResetToRejected(636 reader,637 new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness'));638 }639 reader._closedPromise.catch(() => {});640 reader._ownerReadableStream._reader = undefined;641 reader._ownerReadableStream = undefined;642}643function ReadableStreamBYOBReaderRead(reader, view) {644 const stream = reader._ownerReadableStream;645 assert(stream !== undefined);646 stream._disturbed = true;647 if (stream._state === 'errored') {648 return Promise.reject(stream._storedError);649 }650 // Controllers must implement this.651 return ReadableByteStreamControllerPullInto(stream._readableStreamController, view);652}653function ReadableStreamDefaultReaderRead(reader) {654 const stream = reader._ownerReadableStream;655 assert(stream !== undefined);656 stream._disturbed = true;657 if (stream._state === 'closed') {658 return Promise.resolve(CreateIterResultObject(undefined, true));659 }660 if (stream._state === 'errored') {661 return Promise.reject(stream._storedError);662 }663 assert(stream._state === 'readable');664 return stream._readableStreamController[PullSteps]();665}666// Controllers667class ReadableStreamDefaultController {668 constructor(stream, underlyingSource, size, highWaterMark) {669 if (IsReadableStream(stream) === false) {670 throw new TypeError('ReadableStreamDefaultController can only be constructed with a ReadableStream instance');671 }672 if (stream._readableStreamController !== undefined) {673 throw new TypeError(674 'ReadableStreamDefaultController instances can only be created by the ReadableStream constructor');675 }676 this._controlledReadableStream = stream;677 this._underlyingSource = underlyingSource;678 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.679 this._queue = undefined;680 this._queueTotalSize = undefined;681 ResetQueue(this);682 this._started = false;683 this._closeRequested = false;684 this._pullAgain = false;685 this._pulling = false;686 const normalizedStrategy = ValidateAndNormalizeQueuingStrategy(size, highWaterMark);687 this._strategySize = normalizedStrategy.size;688 this._strategyHWM = normalizedStrategy.highWaterMark;689 const controller = this;690 const startResult = InvokeOrNoop(underlyingSource, 'start', [this]);691 Promise.resolve(startResult).then(692 () => {693 controller._started = true;694 assert(controller._pulling === false);695 assert(controller._pullAgain === false);696 ReadableStreamDefaultControllerCallPullIfNeeded(controller);697 },698 r => {699 ReadableStreamDefaultControllerErrorIfNeeded(controller, r);700 }701 )702 .catch(rethrowAssertionErrorRejection);703 }704 get desiredSize() {705 if (IsReadableStreamDefaultController(this) === false) {706 throw defaultControllerBrandCheckException('desiredSize');707 }708 return ReadableStreamDefaultControllerGetDesiredSize(this);709 }710 close() {711 if (IsReadableStreamDefaultController(this) === false) {712 throw defaultControllerBrandCheckException('close');713 }714 if (this._closeRequested === true) {715 throw new TypeError('The stream has already been closed; do not close it again!');716 }717 const state = this._controlledReadableStream._state;718 if (state !== 'readable') {719 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);720 }721 ReadableStreamDefaultControllerClose(this);722 }723 enqueue(chunk) {724 if (IsReadableStreamDefaultController(this) === false) {725 throw defaultControllerBrandCheckException('enqueue');726 }727 if (this._closeRequested === true) {728 throw new TypeError('stream is closed or draining');729 }730 const state = this._controlledReadableStream._state;731 if (state !== 'readable') {732 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);733 }734 return ReadableStreamDefaultControllerEnqueue(this, chunk);735 }736 error(e) {737 if (IsReadableStreamDefaultController(this) === false) {738 throw defaultControllerBrandCheckException('error');739 }740 const stream = this._controlledReadableStream;741 if (stream._state !== 'readable') {742 throw new TypeError(`The stream is ${stream._state} and so cannot be errored`);743 }744 ReadableStreamDefaultControllerError(this, e);745 }746 [CancelSteps](reason) {747 ResetQueue(this);748 return PromiseInvokeOrNoop(this._underlyingSource, 'cancel', [reason]);749 }750 [PullSteps]() {751 const stream = this._controlledReadableStream;752 if (this._queue.length > 0) {753 const chunk = DequeueValue(this);754 if (this._closeRequested === true && this._queue.length === 0) {755 ReadableStreamClose(stream);756 } else {757 ReadableStreamDefaultControllerCallPullIfNeeded(this);758 }759 return Promise.resolve(CreateIterResultObject(chunk, false));760 }761 const pendingPromise = ReadableStreamAddReadRequest(stream);762 ReadableStreamDefaultControllerCallPullIfNeeded(this);763 return pendingPromise;764 }765}766// Abstract operations for the ReadableStreamDefaultController.767function IsReadableStreamDefaultController(x) {768 if (!typeIsObject(x)) {769 return false;770 }771 if (!Object.prototype.hasOwnProperty.call(x, '_underlyingSource')) {772 return false;773 }774 return true;775}776function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {777 const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);778 if (shouldPull === false) {779 return undefined;780 }781 if (controller._pulling === true) {782 controller._pullAgain = true;783 return undefined;784 }785 assert(controller._pullAgain === false);786 controller._pulling = true;787 const pullPromise = PromiseInvokeOrNoop(controller._underlyingSource, 'pull', [controller]);788 pullPromise.then(789 () => {790 controller._pulling = false;791 if (controller._pullAgain === true) {792 controller._pullAgain = false;793 return ReadableStreamDefaultControllerCallPullIfNeeded(controller);794 }795 return undefined;796 },797 e => {798 ReadableStreamDefaultControllerErrorIfNeeded(controller, e);799 }800 )801 .catch(rethrowAssertionErrorRejection);802 return undefined;803}804function ReadableStreamDefaultControllerShouldCallPull(controller) {805 const stream = controller._controlledReadableStream;806 if (stream._state === 'closed' || stream._state === 'errored') {807 return false;808 }809 if (controller._closeRequested === true) {810 return false;811 }812 if (controller._started === false) {813 return false;814 }815 if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {816 return true;817 }818 const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);819 if (desiredSize > 0) {820 return true;821 }822 return false;823}824// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.825function ReadableStreamDefaultControllerClose(controller) {826 const stream = controller._controlledReadableStream;827 assert(controller._closeRequested === false);828 assert(stream._state === 'readable');829 controller._closeRequested = true;830 if (controller._queue.length === 0) {831 ReadableStreamClose(stream);832 }833}834function ReadableStreamDefaultControllerEnqueue(controller, chunk) {835 const stream = controller._controlledReadableStream;836 assert(controller._closeRequested === false);837 assert(stream._state === 'readable');838 if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {839 ReadableStreamFulfillReadRequest(stream, chunk, false);840 } else {841 let chunkSize = 1;842 if (controller._strategySize !== undefined) {843 const strategySize = controller._strategySize;844 try {845 chunkSize = strategySize(chunk);846 } catch (chunkSizeE) {847 ReadableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);848 throw chunkSizeE;849 }850 }851 try {852 EnqueueValueWithSize(controller, chunk, chunkSize);853 } catch (enqueueE) {854 ReadableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);855 throw enqueueE;856 }857 }858 ReadableStreamDefaultControllerCallPullIfNeeded(controller);859 return undefined;860}861function ReadableStreamDefaultControllerError(controller, e) {862 const stream = controller._controlledReadableStream;863 assert(stream._state === 'readable');864 ResetQueue(controller);865 ReadableStreamError(stream, e);866}867function ReadableStreamDefaultControllerErrorIfNeeded(controller, e) {868 if (controller._controlledReadableStream._state === 'readable') {869 ReadableStreamDefaultControllerError(controller, e);870 }871}872function ReadableStreamDefaultControllerGetDesiredSize(controller) {873 const stream = controller._controlledReadableStream;874 const state = stream._state;875 if (state === 'errored') {876 return null;877 }878 if (state === 'closed') {879 return 0;880 }881 return controller._strategyHWM - controller._queueTotalSize;882}883class ReadableStreamBYOBRequest {884 constructor(controller, view) {885 this._associatedReadableByteStreamController = controller;886 this._view = view;887 }888 get view() {889 return this._view;890 }891 respond(bytesWritten) {892 if (IsReadableStreamBYOBRequest(this) === false) {893 throw byobRequestBrandCheckException('respond');894 }895 if (this._associatedReadableByteStreamController === undefined) {896 throw new TypeError('This BYOB request has been invalidated');897 }898 ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);899 }900 respondWithNewView(view) {901 if (IsReadableStreamBYOBRequest(this) === false) {902 throw byobRequestBrandCheckException('respond');903 }904 if (this._associatedReadableByteStreamController === undefined) {905 throw new TypeError('This BYOB request has been invalidated');906 }907 if (!ArrayBuffer.isView(view)) {908 throw new TypeError('You can only respond with array buffer views');909 }910 ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);911 }912}913class ReadableByteStreamController {914 constructor(stream, underlyingByteSource, highWaterMark) {915 if (IsReadableStream(stream) === false) {916 throw new TypeError('ReadableByteStreamController can only be constructed with a ReadableStream instance given ' +917 'a byte source');918 }919 if (stream._readableStreamController !== undefined) {920 throw new TypeError(921 'ReadableByteStreamController instances can only be created by the ReadableStream constructor given a byte ' +922 'source');923 }924 this._controlledReadableStream = stream;925 this._underlyingByteSource = underlyingByteSource;926 this._pullAgain = false;927 this._pulling = false;928 ReadableByteStreamControllerClearPendingPullIntos(this);929 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.930 this._queue = this._queueTotalSize = undefined;931 ResetQueue(this);932 this._closeRequested = false;933 this._started = false;934 this._strategyHWM = ValidateAndNormalizeHighWaterMark(highWaterMark);935 const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;936 if (autoAllocateChunkSize !== undefined) {937 if (Number.isInteger(autoAllocateChunkSize) === false || autoAllocateChunkSize <= 0) {938 throw new RangeError('autoAllocateChunkSize must be a positive integer');939 }940 }941 this._autoAllocateChunkSize = autoAllocateChunkSize;942 this._pendingPullIntos = [];943 const controller = this;944 const startResult = InvokeOrNoop(underlyingByteSource, 'start', [this]);945 Promise.resolve(startResult).then(946 () => {947 controller._started = true;948 assert(controller._pulling === false);949 assert(controller._pullAgain === false);950 ReadableByteStreamControllerCallPullIfNeeded(controller);951 },952 r => {953 if (stream._state === 'readable') {954 ReadableByteStreamControllerError(controller, r);955 }956 }957 )958 .catch(rethrowAssertionErrorRejection);959 }960 get byobRequest() {961 if (IsReadableByteStreamController(this) === false) {962 throw byteStreamControllerBrandCheckException('byobRequest');963 }964 if (this._byobRequest === undefined && this._pendingPullIntos.length > 0) {965 const firstDescriptor = this._pendingPullIntos[0];966 const view = new Uint8Array(firstDescriptor.buffer,967 firstDescriptor.byteOffset + firstDescriptor.bytesFilled,968 firstDescriptor.byteLength - firstDescriptor.bytesFilled);969 this._byobRequest = new ReadableStreamBYOBRequest(this, view);970 }971 return this._byobRequest;972 }973 get desiredSize() {974 if (IsReadableByteStreamController(this) === false) {975 throw byteStreamControllerBrandCheckException('desiredSize');976 }977 return ReadableByteStreamControllerGetDesiredSize(this);978 }979 close() {980 if (IsReadableByteStreamController(this) === false) {981 throw byteStreamControllerBrandCheckException('close');982 }983 if (this._closeRequested === true) {984 throw new TypeError('The stream has already been closed; do not close it again!');985 }986 const state = this._controlledReadableStream._state;987 if (state !== 'readable') {988 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);989 }990 ReadableByteStreamControllerClose(this);991 }992 enqueue(chunk) {993 if (IsReadableByteStreamController(this) === false) {994 throw byteStreamControllerBrandCheckException('enqueue');995 }996 if (this._closeRequested === true) {997 throw new TypeError('stream is closed or draining');998 }999 const state = this._controlledReadableStream._state;1000 if (state !== 'readable') {1001 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);1002 }1003 if (!ArrayBuffer.isView(chunk)) {1004 throw new TypeError('You can only enqueue array buffer views when using a ReadableByteStreamController');1005 }1006 ReadableByteStreamControllerEnqueue(this, chunk);1007 }1008 error(e) {1009 if (IsReadableByteStreamController(this) === false) {1010 throw byteStreamControllerBrandCheckException('error');1011 }1012 const stream = this._controlledReadableStream;1013 if (stream._state !== 'readable') {1014 throw new TypeError(`The stream is ${stream._state} and so cannot be errored`);1015 }1016 ReadableByteStreamControllerError(this, e);1017 }1018 [CancelSteps](reason) {1019 if (this._pendingPullIntos.length > 0) {1020 const firstDescriptor = this._pendingPullIntos[0];1021 firstDescriptor.bytesFilled = 0;1022 }1023 ResetQueue(this);1024 return PromiseInvokeOrNoop(this._underlyingByteSource, 'cancel', [reason]);1025 }1026 [PullSteps]() {1027 const stream = this._controlledReadableStream;1028 assert(ReadableStreamHasDefaultReader(stream) === true);1029 if (this._queueTotalSize > 0) {1030 assert(ReadableStreamGetNumReadRequests(stream) === 0);1031 const entry = this._queue.shift();1032 this._queueTotalSize -= entry.byteLength;1033 ReadableByteStreamControllerHandleQueueDrain(this);1034 let view;1035 try {1036 view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);1037 } catch (viewE) {1038 return Promise.reject(viewE);1039 }1040 return Promise.resolve(CreateIterResultObject(view, false));1041 }1042 const autoAllocateChunkSize = this._autoAllocateChunkSize;1043 if (autoAllocateChunkSize !== undefined) {1044 let buffer;1045 try {1046 buffer = new ArrayBuffer(autoAllocateChunkSize);1047 } catch (bufferE) {1048 return Promise.reject(bufferE);1049 }1050 const pullIntoDescriptor = {1051 buffer,1052 byteOffset: 0,1053 byteLength: autoAllocateChunkSize,1054 bytesFilled: 0,1055 elementSize: 1,1056 ctor: Uint8Array,1057 readerType: 'default'1058 };1059 this._pendingPullIntos.push(pullIntoDescriptor);1060 }1061 const promise = ReadableStreamAddReadRequest(stream);1062 ReadableByteStreamControllerCallPullIfNeeded(this);1063 return promise;1064 }1065}1066// Abstract operations for the ReadableByteStreamController.1067function IsReadableByteStreamController(x) {1068 if (!typeIsObject(x)) {1069 return false;1070 }1071 if (!Object.prototype.hasOwnProperty.call(x, '_underlyingByteSource')) {1072 return false;1073 }1074 return true;1075}1076function IsReadableStreamBYOBRequest(x) {1077 if (!typeIsObject(x)) {1078 return false;1079 }1080 if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {1081 return false;1082 }1083 return true;1084}1085function ReadableByteStreamControllerCallPullIfNeeded(controller) {1086 const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);1087 if (shouldPull === false) {1088 return undefined;1089 }1090 if (controller._pulling === true) {1091 controller._pullAgain = true;1092 return undefined;1093 }1094 assert(controller._pullAgain === false);1095 controller._pulling = true;1096 // TODO: Test controller argument1097 const pullPromise = PromiseInvokeOrNoop(controller._underlyingByteSource, 'pull', [controller]);1098 pullPromise.then(1099 () => {1100 controller._pulling = false;1101 if (controller._pullAgain === true) {1102 controller._pullAgain = false;1103 ReadableByteStreamControllerCallPullIfNeeded(controller);1104 }1105 },1106 e => {1107 if (controller._controlledReadableStream._state === 'readable') {1108 ReadableByteStreamControllerError(controller, e);1109 }1110 }1111 )1112 .catch(rethrowAssertionErrorRejection);1113 return undefined;1114}1115function ReadableByteStreamControllerClearPendingPullIntos(controller) {1116 ReadableByteStreamControllerInvalidateBYOBRequest(controller);1117 controller._pendingPullIntos = [];1118}1119function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {1120 assert(stream._state !== 'errored', 'state must not be errored');1121 let done = false;1122 if (stream._state === 'closed') {1123 assert(pullIntoDescriptor.bytesFilled === 0);1124 done = true;1125 }1126 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);1127 if (pullIntoDescriptor.readerType === 'default') {1128 ReadableStreamFulfillReadRequest(stream, filledView, done);1129 } else {1130 assert(pullIntoDescriptor.readerType === 'byob');1131 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);1132 }1133}1134function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {1135 const bytesFilled = pullIntoDescriptor.bytesFilled;1136 const elementSize = pullIntoDescriptor.elementSize;1137 assert(bytesFilled <= pullIntoDescriptor.byteLength);1138 assert(bytesFilled % elementSize === 0);1139 return new pullIntoDescriptor.ctor(1140 pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);1141}1142function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {1143 controller._queue.push({ buffer, byteOffset, byteLength });1144 controller._queueTotalSize += byteLength;1145}1146function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {1147 const elementSize = pullIntoDescriptor.elementSize;1148 const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;1149 const maxBytesToCopy = Math.min(controller._queueTotalSize,1150 pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);1151 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;1152 const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;1153 let totalBytesToCopyRemaining = maxBytesToCopy;1154 let ready = false;1155 if (maxAlignedBytes > currentAlignedBytes) {1156 totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;1157 ready = true;1158 }1159 const queue = controller._queue;1160 while (totalBytesToCopyRemaining > 0) {1161 const headOfQueue = queue[0];1162 const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);1163 const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;1164 ArrayBufferCopy(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);1165 if (headOfQueue.byteLength === bytesToCopy) {1166 queue.shift();1167 } else {1168 headOfQueue.byteOffset += bytesToCopy;1169 headOfQueue.byteLength -= bytesToCopy;1170 }1171 controller._queueTotalSize -= bytesToCopy;1172 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);1173 totalBytesToCopyRemaining -= bytesToCopy;1174 }1175 if (ready === false) {1176 assert(controller._queueTotalSize === 0, 'queue must be empty');1177 assert(pullIntoDescriptor.bytesFilled > 0);1178 assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);1179 }1180 return ready;1181}1182function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {1183 assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos[0] === pullIntoDescriptor);1184 ReadableByteStreamControllerInvalidateBYOBRequest(controller);1185 pullIntoDescriptor.bytesFilled += size;1186}1187function ReadableByteStreamControllerHandleQueueDrain(controller) {1188 assert(controller._controlledReadableStream._state === 'readable');1189 if (controller._queueTotalSize === 0 && controller._closeRequested === true) {1190 ReadableStreamClose(controller._controlledReadableStream);1191 } else {1192 ReadableByteStreamControllerCallPullIfNeeded(controller);1193 }1194}1195function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {1196 if (controller._byobRequest === undefined) {1197 return;1198 }1199 controller._byobRequest._associatedReadableByteStreamController = undefined;1200 controller._byobRequest._view = undefined;1201 controller._byobRequest = undefined;1202}1203function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {1204 assert(controller._closeRequested === false);1205 while (controller._pendingPullIntos.length > 0) {1206 if (controller._queueTotalSize === 0) {1207 return;1208 }1209 const pullIntoDescriptor = controller._pendingPullIntos[0];1210 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {1211 ReadableByteStreamControllerShiftPendingPullInto(controller);1212 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor);1213 }1214 }1215}1216function ReadableByteStreamControllerPullInto(controller, view) {1217 const stream = controller._controlledReadableStream;1218 let elementSize = 1;1219 if (view.constructor !== DataView) {1220 elementSize = view.constructor.BYTES_PER_ELEMENT;1221 }1222 const ctor = view.constructor;1223 const pullIntoDescriptor = {1224 buffer: view.buffer,1225 byteOffset: view.byteOffset,1226 byteLength: view.byteLength,1227 bytesFilled: 0,1228 elementSize,1229 ctor,1230 readerType: 'byob'1231 };1232 if (controller._pendingPullIntos.length > 0) {1233 pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);1234 controller._pendingPullIntos.push(pullIntoDescriptor);1235 // No ReadableByteStreamControllerCallPullIfNeeded() call since:1236 // - No change happens on desiredSize1237 // - The source has already been notified of that there's at least 1 pending read(view)1238 return ReadableStreamAddReadIntoRequest(stream);1239 }1240 if (stream._state === 'closed') {1241 const emptyView = new view.constructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);1242 return Promise.resolve(CreateIterResultObject(emptyView, true));1243 }1244 if (controller._queueTotalSize > 0) {1245 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {1246 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);1247 ReadableByteStreamControllerHandleQueueDrain(controller);1248 return Promise.resolve(CreateIterResultObject(filledView, false));1249 }1250 if (controller._closeRequested === true) {1251 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');1252 ReadableByteStreamControllerError(controller, e);1253 return Promise.reject(e);1254 }1255 }1256 pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);1257 controller._pendingPullIntos.push(pullIntoDescriptor);1258 const promise = ReadableStreamAddReadIntoRequest(stream);1259 ReadableByteStreamControllerCallPullIfNeeded(controller);1260 return promise;1261}1262function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {1263 firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);1264 assert(firstDescriptor.bytesFilled === 0, 'bytesFilled must be 0');1265 const stream = controller._controlledReadableStream;1266 if (ReadableStreamHasBYOBReader(stream) === true) {1267 while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {1268 const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);1269 ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);1270 }1271 }1272}1273function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {1274 if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {1275 throw new RangeError('bytesWritten out of range');1276 }1277 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);1278 if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {1279 // TODO: Figure out whether we should detach the buffer or not here.1280 return;1281 }1282 ReadableByteStreamControllerShiftPendingPullInto(controller);1283 const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;1284 if (remainderSize > 0) {1285 const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;1286 const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);1287 ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);1288 }1289 pullIntoDescriptor.buffer = TransferArrayBuffer(pullIntoDescriptor.buffer);1290 pullIntoDescriptor.bytesFilled -= remainderSize;1291 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor);1292 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);1293}1294function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {1295 const firstDescriptor = controller._pendingPullIntos[0];1296 const stream = controller._controlledReadableStream;1297 if (stream._state === 'closed') {1298 if (bytesWritten !== 0) {1299 throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');1300 }1301 ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);1302 } else {1303 assert(stream._state === 'readable');1304 ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);1305 }1306}1307function ReadableByteStreamControllerShiftPendingPullInto(controller) {1308 const descriptor = controller._pendingPullIntos.shift();1309 ReadableByteStreamControllerInvalidateBYOBRequest(controller);1310 return descriptor;1311}1312function ReadableByteStreamControllerShouldCallPull(controller) {1313 const stream = controller._controlledReadableStream;1314 if (stream._state !== 'readable') {1315 return false;1316 }1317 if (controller._closeRequested === true) {1318 return false;1319 }1320 if (controller._started === false) {1321 return false;1322 }1323 if (ReadableStreamHasDefaultReader(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {1324 return true;1325 }1326 if (ReadableStreamHasBYOBReader(stream) === true && ReadableStreamGetNumReadIntoRequests(stream) > 0) {1327 return true;1328 }1329 if (ReadableByteStreamControllerGetDesiredSize(controller) > 0) {1330 return true;1331 }1332 return false;1333}1334// A client of ReadableByteStreamController may use these functions directly to bypass state check.1335function ReadableByteStreamControllerClose(controller) {1336 const stream = controller._controlledReadableStream;1337 assert(controller._closeRequested === false);1338 assert(stream._state === 'readable');1339 if (controller._queueTotalSize > 0) {1340 controller._closeRequested = true;1341 return;1342 }1343 if (controller._pendingPullIntos.length > 0) {1344 const firstPendingPullInto = controller._pendingPullIntos[0];1345 if (firstPendingPullInto.bytesFilled > 0) {1346 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');1347 ReadableByteStreamControllerError(controller, e);1348 throw e;1349 }1350 }1351 ReadableStreamClose(stream);1352}1353function ReadableByteStreamControllerEnqueue(controller, chunk) {1354 const stream = controller._controlledReadableStream;1355 assert(controller._closeRequested === false);1356 assert(stream._state === 'readable');1357 const buffer = chunk.buffer;1358 const byteOffset = chunk.byteOffset;1359 const byteLength = chunk.byteLength;1360 const transferredBuffer = TransferArrayBuffer(buffer);1361 if (ReadableStreamHasDefaultReader(stream) === true) {1362 if (ReadableStreamGetNumReadRequests(stream) === 0) {1363 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);1364 } else {1365 assert(controller._queue.length === 0);1366 const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);1367 ReadableStreamFulfillReadRequest(stream, transferredView, false);1368 }1369 } else if (ReadableStreamHasBYOBReader(stream) === true) {1370 // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.1371 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);1372 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);1373 } else {1374 assert(IsReadableStreamLocked(stream) === false, 'stream must not be locked');1375 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);1376 }1377}1378function ReadableByteStreamControllerError(controller, e) {1379 const stream = controller._controlledReadableStream;1380 assert(stream._state === 'readable');1381 ReadableByteStreamControllerClearPendingPullIntos(controller);1382 ResetQueue(controller);1383 ReadableStreamError(stream, e);1384}1385function ReadableByteStreamControllerGetDesiredSize(controller) {1386 const stream = controller._controlledReadableStream;1387 const state = stream._state;1388 if (state === 'errored') {1389 return null;1390 }1391 if (state === 'closed') {1392 return 0;1393 }1394 return controller._strategyHWM - controller._queueTotalSize;1395}1396function ReadableByteStreamControllerRespond(controller, bytesWritten) {1397 bytesWritten = Number(bytesWritten);1398 if (IsFiniteNonNegativeNumber(bytesWritten) === false) {1399 throw new RangeError('bytesWritten must be a finite');1400 }1401 assert(controller._pendingPullIntos.length > 0);1402 ReadableByteStreamControllerRespondInternal(controller, bytesWritten);1403}1404function ReadableByteStreamControllerRespondWithNewView(controller, view) {1405 assert(controller._pendingPullIntos.length > 0);1406 const firstDescriptor = controller._pendingPullIntos[0];1407 if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {1408 throw new RangeError('The region specified by view does not match byobRequest');1409 }1410 if (firstDescriptor.byteLength !== view.byteLength) {1411 throw new RangeError('The buffer of view has different capacity than byobRequest');1412 }1413 firstDescriptor.buffer = view.buffer;1414 ReadableByteStreamControllerRespondInternal(controller, view.byteLength);1415}1416// Helper functions for the ReadableStream.1417function streamBrandCheckException(name) {1418 return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);1419}1420// Helper functions for the readers.1421function readerLockException(name) {1422 return new TypeError('Cannot ' + name + ' a stream using a released reader');1423}1424// Helper functions for the ReadableStreamDefaultReader.1425function defaultReaderBrandCheckException(name) {1426 return new TypeError(1427 `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);1428}1429function defaultReaderClosedPromiseInitialize(reader) {1430 reader._closedPromise = new Promise((resolve, reject) => {1431 reader._closedPromise_resolve = resolve;1432 reader._closedPromise_reject = reject;1433 });1434}1435function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {1436 reader._closedPromise = Promise.reject(reason);1437 reader._closedPromise_resolve = undefined;1438 reader._closedPromise_reject = undefined;1439}1440function defaultReaderClosedPromiseInitializeAsResolved(reader) {1441 reader._closedPromise = Promise.resolve(undefined);1442 reader._closedPromise_resolve = undefined;1443 reader._closedPromise_reject = undefined;1444}1445function defaultReaderClosedPromiseReject(reader, reason) {1446 assert(reader._closedPromise_resolve !== undefined);1447 assert(reader._closedPromise_reject !== undefined);1448 reader._closedPromise_reject(reason);1449 reader._closedPromise_resolve = undefined;1450 reader._closedPromise_reject = undefined;1451}1452function defaultReaderClosedPromiseResetToRejected(reader, reason) {1453 assert(reader._closedPromise_resolve === undefined);1454 assert(reader._closedPromise_reject === undefined);1455 reader._closedPromise = Promise.reject(reason);1456}1457function defaultReaderClosedPromiseResolve(reader) {1458 assert(reader._closedPromise_resolve !== undefined);1459 assert(reader._closedPromise_reject !== undefined);1460 reader._closedPromise_resolve(undefined);1461 reader._closedPromise_resolve = undefined;1462 reader._closedPromise_reject = undefined;1463}1464// Helper functions for the ReadableStreamDefaultReader.1465function byobReaderBrandCheckException(name) {1466 return new TypeError(1467 `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);1468}1469// Helper functions for the ReadableStreamDefaultController.1470function defaultControllerBrandCheckException(name) {1471 return new TypeError(1472 `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);1473}1474// Helper functions for the ReadableStreamBYOBRequest.1475function byobRequestBrandCheckException(name) {1476 return new TypeError(1477 `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);1478}1479// Helper functions for the ReadableByteStreamController.1480function byteStreamControllerBrandCheckException(name) {1481 return new TypeError(1482 `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);1483}1484// Helper function for ReadableStream pipeThrough1485function ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise) {1486 try {1487 // This relies on the brand-check that is enforced by Promise.prototype.then(). As with the rest of the reference1488 // implementation, it doesn't attempt to do the right thing if someone has modified the global environment.1489 Promise.prototype.then.call(promise, undefined, () => {});1490 } catch (e) {1491 // The brand check failed, therefore the internal slot is not present and there's nothing further to do.1492 }...
Using AI Code Generation
1var harness = $262.createRealm().global;2var ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue = harness.ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue;3var p = new Promise(function(resolve, reject) {4 resolve(1);5});6p.then(function() {});7ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(p);8var harness = $262.createRealm().global;9var ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue = harness.ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue;10var p = new Promise(function(resolve, reject) {11 resolve(1);12});13p.then(function() {});14ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(p);15var harness = $262.createRealm().global;16var ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue = harness.ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue;17var p = new Promise(function(resolve, reject) {18 resolve(1);19});20p.then(function() {});21ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(p);22var harness = $262.createRealm().global;23var ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue = harness.ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue;
Using AI Code Generation
1var harness = $262.harness;2var ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue = harness.ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue;3var p = Promise.resolve();4var p2 = Promise.reject();5ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(p);6ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(p2);7p.catch(function(){});8p2.catch(function(){});9var harness = $262.harness;10var ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue = harness.ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue;11var p = Promise.resolve();12ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(p);13p.catch(function(){});
Using AI Code Generation
1const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = require('./harness/ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue.js');2const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToFalse } = require('./harness/ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToFalse.js');3const { ifIsObjectAndHasAPromiseIsHandledInternalSlotThrow } = require('./harness/ifIsObjectAndHasAPromiseIsHandledInternalSlotThrow.js');4const { ifIsObjectAndHasAPromiseIsHandledInternalSlotReturn } = require('./harness/ifIsObjectAndHasAPromiseIsHandledInternalSlotReturn.js');5const { ifIsObjectAndHasAPromiseIsHandledInternalSlotReturnUndefined } = require('./harness/ifIsObjectAndHasAPromiseIsHandledInternalSlotReturnUndefined.js');6const { ifIsObjectAndHasAPromiseIsHandledInternalSlotReturnUndefined } = require('./harness/ifIsObjectAndHasAPromiseIsHandledInternalSlotReturnUndefined.js');7const { ifIsObjectAndHasAPromiseIsHandledInternalSlotReturnUndefined } = require('./harness/ifIsObjectAndHasAPromiseIsHandledInternalSlotReturnUndefined.js');8const { ifIsObjectAndHasAPromiseIsHandledInternalSlotReturnUndefined } = require('./harness/ifIsObjectAndHasAPromiseIsHandledInternalSlotReturnUndefined.js');9const { ifIsObjectAndHasAPromiseIsHandled
Using AI Code Generation
1const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = require('./resources/testharness.js');2const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = require('./resources/testharness.js');3const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = require('./resources/testharness.js');4const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = require('./resources/testharness.js');5const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = require('./resources/testharness.js');6const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = require('./resources/testharness.js');7const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = require('./resources/testharness.js');8const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = require('./resources/testharness.js');9const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = require('./resources/testharness.js');
Using AI Code Generation
1const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = WPTLib;2ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);3const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = WPTLib;4ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);5const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = WPTLib;6ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);7const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = WPTLib;8ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);9const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = WPTLib;10ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);11const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = WPTLib;12ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);13const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = WPTLib;
Using AI Code Generation
1ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue = function(promise) {2 if (promise && promise.promiseIsHandledInternalSlot) {3 promise.promiseIsHandledInternalSlot = true;4 }5}6ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);7ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue = function(promise) {8 if (promise && promise.promiseIsHandledInternalSlot) {9 promise.promiseIsHandledInternalSlot = true;10 }11}12ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);13ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue = function(promise) {14 if (promise && promise.promiseIsHandledInternalSlot) {15 promise.promiseIsHandledInternalSlot = true;16 }17}18ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);19ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue = function(promise) {20 if (promise && promise.promiseIsHandledInternalSlot) {21 promise.promiseIsHandledInternalSlot = true;22 }23}24ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);
Using AI Code Generation
1const { ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue } = require('./resources/test-utils.js');2const { resolve } = require('path');3const { promiseResolvedWith } = require('./resources/testharness.js');4promise_test(t => {5 const promise = promiseResolvedWith(undefined);6 ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);7 return promise;8}, 'ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue with a promise that fulfills');9promise_test(t => {10 const promise = promiseResolvedWith(undefined);11 ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise);12 return promise;13}, 'ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue with a promise that fulfills');14function ifIsObjectAndHasAPromiseIsHandledInternalSlotSetPromiseIsHandledToTrue(promise) {15 if (typeof promise === 'object' && promise !== null && promise.hasOwnProperty('[[PromiseIsHandled]]')) {16 promise['[[PromiseIsHandled]]'] = true;17 }18}19function promiseResolvedWith(value) {20 return Promise.resolve(value);21}22function promise_test(func, name, properties) {23 const test = async_test(name, properties);24 test.step(() => Promise.resolve().then(() => func(test)).then(test.done, test.done));25}26function async_test(name, properties) {27 return new Test(name, properties, true);28}29function Test(name, properties, isAsync) {30 this.name = name;31 this.properties = properties;32 this.isAsync = isAsync;33 this.phase = 'test_start';34 this.steps = [];
Using AI Code Generation
1var harness = $262.createRealm().global;2var global = this;3var $262 = global.$262;4var asyncTest = harness.asyncTest;5var $DONE = harness.$DONE;6var $ERROR = harness.$ERROR;7var $COMPILE_ERROR = harness.$COMPILE_ERROR;8var $PRINT = harness.$PRINT;9var $DETACHBUFFER = harness.$DETACHBUFFER;10var $DETACHARRAYBUFFER = harness.$DETACHARRAYBUFFER;11var $DETACHARRAYBUFFERS = harness.$DETACHARRAYBUFFERS;12var $CREATEITERATOR = harness.$CREATEITERATOR;13var $CREATEITERABLE = harness.$CREATEITERABLE;14var $CREATEASYNCITERATOR = harness.$CREATEASYNCITERATOR;15var $CREATEASYNCITERABLE = harness.$CREATEASYNCITERABLE;16var $RESOLVEVALUE = harness.$RESOLVEVALUE;17var $RESOLVEVALUEUNWRAPPINGREJECTED = harness.$RESOLVEVALUEUNWRAPPINGREJECTED;18var $RESOLVENEXT = harness.$RESOLVENEXT;19var $RESOLVENEXTUNWRAPPINGREJECTED = harness.$RESOLVENEXTUNWRAPPINGREJECTED;20var $RESOLVE = harness.$RESOLVE;21var $REJECT = harness.$REJECT;22var $REJECTUNWRAPPINGREJECTED = harness.$REJECTUNWRAPPINGREJECTED;23var $CALL = harness.$CALL;24var $CALLBINDING = harness.$CALLBINDING;25var $CALLBINDINGTHIS = harness.$CALLBINDINGTHIS;26var $CALLBINDINGTHISVALUE = harness.$CALLBINDINGTHISVALUE;27var $CONSTRUCT = harness.$CONSTRUCT;28var $CONSTRUCTBINDING = harness.$CONSTRUCTBINDING;29var $CONSTRUCTBINDINGTHIS = harness.$CONSTRUCTBINDINGTHIS;30var $CONSTRUCTBINDINGTHISVALUE = harness.$CONSTRUCTBINDINGTHISVALUE;31var $GET = harness.$GET;32var $GETBINDING = harness.$GETBINDING;33var $GETBINDINGTHIS = harness.$GETBINDINGTHIS;34var $GETBINDINGTHISVALUE = harness.$GETBINDINGTHISVALUE;35var $GETVALUE = harness.$GETVALUE;36var $GETVALUEUNWRAPPINGREJECTED = harness.$GETVALUEUNWRAPPINGREJECTED;37var $GETVALUEUNWRAPPINGREJECTEDWITHABORT = harness.$GETVALUEUNWRAPPINGREJECTEDWITHABORT;
Using AI Code Generation
1test(() => {2 const p = Promise.resolve();3 const p1 = p.then(() => {});4 assert_true(p1.isHandled);5}, 'Promise is handled after a call to then() on it');6test(() => {7 const p = Promise.resolve();8 p.then(() => {});9 assert_false(p.isHandled);10}, 'Promise is not handled after a call to then() on it');11test(() => {12 const p = Promise.resolve();13 p.then(() => {});14 assert_false(p.isHandled);15}, 'Promise is not handled after a call to then() on it');16test(() => {17 const p = Promise.resolve();18 p.then(() => {});19 assert_false(p.isHandled);20}, 'Promise is not handled after a call to then() on it');21test(() => {22 const p = Promise.resolve();23 p.then(() => {});24 assert_false(p.isHandled);25}, 'Promise is not handled after a call to then() on it');26test(() => {27 const p = Promise.resolve();28 p.then(() => {});29 assert_false(p.isHandled);30}, 'Promise is not handled after a call to then() on it');31test(() => {32 const p = Promise.resolve();33 p.then(() => {});34 assert_false(p.isHandled);35}, 'Promise is not handled after a call to then() on it');36test(() => {37 const p = Promise.resolve();38 p.then(() => {});39 assert_false(p.isHandled);40}, 'Promise is not handled after
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!