Best JavaScript code snippet using wpt
readable-stream.js
Source:readable-stream.js
...624 defaultReaderClosedPromiseReject(625 reader,626 new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness'));627 } else {628 defaultReaderClosedPromiseResetToRejected(629 reader,630 new TypeError('Reader was released and can no longer be used to monitor the stream\'s closedness'));631 }632 reader._closedPromise.catch(() => {});633 reader._ownerReadableStream._reader = undefined;634 reader._ownerReadableStream = undefined;635}636function ReadableStreamBYOBReaderRead(reader, view) {637 const stream = reader._ownerReadableStream;638 assert(stream !== undefined);639 stream._disturbed = true;640 if (stream._state === 'errored') {641 return Promise.reject(stream._storedError);642 }643 // Controllers must implement this.644 return ReadableByteStreamControllerPullInto(stream._readableStreamController, view);645}646function ReadableStreamDefaultReaderRead(reader) {647 const stream = reader._ownerReadableStream;648 assert(stream !== undefined);649 stream._disturbed = true;650 if (stream._state === 'closed') {651 return Promise.resolve(CreateIterResultObject(undefined, true));652 }653 if (stream._state === 'errored') {654 return Promise.reject(stream._storedError);655 }656 assert(stream._state === 'readable');657 return stream._readableStreamController[InternalPull]();658}659// Controllers660class ReadableStreamDefaultController {661 constructor(stream, underlyingSource, size, highWaterMark) {662 if (IsReadableStream(stream) === false) {663 throw new TypeError('ReadableStreamDefaultController can only be constructed with a ReadableStream instance');664 }665 if (stream._readableStreamController !== undefined) {666 throw new TypeError(667 'ReadableStreamDefaultController instances can only be created by the ReadableStream constructor');668 }669 this._controlledReadableStream = stream;670 this._underlyingSource = underlyingSource;671 this._queue = [];672 this._started = false;673 this._closeRequested = false;674 this._pullAgain = false;675 this._pulling = false;676 const normalizedStrategy = ValidateAndNormalizeQueuingStrategy(size, highWaterMark);677 this._strategySize = normalizedStrategy.size;678 this._strategyHWM = normalizedStrategy.highWaterMark;679 const controller = this;680 const startResult = InvokeOrNoop(underlyingSource, 'start', [this]);681 Promise.resolve(startResult).then(682 () => {683 controller._started = true;684 assert(controller._pulling === false);685 assert(controller._pullAgain === false);686 ReadableStreamDefaultControllerCallPullIfNeeded(controller);687 },688 r => {689 ReadableStreamDefaultControllerErrorIfNeeded(controller, r);690 }691 )692 .catch(rethrowAssertionErrorRejection);693 }694 get desiredSize() {695 if (IsReadableStreamDefaultController(this) === false) {696 throw defaultControllerBrandCheckException('desiredSize');697 }698 return ReadableStreamDefaultControllerGetDesiredSize(this);699 }700 close() {701 if (IsReadableStreamDefaultController(this) === false) {702 throw defaultControllerBrandCheckException('close');703 }704 if (this._closeRequested === true) {705 throw new TypeError('The stream has already been closed; do not close it again!');706 }707 const state = this._controlledReadableStream._state;708 if (state !== 'readable') {709 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);710 }711 ReadableStreamDefaultControllerClose(this);712 }713 enqueue(chunk) {714 if (IsReadableStreamDefaultController(this) === false) {715 throw defaultControllerBrandCheckException('enqueue');716 }717 if (this._closeRequested === true) {718 throw new TypeError('stream is closed or draining');719 }720 const state = this._controlledReadableStream._state;721 if (state !== 'readable') {722 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);723 }724 return ReadableStreamDefaultControllerEnqueue(this, chunk);725 }726 error(e) {727 if (IsReadableStreamDefaultController(this) === false) {728 throw defaultControllerBrandCheckException('error');729 }730 const stream = this._controlledReadableStream;731 if (stream._state !== 'readable') {732 throw new TypeError(`The stream is ${stream._state} and so cannot be errored`);733 }734 ReadableStreamDefaultControllerError(this, e);735 }736 [InternalCancel](reason) {737 this._queue = [];738 return PromiseInvokeOrNoop(this._underlyingSource, 'cancel', [reason]);739 }740 [InternalPull]() {741 const stream = this._controlledReadableStream;742 if (this._queue.length > 0) {743 const chunk = DequeueValue(this._queue);744 if (this._closeRequested === true && this._queue.length === 0) {745 ReadableStreamClose(stream);746 } else {747 ReadableStreamDefaultControllerCallPullIfNeeded(this);748 }749 return Promise.resolve(CreateIterResultObject(chunk, false));750 }751 const pendingPromise = ReadableStreamAddReadRequest(stream);752 ReadableStreamDefaultControllerCallPullIfNeeded(this);753 return pendingPromise;754 }755}756// Abstract operations for the ReadableStreamDefaultController.757function IsReadableStreamDefaultController(x) {758 if (!typeIsObject(x)) {759 return false;760 }761 if (!Object.prototype.hasOwnProperty.call(x, '_underlyingSource')) {762 return false;763 }764 return true;765}766function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {767 const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);768 if (shouldPull === false) {769 return undefined;770 }771 if (controller._pulling === true) {772 controller._pullAgain = true;773 return undefined;774 }775 assert(controller._pullAgain === false);776 controller._pulling = true;777 const pullPromise = PromiseInvokeOrNoop(controller._underlyingSource, 'pull', [controller]);778 pullPromise.then(779 () => {780 controller._pulling = false;781 if (controller._pullAgain === true) {782 controller._pullAgain = false;783 return ReadableStreamDefaultControllerCallPullIfNeeded(controller);784 }785 return undefined;786 },787 e => {788 ReadableStreamDefaultControllerErrorIfNeeded(controller, e);789 }790 )791 .catch(rethrowAssertionErrorRejection);792 return undefined;793}794function ReadableStreamDefaultControllerShouldCallPull(controller) {795 const stream = controller._controlledReadableStream;796 if (stream._state === 'closed' || stream._state === 'errored') {797 return false;798 }799 if (controller._closeRequested === true) {800 return false;801 }802 if (controller._started === false) {803 return false;804 }805 if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {806 return true;807 }808 const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);809 if (desiredSize > 0) {810 return true;811 }812 return false;813}814// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.815function ReadableStreamDefaultControllerClose(controller) {816 const stream = controller._controlledReadableStream;817 assert(controller._closeRequested === false);818 assert(stream._state === 'readable');819 controller._closeRequested = true;820 if (controller._queue.length === 0) {821 ReadableStreamClose(stream);822 }823}824function ReadableStreamDefaultControllerEnqueue(controller, chunk) {825 const stream = controller._controlledReadableStream;826 assert(controller._closeRequested === false);827 assert(stream._state === 'readable');828 if (IsReadableStreamLocked(stream) === true && ReadableStreamGetNumReadRequests(stream) > 0) {829 ReadableStreamFulfillReadRequest(stream, chunk, false);830 } else {831 let chunkSize = 1;832 if (controller._strategySize !== undefined) {833 const strategySize = controller._strategySize;834 try {835 chunkSize = strategySize(chunk);836 } catch (chunkSizeE) {837 ReadableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);838 throw chunkSizeE;839 }840 }841 try {842 EnqueueValueWithSize(controller._queue, chunk, chunkSize);843 } catch (enqueueE) {844 ReadableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);845 throw enqueueE;846 }847 }848 ReadableStreamDefaultControllerCallPullIfNeeded(controller);849 return undefined;850}851function ReadableStreamDefaultControllerError(controller, e) {852 const stream = controller._controlledReadableStream;853 assert(stream._state === 'readable');854 controller._queue = [];855 ReadableStreamError(stream, e);856}857function ReadableStreamDefaultControllerErrorIfNeeded(controller, e) {858 if (controller._controlledReadableStream._state === 'readable') {859 ReadableStreamDefaultControllerError(controller, e);860 }861}862function ReadableStreamDefaultControllerGetDesiredSize(controller) {863 const queueSize = GetTotalQueueSize(controller._queue);864 return controller._strategyHWM - queueSize;865}866class ReadableStreamBYOBRequest {867 constructor(controller, view) {868 this._associatedReadableByteStreamController = controller;869 this._view = view;870 }871 get view() {872 return this._view;873 }874 respond(bytesWritten) {875 if (IsReadableStreamBYOBRequest(this) === false) {876 throw byobRequestBrandCheckException('respond');877 }878 if (this._associatedReadableByteStreamController === undefined) {879 throw new TypeError('This BYOB request has been invalidated');880 }881 ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);882 }883 respondWithNewView(view) {884 if (IsReadableStreamBYOBRequest(this) === false) {885 throw byobRequestBrandCheckException('respond');886 }887 if (this._associatedReadableByteStreamController === undefined) {888 throw new TypeError('This BYOB request has been invalidated');889 }890 if (!ArrayBuffer.isView(view)) {891 throw new TypeError('You can only respond with array buffer views');892 }893 ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);894 }895}896class ReadableByteStreamController {897 constructor(stream, underlyingByteSource, highWaterMark) {898 if (IsReadableStream(stream) === false) {899 throw new TypeError('ReadableByteStreamController can only be constructed with a ReadableStream instance given ' +900 'a byte source');901 }902 if (stream._readableStreamController !== undefined) {903 throw new TypeError(904 'ReadableByteStreamController instances can only be created by the ReadableStream constructor given a byte ' +905 'source');906 }907 this._controlledReadableStream = stream;908 this._underlyingByteSource = underlyingByteSource;909 this._pullAgain = false;910 this._pulling = false;911 ReadableByteStreamControllerClearPendingPullIntos(this);912 this._queue = [];913 this._totalQueuedBytes = 0;914 this._closeRequested = false;915 this._started = false;916 this._strategyHWM = ValidateAndNormalizeHighWaterMark(highWaterMark);917 const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;918 if (autoAllocateChunkSize !== undefined) {919 if (Number.isInteger(autoAllocateChunkSize) === false || autoAllocateChunkSize <= 0) {920 throw new RangeError('autoAllocateChunkSize must be a positive integer');921 }922 }923 this._autoAllocateChunkSize = autoAllocateChunkSize;924 this._pendingPullIntos = [];925 const controller = this;926 const startResult = InvokeOrNoop(underlyingByteSource, 'start', [this]);927 Promise.resolve(startResult).then(928 () => {929 controller._started = true;930 assert(controller._pulling === false);931 assert(controller._pullAgain === false);932 ReadableByteStreamControllerCallPullIfNeeded(controller);933 },934 r => {935 if (stream._state === 'readable') {936 ReadableByteStreamControllerError(controller, r);937 }938 }939 )940 .catch(rethrowAssertionErrorRejection);941 }942 get byobRequest() {943 if (IsReadableByteStreamController(this) === false) {944 throw byteStreamControllerBrandCheckException('byobRequest');945 }946 if (this._byobRequest === undefined && this._pendingPullIntos.length > 0) {947 const firstDescriptor = this._pendingPullIntos[0];948 const view = new Uint8Array(firstDescriptor.buffer,949 firstDescriptor.byteOffset + firstDescriptor.bytesFilled,950 firstDescriptor.byteLength - firstDescriptor.bytesFilled);951 this._byobRequest = new ReadableStreamBYOBRequest(this, view);952 }953 return this._byobRequest;954 }955 get desiredSize() {956 if (IsReadableByteStreamController(this) === false) {957 throw byteStreamControllerBrandCheckException('desiredSize');958 }959 return ReadableByteStreamControllerGetDesiredSize(this);960 }961 close() {962 if (IsReadableByteStreamController(this) === false) {963 throw byteStreamControllerBrandCheckException('close');964 }965 if (this._closeRequested === true) {966 throw new TypeError('The stream has already been closed; do not close it again!');967 }968 const state = this._controlledReadableStream._state;969 if (state !== 'readable') {970 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);971 }972 ReadableByteStreamControllerClose(this);973 }974 enqueue(chunk) {975 if (IsReadableByteStreamController(this) === false) {976 throw byteStreamControllerBrandCheckException('enqueue');977 }978 if (this._closeRequested === true) {979 throw new TypeError('stream is closed or draining');980 }981 const state = this._controlledReadableStream._state;982 if (state !== 'readable') {983 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);984 }985 if (!ArrayBuffer.isView(chunk)) {986 throw new TypeError('You can only enqueue array buffer views when using a ReadableByteStreamController');987 }988 ReadableByteStreamControllerEnqueue(this, chunk);989 }990 error(e) {991 if (IsReadableByteStreamController(this) === false) {992 throw byteStreamControllerBrandCheckException('error');993 }994 const stream = this._controlledReadableStream;995 if (stream._state !== 'readable') {996 throw new TypeError(`The stream is ${stream._state} and so cannot be errored`);997 }998 ReadableByteStreamControllerError(this, e);999 }1000 [InternalCancel](reason) {1001 if (this._pendingPullIntos.length > 0) {1002 const firstDescriptor = this._pendingPullIntos[0];1003 firstDescriptor.bytesFilled = 0;1004 }1005 this._queue = [];1006 this._totalQueuedBytes = 0;1007 return PromiseInvokeOrNoop(this._underlyingByteSource, 'cancel', [reason]);1008 }1009 [InternalPull]() {1010 const stream = this._controlledReadableStream;1011 assert(ReadableStreamHasDefaultReader(stream) === true);1012 if (this._totalQueuedBytes > 0) {1013 assert(ReadableStreamGetNumReadRequests(stream) === 0);1014 const entry = this._queue.shift();1015 this._totalQueuedBytes -= entry.byteLength;1016 ReadableByteStreamControllerHandleQueueDrain(this);1017 let view;1018 try {1019 view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);1020 } catch (viewE) {1021 return Promise.reject(viewE);1022 }1023 return Promise.resolve(CreateIterResultObject(view, false));1024 }1025 const autoAllocateChunkSize = this._autoAllocateChunkSize;1026 if (autoAllocateChunkSize !== undefined) {1027 let buffer;1028 try {1029 buffer = new ArrayBuffer(autoAllocateChunkSize);1030 } catch (bufferE) {1031 return Promise.reject(bufferE);1032 }1033 const pullIntoDescriptor = {1034 buffer,1035 byteOffset: 0,1036 byteLength: autoAllocateChunkSize,1037 bytesFilled: 0,1038 elementSize: 1,1039 ctor: Uint8Array,1040 readerType: 'default'1041 };1042 this._pendingPullIntos.push(pullIntoDescriptor);1043 }1044 const promise = ReadableStreamAddReadRequest(stream);1045 ReadableByteStreamControllerCallPullIfNeeded(this);1046 return promise;1047 }1048}1049// Abstract operations for the ReadableByteStreamController.1050function IsReadableByteStreamController(x) {1051 if (!typeIsObject(x)) {1052 return false;1053 }1054 if (!Object.prototype.hasOwnProperty.call(x, '_underlyingByteSource')) {1055 return false;1056 }1057 return true;1058}1059function IsReadableStreamBYOBRequest(x) {1060 if (!typeIsObject(x)) {1061 return false;1062 }1063 if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {1064 return false;1065 }1066 return true;1067}1068function ReadableByteStreamControllerCallPullIfNeeded(controller) {1069 const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);1070 if (shouldPull === false) {1071 return undefined;1072 }1073 if (controller._pulling === true) {1074 controller._pullAgain = true;1075 return undefined;1076 }1077 assert(controller._pullAgain === false);1078 controller._pulling = true;1079 // TODO: Test controller argument1080 const pullPromise = PromiseInvokeOrNoop(controller._underlyingByteSource, 'pull', [controller]);1081 pullPromise.then(1082 () => {1083 controller._pulling = false;1084 if (controller._pullAgain === true) {1085 controller._pullAgain = false;1086 ReadableByteStreamControllerCallPullIfNeeded(controller);1087 }1088 },1089 e => {1090 if (controller._controlledReadableStream._state === 'readable') {1091 ReadableByteStreamControllerError(controller, e);1092 }1093 }1094 )1095 .catch(rethrowAssertionErrorRejection);1096 return undefined;1097}1098function ReadableByteStreamControllerClearPendingPullIntos(controller) {1099 ReadableByteStreamControllerInvalidateBYOBRequest(controller);1100 controller._pendingPullIntos = [];1101}1102function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {1103 assert(stream._state !== 'errored', 'state must not be errored');1104 let done = false;1105 if (stream._state === 'closed') {1106 assert(pullIntoDescriptor.bytesFilled === 0);1107 done = true;1108 }1109 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);1110 if (pullIntoDescriptor.readerType === 'default') {1111 ReadableStreamFulfillReadRequest(stream, filledView, done);1112 } else {1113 assert(pullIntoDescriptor.readerType === 'byob');1114 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);1115 }1116}1117function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {1118 const bytesFilled = pullIntoDescriptor.bytesFilled;1119 const elementSize = pullIntoDescriptor.elementSize;1120 assert(bytesFilled <= pullIntoDescriptor.byteLength);1121 assert(bytesFilled % elementSize === 0);1122 return new pullIntoDescriptor.ctor(1123 pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);1124}1125function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {1126 controller._queue.push({ buffer, byteOffset, byteLength });1127 controller._totalQueuedBytes += byteLength;1128}1129function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {1130 const elementSize = pullIntoDescriptor.elementSize;1131 const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;1132 const maxBytesToCopy = Math.min(controller._totalQueuedBytes,1133 pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);1134 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;1135 const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;1136 let totalBytesToCopyRemaining = maxBytesToCopy;1137 let ready = false;1138 if (maxAlignedBytes > currentAlignedBytes) {1139 totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;1140 ready = true;1141 }1142 const queue = controller._queue;1143 while (totalBytesToCopyRemaining > 0) {1144 const headOfQueue = queue[0];1145 const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);1146 const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;1147 ArrayBufferCopy(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);1148 if (headOfQueue.byteLength === bytesToCopy) {1149 queue.shift();1150 } else {1151 headOfQueue.byteOffset += bytesToCopy;1152 headOfQueue.byteLength -= bytesToCopy;1153 }1154 controller._totalQueuedBytes -= bytesToCopy;1155 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);1156 totalBytesToCopyRemaining -= bytesToCopy;1157 }1158 if (ready === false) {1159 assert(controller._totalQueuedBytes === 0, 'queue must be empty');1160 assert(pullIntoDescriptor.bytesFilled > 0);1161 assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize);1162 }1163 return ready;1164}1165function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {1166 assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos[0] === pullIntoDescriptor);1167 ReadableByteStreamControllerInvalidateBYOBRequest(controller);1168 pullIntoDescriptor.bytesFilled += size;1169}1170function ReadableByteStreamControllerHandleQueueDrain(controller) {1171 assert(controller._controlledReadableStream._state === 'readable');1172 if (controller._totalQueuedBytes === 0 && controller._closeRequested === true) {1173 ReadableStreamClose(controller._controlledReadableStream);1174 } else {1175 ReadableByteStreamControllerCallPullIfNeeded(controller);1176 }1177}1178function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {1179 if (controller._byobRequest === undefined) {1180 return;1181 }1182 controller._byobRequest._associatedReadableByteStreamController = undefined;1183 controller._byobRequest._view = undefined;1184 controller._byobRequest = undefined;1185}1186function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {1187 assert(controller._closeRequested === false);1188 while (controller._pendingPullIntos.length > 0) {1189 if (controller._totalQueuedBytes === 0) {1190 return;1191 }1192 const pullIntoDescriptor = controller._pendingPullIntos[0];1193 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {1194 ReadableByteStreamControllerShiftPendingPullInto(controller);1195 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor);1196 }1197 }1198}1199function ReadableByteStreamControllerPullInto(controller, view) {1200 const stream = controller._controlledReadableStream;1201 let elementSize = 1;1202 if (view.constructor !== DataView) {1203 elementSize = view.constructor.BYTES_PER_ELEMENT;1204 }1205 const ctor = view.constructor;1206 const pullIntoDescriptor = {1207 buffer: view.buffer,1208 byteOffset: view.byteOffset,1209 byteLength: view.byteLength,1210 bytesFilled: 0,1211 elementSize,1212 ctor,1213 readerType: 'byob'1214 };1215 if (controller._pendingPullIntos.length > 0) {1216 pullIntoDescriptor.buffer = SameRealmTransfer(pullIntoDescriptor.buffer);1217 controller._pendingPullIntos.push(pullIntoDescriptor);1218 // No ReadableByteStreamControllerCallPullIfNeeded() call since:1219 // - No change happens on desiredSize1220 // - The source has already been notified of that there's at least 1 pending read(view)1221 return ReadableStreamAddReadIntoRequest(stream);1222 }1223 if (stream._state === 'closed') {1224 const emptyView = new view.constructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);1225 return Promise.resolve(CreateIterResultObject(emptyView, true));1226 }1227 if (controller._totalQueuedBytes > 0) {1228 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) === true) {1229 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);1230 ReadableByteStreamControllerHandleQueueDrain(controller);1231 return Promise.resolve(CreateIterResultObject(filledView, false));1232 }1233 if (controller._closeRequested === true) {1234 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');1235 ReadableByteStreamControllerError(controller, e);1236 return Promise.reject(e);1237 }1238 }1239 pullIntoDescriptor.buffer = SameRealmTransfer(pullIntoDescriptor.buffer);1240 controller._pendingPullIntos.push(pullIntoDescriptor);1241 const promise = ReadableStreamAddReadIntoRequest(stream);1242 ReadableByteStreamControllerCallPullIfNeeded(controller);1243 return promise;1244}1245function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {1246 firstDescriptor.buffer = SameRealmTransfer(firstDescriptor.buffer);1247 assert(firstDescriptor.bytesFilled === 0, 'bytesFilled must be 0');1248 const stream = controller._controlledReadableStream;1249 while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {1250 const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);1251 ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);1252 }1253}1254function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {1255 if (pullIntoDescriptor.bytesFilled + bytesWritten > pullIntoDescriptor.byteLength) {1256 throw new RangeError('bytesWritten out of range');1257 }1258 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);1259 if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {1260 // TODO: Figure out whether we should detach the buffer or not here.1261 return;1262 }1263 ReadableByteStreamControllerShiftPendingPullInto(controller);1264 const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;1265 if (remainderSize > 0) {1266 const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;1267 const remainder = pullIntoDescriptor.buffer.slice(end - remainderSize, end);1268 ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);1269 }1270 pullIntoDescriptor.buffer = SameRealmTransfer(pullIntoDescriptor.buffer);1271 pullIntoDescriptor.bytesFilled -= remainderSize;1272 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableStream, pullIntoDescriptor);1273 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);1274}1275function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {1276 const firstDescriptor = controller._pendingPullIntos[0];1277 const stream = controller._controlledReadableStream;1278 if (stream._state === 'closed') {1279 if (bytesWritten !== 0) {1280 throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');1281 }1282 ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);1283 } else {1284 assert(stream._state === 'readable');1285 ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);1286 }1287}1288function ReadableByteStreamControllerShiftPendingPullInto(controller) {1289 const descriptor = controller._pendingPullIntos.shift();1290 ReadableByteStreamControllerInvalidateBYOBRequest(controller);1291 return descriptor;1292}1293function ReadableByteStreamControllerShouldCallPull(controller) {1294 const stream = controller._controlledReadableStream;1295 if (stream._state !== 'readable') {1296 return false;1297 }1298 if (controller._closeRequested === true) {1299 return false;1300 }1301 if (controller._started === false) {1302 return false;1303 }1304 if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {1305 return true;1306 }1307 if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {1308 return true;1309 }1310 if (ReadableByteStreamControllerGetDesiredSize(controller) > 0) {1311 return true;1312 }1313 return false;1314}1315// A client of ReadableByteStreamController may use these functions directly to bypass state check.1316function ReadableByteStreamControllerClose(controller) {1317 const stream = controller._controlledReadableStream;1318 assert(controller._closeRequested === false);1319 assert(stream._state === 'readable');1320 if (controller._totalQueuedBytes > 0) {1321 controller._closeRequested = true;1322 return;1323 }1324 if (controller._pendingPullIntos.length > 0) {1325 const firstPendingPullInto = controller._pendingPullIntos[0];1326 if (firstPendingPullInto.bytesFilled > 0) {1327 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');1328 ReadableByteStreamControllerError(controller, e);1329 throw e;1330 }1331 }1332 ReadableStreamClose(stream);1333}1334function ReadableByteStreamControllerEnqueue(controller, chunk) {1335 const stream = controller._controlledReadableStream;1336 assert(controller._closeRequested === false);1337 assert(stream._state === 'readable');1338 const buffer = chunk.buffer;1339 const byteOffset = chunk.byteOffset;1340 const byteLength = chunk.byteLength;1341 const transferredBuffer = SameRealmTransfer(buffer);1342 if (ReadableStreamHasDefaultReader(stream) === true) {1343 if (ReadableStreamGetNumReadRequests(stream) === 0) {1344 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);1345 } else {1346 assert(controller._queue.length === 0);1347 const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);1348 ReadableStreamFulfillReadRequest(stream, transferredView, false);1349 }1350 } else if (ReadableStreamHasBYOBReader(stream) === true) {1351 // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.1352 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);1353 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);1354 } else {1355 assert(IsReadableStreamLocked(stream) === false, 'stream must not be locked');1356 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);1357 }1358}1359function ReadableByteStreamControllerError(controller, e) {1360 const stream = controller._controlledReadableStream;1361 assert(stream._state === 'readable');1362 ReadableByteStreamControllerClearPendingPullIntos(controller);1363 controller._queue = [];1364 ReadableStreamError(stream, e);1365}1366function ReadableByteStreamControllerGetDesiredSize(controller) {1367 return controller._strategyHWM - controller._totalQueuedBytes;1368}1369function ReadableByteStreamControllerRespond(controller, bytesWritten) {1370 bytesWritten = Number(bytesWritten);1371 if (IsFiniteNonNegativeNumber(bytesWritten) === false) {1372 throw new RangeError('bytesWritten must be a finite');1373 }1374 assert(controller._pendingPullIntos.length > 0);1375 ReadableByteStreamControllerRespondInternal(controller, bytesWritten);1376}1377function ReadableByteStreamControllerRespondWithNewView(controller, view) {1378 assert(controller._pendingPullIntos.length > 0);1379 const firstDescriptor = controller._pendingPullIntos[0];1380 if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {1381 throw new RangeError('The region specified by view does not match byobRequest');1382 }1383 if (firstDescriptor.byteLength !== view.byteLength) {1384 throw new RangeError('The buffer of view has different capacity than byobRequest');1385 }1386 firstDescriptor.buffer = view.buffer;1387 ReadableByteStreamControllerRespondInternal(controller, view.byteLength);1388}1389// Helper functions for the ReadableStream.1390function streamBrandCheckException(name) {1391 return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);1392}1393// Helper functions for the readers.1394function readerLockException(name) {1395 return new TypeError('Cannot ' + name + ' a stream using a released reader');1396}1397// Helper functions for the ReadableStreamDefaultReader.1398function defaultReaderBrandCheckException(name) {1399 return new TypeError(1400 `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);1401}1402function defaultReaderClosedPromiseInitialize(reader) {1403 reader._closedPromise = new Promise((resolve, reject) => {1404 reader._closedPromise_resolve = resolve;1405 reader._closedPromise_reject = reject;1406 });1407}1408function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {1409 reader._closedPromise = Promise.reject(reason);1410 reader._closedPromise_resolve = undefined;1411 reader._closedPromise_reject = undefined;1412}1413function defaultReaderClosedPromiseInitializeAsResolved(reader) {1414 reader._closedPromise = Promise.resolve(undefined);1415 reader._closedPromise_resolve = undefined;1416 reader._closedPromise_reject = undefined;1417}1418function defaultReaderClosedPromiseReject(reader, reason) {1419 assert(reader._closedPromise_resolve !== undefined);1420 assert(reader._closedPromise_reject !== undefined);1421 reader._closedPromise_reject(reason);1422 reader._closedPromise_resolve = undefined;1423 reader._closedPromise_reject = undefined;1424}1425function defaultReaderClosedPromiseResetToRejected(reader, reason) {1426 assert(reader._closedPromise_resolve === undefined);1427 assert(reader._closedPromise_reject === undefined);1428 reader._closedPromise = Promise.reject(reason);1429}1430function defaultReaderClosedPromiseResolve(reader) {1431 assert(reader._closedPromise_resolve !== undefined);1432 assert(reader._closedPromise_reject !== undefined);1433 reader._closedPromise_resolve(undefined);1434 reader._closedPromise_resolve = undefined;1435 reader._closedPromise_reject = undefined;1436}1437// Helper functions for the ReadableStreamDefaultReader.1438function byobReaderBrandCheckException(name) {1439 return new TypeError(...
generic-reader.ts
Source:generic-reader.ts
...27 defaultReaderClosedPromiseReject(28 reader,29 new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));30 } else {31 defaultReaderClosedPromiseResetToRejected(32 reader,33 new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));34 }35 reader._ownerReadableStream._reader = undefined;36 reader._ownerReadableStream = undefined!;37}38// Helper functions for the readers.39export function readerLockException(name: string): TypeError {40 return new TypeError('Cannot ' + name + ' a stream using a released reader');41}42// Helper functions for the ReadableStreamDefaultReader.43export function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader<any>) {44 reader._closedPromise = newPromise((resolve, reject) => {45 reader._closedPromise_resolve = resolve;46 reader._closedPromise_reject = reject;47 });48}49export function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader<any>, reason: any) {50 defaultReaderClosedPromiseInitialize(reader);51 defaultReaderClosedPromiseReject(reader, reason);52}53export function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader<any>) {54 defaultReaderClosedPromiseInitialize(reader);55 defaultReaderClosedPromiseResolve(reader);56}57export function defaultReaderClosedPromiseReject(reader: ReadableStreamReader<any>, reason: any) {58 assert(reader._closedPromise_resolve !== undefined);59 assert(reader._closedPromise_reject !== undefined);60 setPromiseIsHandledToTrue(reader._closedPromise);61 reader._closedPromise_reject!(reason);62 reader._closedPromise_resolve = undefined;63 reader._closedPromise_reject = undefined;64}65export function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader<any>, reason: any) {66 assert(reader._closedPromise_resolve === undefined);67 assert(reader._closedPromise_reject === undefined);68 defaultReaderClosedPromiseInitializeAsRejected(reader, reason);69}70export function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader<any>) {71 assert(reader._closedPromise_resolve !== undefined);72 assert(reader._closedPromise_reject !== undefined);73 reader._closedPromise_resolve!(undefined);74 reader._closedPromise_resolve = undefined;75 reader._closedPromise_reject = undefined;...
Using AI Code Generation
1self.defaultReaderClosedPromiseResetToRejected();2self.defaultWriterClosedPromiseResetToRejected();3self.defaultWriterReadyPromiseResetToRejected();4self.defaultWriterReadyPromiseResetToRejectedWithException('Exception');5self.error1();6self.error2();7self.error3();8self.error4();9self.error5();10self.error6();11self.error7();12self.error8();13self.error9();14self.error10();15self.error11();16self.error12();17self.error13();18self.error14();19self.error15();20self.error16();21self.error17();22self.error18();23self.error19();24self.error20();25self.error21();26self.error22();27self.error23();28self.error24();29self.error25();30self.error26();31self.error27();
Using AI Code Generation
1const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;2const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;3const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;4const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;5const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;6const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;7const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;8const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;9const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;10const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;11const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;12const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;13const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;
Using AI Code Generation
1var defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;2var rs = new ReadableStream({3 start(controller) {4 controller.enqueue('a');5 controller.close();6 }7});8var reader = rs.getReader();9reader.read().then(result => {10 assert_equals(result.value, 'a');11 assert_true(result.done);12 return defaultReaderClosedPromiseResetToRejected(reader, new Error('oops'));13}).then(() => {14 return reader.read();15}).then(result => {16 assert_equals(result.value, undefined);17 assert_true(result.done);18}).catch(e => {19 assert_unreached(e);20});21var defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;22var rs = new ReadableStream({23 start(controller) {24 controller.enqueue('a');25 controller.close();26 }27});28var reader = rs.getReader();29reader.read().then(result => {30 assert_equals(result.value, 'a');31 assert_true(result.done);32 return defaultReaderClosedPromiseResetToRejected(reader, new Error('oops'));33}).then(() => {34 return reader.read();35}).then(result => {36 assert_equals(result.value, undefined);37 assert_true(result.done);38}).catch(e => {39 assert_unreached(e);40});41var defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;42var rs = new ReadableStream({43 start(controller) {44 controller.enqueue('a');45 controller.close();46 }47});48var reader = rs.getReader();49reader.read().then(result => {50 assert_equals(result.value, 'a');51 assert_true(result.done);52 return defaultReaderClosedPromiseResetToRejected(reader, new Error('oops'));53}).then(() => {54 return reader.read();55}).then(result => {56 assert_equals(result.value, undefined);57 assert_true(result.done);58}).catch(e => {59 assert_unreached(e);60});61var defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;62var rs = new ReadableStream({63 start(controller) {64 controller.enqueue('
Using AI Code Generation
1const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;2const readableStream = new ReadableStream();3const reader = readableStream.getReader();4defaultReaderClosedPromiseResetToRejected(reader);5const closedPromise = reader.closed;6assert_equals(closedPromise.constructor.name, 'Promise');7assert_equals(closedPromise._state, 'rejected');8assert_equals(closedPromise._result.constructor.name, 'TypeError');9assert_equals(closedPromise._result.message, 'closed promise is already rejected');10done();
Using AI Code Generation
1test(() => {2 const ws = new WritableStream({3 write() {4 return new Promise(resolve => {5 setTimeout(resolve, 1000);6 });7 }8 });9 const writer = ws.getWriter();10 const writePromise = writer.write('a');11 writer.releaseLock();12 return writePromise.then(() => {13 return promise_rejects(t, new TypeError(), ws.abort());14 });15}, 'abort() rejects if the stream is errored and there is a pending write()');16test(() => {17 const ws = new WritableStream();18 const writer = ws.getWriter();19 writer.releaseLock();20 return promise_rejects(t, new TypeError(), ws.abort());21}, 'abort() rejects if the stream is errored and there is a pending write()');22test(() => {23 const ws = new WritableStream();24 const writer = ws.getWriter();25 writer.releaseLock();26 return promise_rejects(t, new TypeError(), ws.abort());27}, 'abort() rejects if the stream is errored and there is a pending write()');28test(() => {29 const ws = new WritableStream();30 const writer = ws.getWriter();31 writer.releaseLock();32 return promise_rejects(t, new TypeError(), ws.abort());33}, 'abort() rejects if the stream is errored and there is a pending write()');34test(() => {35 const ws = new WritableStream();36 const writer = ws.getWriter();37 writer.releaseLock();38 return promise_rejects(t, new TypeError(), ws.abort());39}, 'abort() rejects if the stream is errored and there is a pending write()');40test(() => {41 const ws = new WritableStream();42 const writer = ws.getWriter();43 writer.releaseLock();44 return promise_rejects(t, new TypeError(), ws.abort());45}, 'abort() rejects if the stream is errored and there is
Using AI Code Generation
1promise_test(async t => {2 const stream = new ReadableStream({3 start(controller) {4 controller.close();5 }6 });7 const reader = stream.getReader();8 await reader.closed;9 const defaultReaderClosedPromiseResetToRejected = reader.closed.catch(() => {});10 await defaultReaderClosedPromiseResetToRejected;11}, 'Test defaultReaderClosedPromiseResetToRejected method of wpt');12Uncaught (in promise) TypeError: Cannot read property 'catch' of undefined13> readonly attribute ReadableStreamDefaultReader? locked;14> readonly attribute ReadableStreamDefaultReader? locked;15> readonly attribute ReadableStreamDefaultReader? locked;
Using AI Code Generation
1var defaultReaderClosedPromiseResetToRejected = new Promise(function(resolve, reject) {2 var rs = new ReadableStream({3 start(controller) {4 controller.enqueue('a');5 }6 });7 var reader = rs.getReader();8 reader.read().then(result => {9 assert(result.value === 'a');10 assert(result.done === false);11 reader.releaseLock();12 });13 reader.closed.then(() => {14 assert(false, 'closed should not be fulfilled');15 }, () => {16 assert(true, 'closed should be rejected');17 });18 reader.cancel();19});20promise_test(() => defaultReaderClosedPromiseResetToRejected, 'defaultReaderClosedPromiseResetToRejected');21var defaultReaderClosedPromiseResetToRejected = new Promise(function(resolve, reject) {22 var rs = new ReadableStream({23 start(controller) {24 controller.enqueue('a');25 }26 });27 var reader = rs.getReader();28 reader.read().then(result => {29 assert(result.value === 'a');30 assert(result.done === false);31 reader.releaseLock();32 });33 reader.closed.then(() => {34 assert(false, 'closed should not be fulfilled');35 }, () => {36 assert(true, 'closed should be rejected');37 });38 reader.cancel();39});40promise_test(() => defaultReaderClosedPromiseResetToRejected, 'defaultReaderClosedPromiseResetToRejected');41var defaultReaderClosedPromiseResetToRejected = new Promise(function(resolve, reject) {42 var rs = new ReadableStream({43 start(controller) {44 controller.enqueue('a');45 }46 });47 var reader = rs.getReader();48 reader.read().then(result => {49 assert(result.value === 'a');50 assert(result.done === false);51 reader.releaseLock();52 });53 reader.closed.then(() => {54 assert(false, 'closed should not be fulfilled');55 }, () => {56 assert(true, 'closed should be rejected');57 });58 reader.cancel();59});60promise_test(() => defaultReaderClosedPromiseResetToRejected, 'defaultReaderClosedPromiseResetToRejected');
Using AI Code Generation
1const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;2const reader = new ReadableStream().getReader();3const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;4const readableStream = new ReadableStream({5 start(c) {6 c.enqueue('a');7 c.close();8 }9});10const reader = readableStream.getReader();11const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;12const readableStream = new ReadableStream({13 start(c) {14 c.enqueue('a');15 c.error('e');16 }17});18const reader = readableStream.getReader();19const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;20const readableStream = new ReadableStream({21 start(c) {22 c.enqueue('a');23 c.error('e');24 }25});26const reader = readableStream.getReader();27reader.closed.then(() => console.log('closed'));28const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;29const readableStream = new ReadableStream({30 start(c) {31 c.enqueue('a');32 c.close();33 }34});35const reader = readableStream.getReader();36reader.closed.then(() => console.log('closed'));37const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;38const readableStream = new ReadableStream({39 start(c) {40 c.enqueue('a');41 c.close();42 }43});44const reader = readableStream.getReader();45reader.closed.then(() => console.log('closed'));46const defaultReaderClosedPromiseResetToRejected = wpt.defaultReaderClosedPromiseResetToRejected;47const readableStream = new ReadableStream({48 start(c) {49 c.enqueue('a');50 c.close();51 }52});
Using AI Code Generation
1import {defaultReaderClosedPromiseResetToRejected} from2'./resources/test-utils.js';3promise_test(async t => {4 const rs = new ReadableStream({5 start(c) {6 c.enqueue('a');7 c.close();8 }9 });10 const reader = rs.getReader();11 assert_equals(reader.closed, defaultReaderClosedPromiseResetToRejected);12 const result = await reader.read();13 assert_equals(result.value, 'a');14 assert_true(result.done);15}, 'ReadableStream with byte source: getReader().closed should be a rejected16promise');
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!!