Best JavaScript code snippet using wpt
writable-stream.ts
Source:writable-stream.ts
...348 stream._closeRequest = undefined;349 }350 const writer = stream._writer;351 if (writer !== undefined) {352 defaultWriterClosedPromiseReject(writer, stream._storedError);353 }354}355function WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {356 assert(stream._state === 'writable');357 assert(WritableStreamCloseQueuedOrInFlight(stream) === false);358 const writer = stream._writer;359 if (writer !== undefined && backpressure !== stream._backpressure) {360 if (backpressure === true) {361 defaultWriterReadyPromiseReset(writer);362 } else {363 assert(backpressure === false);364 defaultWriterReadyPromiseResolve(writer);365 }366 }367 stream._backpressure = backpressure;368}369export type WritableStreamDefaultWriterType<W> = WritableStreamDefaultWriter<W>;370class WritableStreamDefaultWriter<W> {371 /** @internal */372 _ownerWritableStream: WritableStream<W>;373 /** @internal */374 _closedPromise!: Promise<void>;375 /** @internal */376 _closedPromise_resolve?: (value?: undefined) => void;377 /** @internal */378 _closedPromise_reject?: (reason: any) => void;379 /** @internal */380 _closedPromiseState!: 'pending' | 'resolved' | 'rejected';381 /** @internal */382 _readyPromise!: Promise<void>;383 /** @internal */384 _readyPromise_resolve?: (value?: undefined) => void;385 /** @internal */386 _readyPromise_reject?: (reason: any) => void;387 /** @internal */388 _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';389 constructor(stream: WritableStream<W>) {390 if (IsWritableStream(stream) === false) {391 throw new TypeError('WritableStreamDefaultWriter can only be constructed with a WritableStream instance');392 }393 if (IsWritableStreamLocked(stream) === true) {394 throw new TypeError('This stream has already been locked for exclusive writing by another writer');395 }396 this._ownerWritableStream = stream;397 stream._writer = this;398 const state = stream._state;399 if (state === 'writable') {400 if (WritableStreamCloseQueuedOrInFlight(stream) === false && stream._backpressure === true) {401 defaultWriterReadyPromiseInitialize(this);402 } else {403 defaultWriterReadyPromiseInitializeAsResolved(this);404 }405 defaultWriterClosedPromiseInitialize(this);406 } else if (state === 'erroring') {407 defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);408 defaultWriterClosedPromiseInitialize(this);409 } else if (state === 'closed') {410 defaultWriterReadyPromiseInitializeAsResolved(this);411 defaultWriterClosedPromiseInitializeAsResolved(this);412 } else {413 assert(state === 'errored');414 const storedError = stream._storedError;415 defaultWriterReadyPromiseInitializeAsRejected(this, storedError);416 defaultWriterClosedPromiseInitializeAsRejected(this, storedError);417 }418 }419 get closed(): Promise<void> {420 if (IsWritableStreamDefaultWriter(this) === false) {421 return Promise.reject(defaultWriterBrandCheckException('closed'));422 }423 return this._closedPromise;424 }425 get desiredSize(): number | null {426 if (IsWritableStreamDefaultWriter(this) === false) {427 throw defaultWriterBrandCheckException('desiredSize');428 }429 if (this._ownerWritableStream === undefined) {430 throw defaultWriterLockException('desiredSize');431 }432 return WritableStreamDefaultWriterGetDesiredSize(this);433 }434 get ready(): Promise<void> {435 if (IsWritableStreamDefaultWriter(this) === false) {436 return Promise.reject(defaultWriterBrandCheckException('ready'));437 }438 return this._readyPromise;439 }440 abort(reason: any): Promise<void> {441 if (IsWritableStreamDefaultWriter(this) === false) {442 return Promise.reject(defaultWriterBrandCheckException('abort'));443 }444 if (this._ownerWritableStream === undefined) {445 return Promise.reject(defaultWriterLockException('abort'));446 }447 return WritableStreamDefaultWriterAbort(this, reason);448 }449 close(): Promise<void> {450 if (IsWritableStreamDefaultWriter(this) === false) {451 return Promise.reject(defaultWriterBrandCheckException('close'));452 }453 const stream = this._ownerWritableStream;454 if (stream === undefined) {455 return Promise.reject(defaultWriterLockException('close'));456 }457 if (WritableStreamCloseQueuedOrInFlight(stream) === true) {458 return Promise.reject(new TypeError('cannot close an already-closing stream'));459 }460 return WritableStreamDefaultWriterClose(this);461 }462 releaseLock(): void {463 if (IsWritableStreamDefaultWriter(this) === false) {464 throw defaultWriterBrandCheckException('releaseLock');465 }466 const stream = this._ownerWritableStream;467 if (stream === undefined) {468 return;469 }470 assert(stream._writer !== undefined);471 WritableStreamDefaultWriterRelease(this);472 }473 write(chunk: W): Promise<void> {474 if (IsWritableStreamDefaultWriter(this) === false) {475 return Promise.reject(defaultWriterBrandCheckException('write'));476 }477 if (this._ownerWritableStream === undefined) {478 return Promise.reject(defaultWriterLockException('write to'));479 }480 return WritableStreamDefaultWriterWrite(this, chunk);481 }482}483// Abstract operations for the WritableStreamDefaultWriter.484function IsWritableStreamDefaultWriter<W>(x: any): x is WritableStreamDefaultWriter<W> {485 if (!typeIsObject(x)) {486 return false;487 }488 if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {489 return false;490 }491 return true;492}493// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.494function WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter<any>, reason: any) {495 const stream = writer._ownerWritableStream;496 assert(stream !== undefined);497 return WritableStreamAbort(stream, reason);498}499function WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter<any>): Promise<void> {500 const stream = writer._ownerWritableStream;501 assert(stream !== undefined);502 const state = stream._state;503 if (state === 'closed' || state === 'errored') {504 return Promise.reject(new TypeError(505 `The stream (in ${state} state) is not in the writable state and cannot be closed`));506 }507 assert(state === 'writable' || state === 'erroring');508 assert(WritableStreamCloseQueuedOrInFlight(stream) === false);509 const promise = new Promise<void>((resolve, reject) => {510 const closeRequest: CloseRequest = {511 _resolve: resolve,512 _reject: reject513 };514 stream._closeRequest = closeRequest;515 });516 if (stream._backpressure === true && state === 'writable') {517 defaultWriterReadyPromiseResolve(writer);518 }519 WritableStreamDefaultControllerClose(stream._writableStreamController);520 return promise;521}522function WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter<any>): Promise<void> {523 const stream = writer._ownerWritableStream;524 assert(stream !== undefined);525 const state = stream._state;526 if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') {527 return Promise.resolve();528 }529 if (state === 'errored') {530 return Promise.reject(stream._storedError);531 }532 assert(state === 'writable' || state === 'erroring');533 return WritableStreamDefaultWriterClose(writer);534}535function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter<any>, error: any) {536 if (writer._closedPromiseState === 'pending') {537 defaultWriterClosedPromiseReject(writer, error);538 } else {539 defaultWriterClosedPromiseResetToRejected(writer, error);540 }541}542function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter<any>, error: any) {543 if (writer._readyPromiseState === 'pending') {544 defaultWriterReadyPromiseReject(writer, error);545 } else {546 defaultWriterReadyPromiseResetToRejected(writer, error);547 }548}549function WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter<any>): number | null {550 const stream = writer._ownerWritableStream;551 const state = stream._state;552 if (state === 'errored' || state === 'erroring') {553 return null;554 }555 if (state === 'closed') {556 return 0;557 }558 return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);559}560function WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter<any>) {561 const stream = writer._ownerWritableStream;562 assert(stream !== undefined);563 assert(stream._writer === writer);564 const releasedError = new TypeError(565 'Writer was released and can no longer be used to monitor the stream\'s closedness');566 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);567 // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not568 // rejected until afterwards. This means that simply testing state will not work.569 WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);570 stream._writer = undefined;571 writer._ownerWritableStream = undefined!;572}573function WritableStreamDefaultWriterWrite<W>(writer: WritableStreamDefaultWriter<W>, chunk: W): Promise<void> {574 const stream = writer._ownerWritableStream;575 assert(stream !== undefined);576 const controller = stream._writableStreamController;577 const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);578 if (stream !== writer._ownerWritableStream) {579 return Promise.reject(defaultWriterLockException('write to'));580 }581 const state = stream._state;582 if (state === 'errored') {583 return Promise.reject(stream._storedError);584 }585 if (WritableStreamCloseQueuedOrInFlight(stream) === true || state === 'closed') {586 return Promise.reject(new TypeError('The stream is closing or closed and cannot be written to'));587 }588 if (state === 'erroring') {589 return Promise.reject(stream._storedError);590 }591 assert(state === 'writable');592 const promise = WritableStreamAddWriteRequest(stream);593 WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);594 return promise;595}596interface WriteRecord<W> {597 chunk: W;598}599type QueueRecord<W> = WriteRecord<W> | 'close';600export type WritableStreamDefaultControllerType = WritableStreamDefaultController<any>;601class WritableStreamDefaultController<W = any> {602 /** @internal */603 _controlledWritableStream!: WritableStream<W>;604 /** @internal */605 _queue!: SimpleQueue<QueuePair<QueueRecord<W>>>;606 /** @internal */607 _queueTotalSize!: number;608 /** @internal */609 _started!: boolean;610 /** @internal */611 _strategySizeAlgorithm!: QueuingStrategySizeCallback<W>;612 /** @internal */613 _strategyHWM!: number;614 /** @internal */615 _writeAlgorithm!: (chunk: W) => Promise<void>;616 /** @internal */617 _closeAlgorithm!: () => Promise<void>;618 /** @internal */619 _abortAlgorithm!: (reason: any) => Promise<void>;620 /** @internal */621 constructor() {622 throw new TypeError('WritableStreamDefaultController cannot be constructed explicitly');623 }624 error(e: any) {625 if (IsWritableStreamDefaultController(this) === false) {626 throw new TypeError(627 'WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');628 }629 const state = this._controlledWritableStream._state;630 if (state !== 'writable') {631 // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so632 // just treat it as a no-op.633 return;634 }635 WritableStreamDefaultControllerError(this, e);636 }637 /** @internal */638 [AbortSteps](reason: any) {639 const result = this._abortAlgorithm(reason);640 WritableStreamDefaultControllerClearAlgorithms(this);641 return result;642 }643 /** @internal */644 [ErrorSteps]() {645 ResetQueue(this);646 }647}648// Abstract operations implementing interface required by the WritableStream.649function IsWritableStreamDefaultController<W>(x: any): x is WritableStreamDefaultController<W> {650 if (!typeIsObject(x)) {651 return false;652 }653 if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {654 return false;655 }656 return true;657}658function SetUpWritableStreamDefaultController<W>(stream: WritableStream<W>,659 controller: WritableStreamDefaultController<W>,660 startAlgorithm: () => void | PromiseLike<void>,661 writeAlgorithm: (chunk: W) => Promise<void>,662 closeAlgorithm: () => Promise<void>,663 abortAlgorithm: (reason: any) => Promise<void>,664 highWaterMark: number,665 sizeAlgorithm: QueuingStrategySizeCallback<W>) {666 assert(IsWritableStream(stream) === true);667 assert(stream._writableStreamController === undefined);668 controller._controlledWritableStream = stream;669 stream._writableStreamController = controller;670 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.671 controller._queue = undefined!;672 controller._queueTotalSize = undefined!;673 ResetQueue(controller);674 controller._started = false;675 controller._strategySizeAlgorithm = sizeAlgorithm;676 controller._strategyHWM = highWaterMark;677 controller._writeAlgorithm = writeAlgorithm;678 controller._closeAlgorithm = closeAlgorithm;679 controller._abortAlgorithm = abortAlgorithm;680 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);681 WritableStreamUpdateBackpressure(stream, backpressure);682 const startResult = startAlgorithm();683 const startPromise = Promise.resolve(startResult);684 startPromise.then(685 () => {686 assert(stream._state === 'writable' || stream._state === 'erroring');687 controller._started = true;688 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);689 },690 r => {691 assert(stream._state === 'writable' || stream._state === 'erroring');692 controller._started = true;693 WritableStreamDealWithRejection(stream, r);694 }695 ).catch(rethrowAssertionErrorRejection);696}697function SetUpWritableStreamDefaultControllerFromUnderlyingSink<W>(stream: WritableStream<W>,698 underlyingSink: UnderlyingSink<W>,699 highWaterMark: number,700 sizeAlgorithm: QueuingStrategySizeCallback<W>) {701 assert(underlyingSink !== undefined);702 const controller = Object.create(WritableStreamDefaultController.prototype);703 function startAlgorithm() {704 return InvokeOrNoop<typeof underlyingSink, 'start'>(underlyingSink, 'start', [controller]);705 }706 const writeAlgorithm = CreateAlgorithmFromUnderlyingMethod<typeof underlyingSink, 'write'>(707 underlyingSink, 'write', 1, [controller]708 );709 const closeAlgorithm = CreateAlgorithmFromUnderlyingMethod<typeof underlyingSink, 'close'>(710 underlyingSink, 'close', 0, []711 );712 const abortAlgorithm = CreateAlgorithmFromUnderlyingMethod<typeof underlyingSink, 'abort'>(713 underlyingSink, 'abort', 1, []714 );715 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,716 abortAlgorithm, highWaterMark, sizeAlgorithm);717}718// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.719function WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController<any>) {720 controller._writeAlgorithm = undefined!;721 controller._closeAlgorithm = undefined!;722 controller._abortAlgorithm = undefined!;723 controller._strategySizeAlgorithm = undefined!;724}725function WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController<any>) {726 EnqueueValueWithSize(controller, 'close', 0);727 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);728}729function WritableStreamDefaultControllerGetChunkSize<W>(controller: WritableStreamDefaultController<W>,730 chunk: W): number {731 try {732 return controller._strategySizeAlgorithm(chunk);733 } catch (chunkSizeE) {734 WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);735 return 1;736 }737}738function WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController<any>): number {739 return controller._strategyHWM - controller._queueTotalSize;740}741function WritableStreamDefaultControllerWrite<W>(controller: WritableStreamDefaultController<W>,742 chunk: W,743 chunkSize: number) {744 const writeRecord = { chunk };745 try {746 EnqueueValueWithSize(controller, writeRecord, chunkSize);747 } catch (enqueueE) {748 WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);749 return;750 }751 const stream = controller._controlledWritableStream;752 if (WritableStreamCloseQueuedOrInFlight(stream) === false && stream._state === 'writable') {753 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);754 WritableStreamUpdateBackpressure(stream, backpressure);755 }756 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);757}758// Abstract operations for the WritableStreamDefaultController.759function WritableStreamDefaultControllerAdvanceQueueIfNeeded<W>(controller: WritableStreamDefaultController<W>) {760 const stream = controller._controlledWritableStream;761 if (controller._started === false) {762 return;763 }764 if (stream._inFlightWriteRequest !== undefined) {765 return;766 }767 const state = stream._state;768 assert(state !== 'closed' && state !== 'errored');769 if (state === 'erroring') {770 WritableStreamFinishErroring(stream);771 return;772 }773 if (controller._queue.length === 0) {774 return;775 }776 const writeRecord = PeekQueueValue(controller);777 if (writeRecord === 'close') {778 WritableStreamDefaultControllerProcessClose(controller);779 } else {780 WritableStreamDefaultControllerProcessWrite(controller, writeRecord.chunk);781 }782}783function WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController<any>, error: any) {784 if (controller._controlledWritableStream._state === 'writable') {785 WritableStreamDefaultControllerError(controller, error);786 }787}788function WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController<any>) {789 const stream = controller._controlledWritableStream;790 WritableStreamMarkCloseRequestInFlight(stream);791 DequeueValue(controller);792 assert(controller._queue.length === 0);793 const sinkClosePromise = controller._closeAlgorithm();794 WritableStreamDefaultControllerClearAlgorithms(controller);795 sinkClosePromise.then(796 () => {797 WritableStreamFinishInFlightClose(stream);798 },799 reason => {800 WritableStreamFinishInFlightCloseWithError(stream, reason);801 }802 ).catch(rethrowAssertionErrorRejection);803}804function WritableStreamDefaultControllerProcessWrite<W>(controller: WritableStreamDefaultController<W>, chunk: W) {805 const stream = controller._controlledWritableStream;806 WritableStreamMarkFirstWriteRequestInFlight(stream);807 const sinkWritePromise = controller._writeAlgorithm(chunk);808 sinkWritePromise.then(809 () => {810 WritableStreamFinishInFlightWrite(stream);811 const state = stream._state;812 assert(state === 'writable' || state === 'erroring');813 DequeueValue(controller);814 if (WritableStreamCloseQueuedOrInFlight(stream) === false && state === 'writable') {815 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);816 WritableStreamUpdateBackpressure(stream, backpressure);817 }818 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);819 },820 reason => {821 if (stream._state === 'writable') {822 WritableStreamDefaultControllerClearAlgorithms(controller);823 }824 WritableStreamFinishInFlightWriteWithError(stream, reason);825 }826 ).catch(rethrowAssertionErrorRejection);827}828function WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController<any>): boolean {829 const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);830 return desiredSize <= 0;831}832// A client of WritableStreamDefaultController may use these functions directly to bypass state check.833function WritableStreamDefaultControllerError(controller: WritableStreamDefaultController<any>, error: any) {834 const stream = controller._controlledWritableStream;835 assert(stream._state === 'writable');836 WritableStreamDefaultControllerClearAlgorithms(controller);837 WritableStreamStartErroring(stream, error);838}839// Helper functions for the WritableStream.840function streamBrandCheckException(name: string): TypeError {841 return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);842}843// Helper functions for the WritableStreamDefaultWriter.844function defaultWriterBrandCheckException(name: string): TypeError {845 return new TypeError(846 `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);847}848function defaultWriterLockException(name: string): TypeError {849 return new TypeError('Cannot ' + name + ' a stream using a released writer');850}851function defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter<any>) {852 writer._closedPromise = new Promise((resolve, reject) => {853 writer._closedPromise_resolve = resolve;854 writer._closedPromise_reject = reject;855 writer._closedPromiseState = 'pending';856 });857}858function defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter<any>, reason: any) {859 defaultWriterClosedPromiseInitialize(writer);860 defaultWriterClosedPromiseReject(writer, reason);861}862function defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter<any>) {863 defaultWriterClosedPromiseInitialize(writer);864 defaultWriterClosedPromiseResolve(writer);865}866function defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter<any>, reason: any) {867 assert(writer._closedPromise_resolve !== undefined);868 assert(writer._closedPromise_reject !== undefined);869 assert(writer._closedPromiseState === 'pending');870 writer._closedPromise.catch(() => {});871 writer._closedPromise_reject!(reason);872 writer._closedPromise_resolve = undefined;873 writer._closedPromise_reject = undefined;874 writer._closedPromiseState = 'rejected';875}876function defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter<any>, reason: any) {877 assert(writer._closedPromise_resolve === undefined);878 assert(writer._closedPromise_reject === undefined);879 assert(writer._closedPromiseState !== 'pending');880 defaultWriterClosedPromiseInitializeAsRejected(writer, reason);...
writable-stream.js
Source:writable-stream.js
...108 }109 stream._writeRequests = [];110 const writer = stream._writer;111 if (writer !== undefined) {112 defaultWriterClosedPromiseReject(writer, e);113 writer._closedPromise.catch(() => {});114 if (state === 'writable' &&115 WritableStreamDefaultControllerGetBackpressure(stream._writableStreamController) === true) {116 defaultWriterReadyPromiseReject(writer, e);117 } else {118 defaultWriterReadyPromiseResetToRejected(writer, e);119 }120 writer._readyPromise.catch(() => {});121 }122 stream._state = 'errored';123 stream._storedError = e;124}125function WritableStreamFinishClose(stream) {126 assert(stream._state === 'closing');127 // writer cannot be released while close() is ongoing. So, we can assert that128 // there's an active writer.129 assert(stream._writer !== undefined);130 stream._state = 'closed';131 defaultWriterClosedPromiseResolve(stream._writer);132}133function WritableStreamFulfillWriteRequest(stream) {134 assert(stream._writeRequests.length > 0);135 const writeRequest = stream._writeRequests.shift();136 writeRequest._resolve(undefined);137}138function WritableStreamUpdateBackpressure(stream, backpressure) {139 assert(stream._state === 'writable');140 const writer = stream._writer;141 if (writer === undefined) {142 return;143 }144 if (backpressure === true) {145 defaultWriterReadyPromiseReset(writer);146 } else {147 assert(backpressure === false);148 defaultWriterReadyPromiseResolve(writer);149 }150}151class WritableStreamDefaultWriter {152 constructor(stream) {153 if (IsWritableStream(stream) === false) {154 throw new TypeError('WritableStreamDefaultWriter can only be constructed with a WritableStream instance');155 }156 if (IsWritableStreamLocked(stream) === true) {157 throw new TypeError('This stream has already been locked for exclusive writing by another writer');158 }159 this._ownerWritableStream = stream;160 stream._writer = this;161 const state = stream._state;162 if (state === 'writable' || state === 'closing') {163 defaultWriterClosedPromiseInitialize(this);164 } else if (state === 'closed') {165 defaultWriterClosedPromiseInitializeAsResolved(this);166 } else {167 assert(state === 'errored', 'state must be errored');168 defaultWriterClosedPromiseInitializeAsRejected(this, stream._storedError);169 this._closedPromise.catch(() => {});170 }171 if (state === 'writable' &&172 WritableStreamDefaultControllerGetBackpressure(stream._writableStreamController) === true) {173 defaultWriterReadyPromiseInitialize(this);174 } else {175 defaultWriterReadyPromiseInitializeAsResolved(this, undefined);176 }177 }178 get closed() {179 if (IsWritableStreamDefaultWriter(this) === false) {180 return Promise.reject(defaultWriterBrandCheckException('closed'));181 }182 return this._closedPromise;183 }184 get desiredSize() {185 if (IsWritableStreamDefaultWriter(this) === false) {186 throw defaultWriterBrandCheckException('desiredSize');187 }188 if (this._ownerWritableStream === undefined) {189 throw defaultWriterLockException('desiredSize');190 }191 return WritableStreamDefaultWriterGetDesiredSize(this);192 }193 get ready() {194 if (IsWritableStreamDefaultWriter(this) === false) {195 return Promise.reject(defaultWriterBrandCheckException('ready'));196 }197 return this._readyPromise;198 }199 abort(reason) {200 if (IsWritableStreamDefaultWriter(this) === false) {201 return Promise.reject(defaultWriterBrandCheckException('abort'));202 }203 if (this._ownerWritableStream === undefined) {204 return Promise.reject(defaultWriterLockException('abort'));205 }206 return WritableStreamDefaultWriterAbort(this, reason);207 }208 close() {209 if (IsWritableStreamDefaultWriter(this) === false) {210 return Promise.reject(defaultWriterBrandCheckException('close'));211 }212 const stream = this._ownerWritableStream;213 if (stream === undefined) {214 return Promise.reject(defaultWriterLockException('close'));215 }216 if (stream._state === 'closing') {217 return Promise.reject(new TypeError('cannot close an already-closing stream'));218 }219 return WritableStreamDefaultWriterClose(this);220 }221 releaseLock() {222 if (IsWritableStreamDefaultWriter(this) === false) {223 throw defaultWriterBrandCheckException('releaseLock');224 }225 const stream = this._ownerWritableStream;226 if (stream === undefined) {227 return;228 }229 assert(stream._writer !== undefined);230 WritableStreamDefaultWriterRelease(this);231 }232 write(chunk) {233 if (IsWritableStreamDefaultWriter(this) === false) {234 return Promise.reject(defaultWriterBrandCheckException('write'));235 }236 const stream = this._ownerWritableStream;237 if (stream === undefined) {238 return Promise.reject(defaultWriterLockException('write to'));239 }240 if (stream._state === 'closing') {241 return Promise.reject(new TypeError('Cannot write to an already-closed stream'));242 }243 return WritableStreamDefaultWriterWrite(this, chunk);244 }245}246// Abstract operations for the WritableStreamDefaultWriter.247function IsWritableStreamDefaultWriter(x) {248 if (!typeIsObject(x)) {249 return false;250 }251 if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {252 return false;253 }254 return true;255}256// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.257function WritableStreamDefaultWriterAbort(writer, reason) {258 const stream = writer._ownerWritableStream;259 assert(stream !== undefined);260 return WritableStreamAbort(stream, reason);261}262function WritableStreamDefaultWriterClose(writer) {263 const stream = writer._ownerWritableStream;264 assert(stream !== undefined);265 const state = stream._state;266 if (state === 'closed' || state === 'errored') {267 return Promise.reject(new TypeError(268 `The stream (in ${state} state) is not in the writable state and cannot be closed`));269 }270 assert(state === 'writable');271 const promise = WritableStreamAddWriteRequest(stream);272 if (WritableStreamDefaultControllerGetBackpressure(stream._writableStreamController) === true) {273 defaultWriterReadyPromiseResolve(writer);274 }275 stream._state = 'closing';276 WritableStreamDefaultControllerClose(stream._writableStreamController);277 return promise;278}279function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {280 const stream = writer._ownerWritableStream;281 assert(stream !== undefined);282 const state = stream._state;283 if (state === 'closing' || state === 'closed') {284 return Promise.resolve();285 }286 if (state === 'errored') {287 return Promise.reject(stream._storedError);288 }289 assert(state === 'writable');290 return WritableStreamDefaultWriterClose(writer);291}292function WritableStreamDefaultWriterGetDesiredSize(writer) {293 const stream = writer._ownerWritableStream;294 const state = stream._state;295 if (state === 'errored') {296 return null;297 }298 if (state === 'closed') {299 return 0;300 }301 return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);302}303function WritableStreamDefaultWriterRelease(writer) {304 const stream = writer._ownerWritableStream;305 assert(stream !== undefined);306 assert(stream._writer === writer);307 const releasedError = new TypeError(308 'Writer was released and can no longer be used to monitor the stream\'s closedness');309 const state = stream._state;310 if (state === 'writable' || state === 'closing') {311 defaultWriterClosedPromiseReject(writer, releasedError);312 } else {313 defaultWriterClosedPromiseResetToRejected(writer, releasedError);314 }315 writer._closedPromise.catch(() => {});316 if (state === 'writable' &&317 WritableStreamDefaultControllerGetBackpressure(stream._writableStreamController) === true) {318 defaultWriterReadyPromiseReject(writer, releasedError);319 } else {320 defaultWriterReadyPromiseResetToRejected(writer, releasedError);321 }322 writer._readyPromise.catch(() => {});323 stream._writer = undefined;324 writer._ownerWritableStream = undefined;325}326function WritableStreamDefaultWriterWrite(writer, chunk) {327 const stream = writer._ownerWritableStream;328 assert(stream !== undefined);329 const state = stream._state;330 if (state === 'closed' || state === 'errored') {331 return Promise.reject(new TypeError(332 `The stream (in ${state} state) is not in the writable state and cannot be written to`));333 }334 assert(state === 'writable');335 const promise = WritableStreamAddWriteRequest(stream);336 WritableStreamDefaultControllerWrite(stream._writableStreamController, chunk);337 return promise;338}339class WritableStreamDefaultController {340 constructor(stream, underlyingSink, size, highWaterMark) {341 if (IsWritableStream(stream) === false) {342 throw new TypeError('WritableStreamDefaultController can only be constructed with a WritableStream instance');343 }344 if (stream._writableStreamController !== undefined) {345 throw new TypeError(346 'WritableStreamDefaultController instances can only be created by the WritableStream constructor');347 }348 this._controlledWritableStream = stream;349 this._underlyingSink = underlyingSink;350 this._queue = [];351 this._started = false;352 this._writing = false;353 const normalizedStrategy = ValidateAndNormalizeQueuingStrategy(size, highWaterMark);354 this._strategySize = normalizedStrategy.size;355 this._strategyHWM = normalizedStrategy.highWaterMark;356 const backpressure = WritableStreamDefaultControllerGetBackpressure(this);357 if (backpressure === true) {358 WritableStreamUpdateBackpressure(stream, backpressure);359 }360 const controller = this;361 const startResult = InvokeOrNoop(underlyingSink, 'start', [this]);362 Promise.resolve(startResult).then(363 () => {364 controller._started = true;365 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);366 },367 r => {368 WritableStreamDefaultControllerErrorIfNeeded(controller, r);369 }370 )371 .catch(rethrowAssertionErrorRejection);372 }373 error(e) {374 if (IsWritableStreamDefaultController(this) === false) {375 throw new TypeError(376 'WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController');377 }378 const state = this._controlledWritableStream._state;379 if (state === 'closed' || state === 'errored') {380 throw new TypeError(`The stream is ${state} and so cannot be errored`);381 }382 WritableStreamDefaultControllerError(this, e);383 }384}385// Abstract operations implementing interface required by the WritableStream.386function WritableStreamDefaultControllerAbort(controller, reason) {387 controller._queue = [];388 const sinkAbortPromise = PromiseInvokeOrFallbackOrNoop(controller._underlyingSink, 'abort', [reason],389 'close', [controller]);390 return sinkAbortPromise.then(() => undefined);391}392function WritableStreamDefaultControllerClose(controller) {393 EnqueueValueWithSize(controller._queue, 'close', 0);394 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);395}396function WritableStreamDefaultControllerGetDesiredSize(controller) {397 const queueSize = GetTotalQueueSize(controller._queue);398 return controller._strategyHWM - queueSize;399}400function WritableStreamDefaultControllerWrite(controller, chunk) {401 const stream = controller._controlledWritableStream;402 assert(stream._state === 'writable');403 let chunkSize = 1;404 if (controller._strategySize !== undefined) {405 try {406 chunkSize = controller._strategySize(chunk);407 } catch (chunkSizeE) {408 // TODO: Should we notify the sink of this error?409 WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);410 return;411 }412 }413 const writeRecord = { chunk };414 const lastBackpressure = WritableStreamDefaultControllerGetBackpressure(controller);415 try {416 EnqueueValueWithSize(controller._queue, writeRecord, chunkSize);417 } catch (enqueueE) {418 WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);419 return;420 }421 if (stream._state === 'writable') {422 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);423 if (lastBackpressure !== backpressure) {424 WritableStreamUpdateBackpressure(stream, backpressure);425 }426 }427 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);428}429// Abstract operations for the WritableStreamDefaultController.430function IsWritableStreamDefaultController(x) {431 if (!typeIsObject(x)) {432 return false;433 }434 if (!Object.prototype.hasOwnProperty.call(x, '_underlyingSink')) {435 return false;436 }437 return true;438}439function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {440 if (controller._controlledWritableStream._state === 'closed' ||441 controller._controlledWritableStream._state === 'errored') {442 return;443 }444 if (controller._started === false) {445 return;446 }447 if (controller._writing === true) {448 return;449 }450 if (controller._queue.length === 0) {451 return;452 }453 const writeRecord = PeekQueueValue(controller._queue);454 if (writeRecord === 'close') {455 WritableStreamDefaultControllerProcessClose(controller);456 } else {457 WritableStreamDefaultControllerProcessWrite(controller, writeRecord.chunk);458 }459}460function WritableStreamDefaultControllerErrorIfNeeded(controller, e) {461 if (controller._controlledWritableStream._state === 'writable' ||462 controller._controlledWritableStream._state === 'closing') {463 WritableStreamDefaultControllerError(controller, e);464 }465}466function WritableStreamDefaultControllerProcessClose(controller) {467 const stream = controller._controlledWritableStream;468 assert(stream._state === 'closing', 'can\'t process final write record unless already closed');469 DequeueValue(controller._queue);470 assert(controller._queue.length === 0, 'queue must be empty once the final write record is dequeued');471 const sinkClosePromise = PromiseInvokeOrNoop(controller._underlyingSink, 'close', [controller]);472 sinkClosePromise.then(473 () => {474 if (stream._state !== 'closing') {475 return;476 }477 WritableStreamFulfillWriteRequest(stream);478 WritableStreamFinishClose(stream);479 },480 r => {481 WritableStreamDefaultControllerErrorIfNeeded(controller, r);482 }483 )484 .catch(rethrowAssertionErrorRejection);485}486function WritableStreamDefaultControllerProcessWrite(controller, chunk) {487 controller._writing = true;488 const sinkWritePromise = PromiseInvokeOrNoop(controller._underlyingSink, 'write', [chunk, controller]);489 sinkWritePromise.then(490 () => {491 const stream = controller._controlledWritableStream;492 const state = stream._state;493 if (state === 'errored' || state === 'closed') {494 return;495 }496 controller._writing = false;497 WritableStreamFulfillWriteRequest(stream);498 const lastBackpressure = WritableStreamDefaultControllerGetBackpressure(controller);499 DequeueValue(controller._queue);500 if (state !== 'closing') {501 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);502 if (lastBackpressure !== backpressure) {503 WritableStreamUpdateBackpressure(controller._controlledWritableStream, backpressure);504 }505 }506 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);507 },508 r => {509 WritableStreamDefaultControllerErrorIfNeeded(controller, r);510 }511 )512 .catch(rethrowAssertionErrorRejection);513}514function WritableStreamDefaultControllerGetBackpressure(controller) {515 const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);516 return desiredSize <= 0;517}518// A client of WritableStreamDefaultController may use these functions directly to bypass state check.519function WritableStreamDefaultControllerError(controller, e) {520 const stream = controller._controlledWritableStream;521 assert(stream._state === 'writable' || stream._state === 'closing');522 WritableStreamError(stream, e);523 controller._queue = [];524}525// Helper functions for the WritableStream.526function streamBrandCheckException(name) {527 return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);528}529// Helper functions for the WritableStreamDefaultWriter.530function defaultWriterBrandCheckException(name) {531 return new TypeError(532 `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);533}534function defaultWriterLockException(name) {535 return new TypeError('Cannot ' + name + ' a stream using a released writer');536}537function defaultWriterClosedPromiseInitialize(writer) {538 writer._closedPromise = new Promise((resolve, reject) => {539 writer._closedPromise_resolve = resolve;540 writer._closedPromise_reject = reject;541 });542}543function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {544 writer._closedPromise = Promise.reject(reason);545 writer._closedPromise_resolve = undefined;546 writer._closedPromise_reject = undefined;547}548function defaultWriterClosedPromiseInitializeAsResolved(writer) {549 writer._closedPromise = Promise.resolve(undefined);550 writer._closedPromise_resolve = undefined;551 writer._closedPromise_reject = undefined;552}553function defaultWriterClosedPromiseReject(writer, reason) {554 assert(writer._closedPromise_resolve !== undefined);555 assert(writer._closedPromise_reject !== undefined);556 writer._closedPromise_reject(reason);557 writer._closedPromise_resolve = undefined;558 writer._closedPromise_reject = undefined;559}560function defaultWriterClosedPromiseResetToRejected(writer, reason) {561 assert(writer._closedPromise_resolve === undefined);562 assert(writer._closedPromise_reject === undefined);563 writer._closedPromise = Promise.reject(reason);564}565function defaultWriterClosedPromiseResolve(writer) {566 assert(writer._closedPromise_resolve !== undefined);567 assert(writer._closedPromise_reject !== undefined);...
Using AI Code Generation
1const wptools = require('wptools');2wptools.defaultWriterClosedPromiseReject();3const wptools = require('wptools');4wptools.defaultWriterClosedPromiseResolve();5const wptools = require('wptools');6wptools.defaultWriterClosedPromiseReject();7const wptools = require('wptools');8wptools.defaultWriterClosedPromiseResolve();9const wptools = require('wptools');10wptools.write('data to write to file');11const wptools = require('wptools');12wptools.writeAsync('data to write to file');13const wptools = require('wptools');14wptools.writeAsyncPromise('data to write to file').then(function () {15}, function () {16});17const wptools = require('wptools');18wptools.writeAsyncPromise('data to write to file').then(function () {19}, function () {20});21const wptools = require('wptools');22wptools.write('data
Using AI Code Generation
1const wptools = require('wptools')2wptools.defaultWriterClosedPromiseReject()3const wptools = require('wptools')4wptools.defaultWriterClosedPromiseResolve()5const wptools = require('wptools')6wptools.defaultWriterClosedPromiseReset()7const wptools = require('wptools')8wptools.defaultWriterClosedPromiseWait()9const wptools = require('wptools')10wptools.defaultWriterClosedPromiseWaitFor()11const wptools = require('wptools')12wptools.defaultWriterClosedPromiseWaitForAll()13const wptools = require('wptools')14wptools.defaultWriterClosedPromiseWaitForAllSettled()15const wptools = require('wptools')16wptools.defaultWriterClosedPromiseWaitForAny()17const wptools = require('wptools')18wptools.defaultWriterClosedPromiseWaitForAnySettled()19const wptools = require('wptools')20wptools.defaultWriterClosedPromiseWaitForFirst()21const wptools = require('wptools')22wptools.defaultWriterClosedPromiseWaitForFirstSettled()23const wptools = require('wptools')24wptools.defaultWriterClosedPromiseWaitForLast()25const wptools = require('wptools')
Using AI Code Generation
1const wptools = require('wptools');2const wp = wptools();3wp.defaultWriterClosedPromiseReject();4wp.defaultWriterClosedPromiseResolve();5const wptools = require('wptools');6const wp = wptools();7wp.defaultWriterClosedPromiseReject();8wp.defaultWriterClosedPromiseResolve();9const wptools = require('wptools');10const wp = wptools();11wp.defaultWriterClosedPromiseReject();12const wptools = require('wptools');13const wp = wptools();14wp.defaultWriterClosedPromiseResolve();15const wptools = require('wptools');16const wp = wptools();17wp.defaultWriterClosedPromise();18const wptools = require('wptools');19const wp = wptools();20wp.defaultWriterClosed();21const wptools = require('wptools');22const wp = wptools();23wp.defaultWriterClosedPromiseReject();24const wptools = require('wptools');25const wp = wptools();26wp.defaultWriterClosedPromiseResolve();27const wptools = require('w
Using AI Code Generation
1import { defaultWriterClosedPromiseReject } from "./wpt/streams/resources/test-utils.js";2promise_test(async t => {3 const ws = new WritableStream({4 write() {5 return defaultWriterClosedPromiseReject(new TypeError("boo"));6 }7 });8 const writer = ws.getWriter();9 writer.write("a");10 writer.close();11 await promise_rejects(t, new TypeError("boo"), writer.closed, "closed should reject");12}, "closed should reject with the error passed to defaultWriterClosedPromiseReject()");13I don't know if it's possible to import the test from the wpt repo into the streams repo, or if it's possible
Using AI Code Generation
1const wptools = require('wp-tools');2const defaultWriterClosedPromiseReject = wptools.defaultWriterClosedPromiseReject;3const stream = require('stream');4const { Readable } = stream;5const { Writable } = stream;6const readable = new Readable({7 read(size) {8 this.push('some data');9 this.push(null);10 }11});12const writable = new Writable({13 write(chunk, encoding, callback) {14 callback();15 }16});17readable.pipe(writable);18defaultWriterClosedPromiseReject(readable, writable, new Error('some error'));19const wptools = require('wp-tools');20const defaultWriterClosedPromiseResolve = wptools.defaultWriterClosedPromiseResolve;21const stream = require('stream');22const { Readable } = stream;23const { Writable } = stream;24const readable = new Readable({25 read(size) {26 this.push('some data');27 this.push(null);28 }29});30const writable = new Writable({31 write(chunk, encoding, callback) {32 callback();33 }34});35readable.pipe(writable);36defaultWriterClosedPromiseResolve(readable, writable, 'some data');37const wptools = require('wp-tools');38const defaultWriterClosedPromiseResolve = wptools.defaultWriterClosedPromiseResolve;39const stream = require('stream');40const { Readable } = stream;41const { Writable } = stream;42const readable = new Readable({43 read(size) {44 this.push('some data');45 this.push(null);46 }47});48const writable = new Writable({49 write(chunk, encoding, callback) {50 callback();51 }52});53readable.pipe(writable);54defaultWriterClosedPromiseResolve(readable, writable);55const wptools = require('wp-tools');56const defaultWriterClosedPromiseResolve = wptools.defaultWriterClosedPromiseResolve;57const stream = require('stream');58const { Readable } = stream;59const { Writable } = stream;60const readable = new Readable({61 read(size) {62 this.push('some data');63 this.push(null);64 }65});
Using AI Code Generation
1import { defaultWriterClosedPromiseReject } from 'wpt';2test(() => {3 const writer = new WritableStream().getWriter();4 const closedPromise = writer.closed;5 writer.releaseLock();6 const customError = new Error('custom error');7 defaultWriterClosedPromiseReject(closedPromise, customError);8 return promise_rejects(t, customError, closedPromise, 'closed promise should be rejected with the custom error');9}, 'Test to verify defaultWriterClosedPromiseReject method of wpt');10export function defaultWriterClosedPromiseReject(closedPromise, customError) {11 closedPromise.catch(() => {});12 closedPromise._reject(customError);13}
Using AI Code Generation
1(async () => {2 const writer = new WritableStreamDefaultWriter();3 writer.releaseLock();4 const promise = writer.defaultWriterClosedPromiseReject;5 promise.catch(() => {});6 writer.close();7 await promise;8})();
Using AI Code Generation
1const wpt = require('wpt');2const fs = require('fs');3const path = 'test.txt';4wpt.defaultWriterClosedPromiseReject(path, fs);5console.log('File created successfully');6Related Posts: Node.js | fs.writeFile() method7Node.js | fs.writeSync() method8Node.js | fs.write() method9Node.js | fs.read() method10Node.js | fs.readSync() method11Node.js | fs.readFile() method12Node.js | fs.readFileSync() method13Node.js | fs.appendFile() method14Node.js | fs.appendFileSync() method15Node.js | fs.access() method16Node.js | fs.accessSync() method17Node.js | fs.copyFile() method18Node.js | fs.copyFileSync() method19Node.js | fs.createReadStream() method20Node.js | fs.createWriteStream() method
Using AI Code Generation
1const wpt = require('wpt');2const fs = require('fs');3const stream = fs.createWriteStream('output.txt');4stream.write('Hello World!');5stream.end('This is the end of the file.');6stream.on('finish', () => {7 console.log('The file has been written.');8});9stream.on('close', () => {10 console.log('The file has been closed.');11});12wpt.defaultWriterClosedPromiseReject(stream).then(() => {13 console.log('The file has been written.');14}).catch(() => {15 console.log('The file has been closed.');16});17const wpt = require('wpt');18const fs = require('fs');19const stream = fs.createWriteStream('output.txt');20stream.write('Hello World!');21stream.end('This is the end of the file.');22stream.on('finish', () => {23 console.log('The file has been written.');24});25stream.on('close', () => {26 console.log('The file has been closed.');27});28wpt.defaultWriterClosedPromiseReject(stream).then(() => {29 console.log('The file has been written.');30}).catch(() => {31 console.log('The file has been closed.');32});33const wpt = require('wpt');34const fs = require('fs');35const stream = fs.createWriteStream('output.txt');36stream.write('Hello World!');37stream.end('This is the end of the file.');38stream.on('finish', () => {39 console.log('The file has been written.');40});41stream.on('close', () => {42 console.log('The file has been closed.');43});44wpt.defaultWriterReadyPromiseReject(stream).then(() => {45 console.log('The file has been written.');46}).catch(() => {47 console.log('The file has been closed.');48});49const wpt = require('wpt');50const fs = require('fs');51const stream = fs.createWriteStream('output.txt');52stream.write('Hello World!
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!!