-
Notifications
You must be signed in to change notification settings - Fork 30
/
readable-stream.ts
533 lines (454 loc) · 19 KB
/
readable-stream.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
import assert from '../stub/assert';
import {
promiseRejectedWith,
promiseResolvedWith,
setPromiseIsHandledToTrue,
transformPromiseWith
} from './helpers/webidl';
import { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';
import { AcquireReadableStreamAsyncIterator, ReadableStreamAsyncIterator } from './readable-stream/async-iterator';
import { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';
import {
AcquireReadableStreamDefaultReader,
IsReadableStreamDefaultReader,
ReadableStreamDefaultReader,
ReadableStreamDefaultReadResult
} from './readable-stream/default-reader';
import {
AcquireReadableStreamBYOBReader,
IsReadableStreamBYOBReader,
ReadableStreamBYOBReader,
ReadableStreamBYOBReadResult
} from './readable-stream/byob-reader';
import { ReadableStreamPipeTo } from './readable-stream/pipe';
import { ReadableStreamTee } from './readable-stream/tee';
import { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';
import { SimpleQueue } from './simple-queue';
import {
ReadableByteStreamController,
ReadableStreamBYOBRequest,
SetUpReadableByteStreamController,
SetUpReadableByteStreamControllerFromUnderlyingSource
} from './readable-stream/byte-stream-controller';
import {
ReadableStreamDefaultController,
SetUpReadableStreamDefaultController,
SetUpReadableStreamDefaultControllerFromUnderlyingSource
} from './readable-stream/default-controller';
import {
UnderlyingByteSource,
UnderlyingByteSourcePullCallback,
UnderlyingByteSourceStartCallback,
UnderlyingSource,
UnderlyingSourceCancelCallback,
UnderlyingSourcePullCallback,
UnderlyingSourceStartCallback
} from './readable-stream/underlying-source';
import { noop } from '../utils';
import { typeIsObject } from './helpers/miscellaneous';
import { CreateArrayFromList } from './abstract-ops/ecmascript';
import { CancelSteps } from './abstract-ops/internal-methods';
import { IsNonNegativeNumber } from './abstract-ops/miscellaneous';
import { assertObject, assertRequiredArgument } from './validators/basic';
import { convertQueuingStrategy } from './validators/queuing-strategy';
import { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';
import { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';
import { ReadableStreamGetReaderOptions } from './readable-stream/reader-options';
import { convertReaderOptions } from './validators/reader-options';
import { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';
import { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';
import { convertIteratorOptions } from './validators/iterator-options';
import { convertPipeOptions } from './validators/pipe-options';
import { ReadableWritablePair } from './readable-stream/readable-writable-pair';
import { convertReadableWritablePair } from './validators/readable-writable-pair';
export type ReadableByteStream = ReadableStream<Uint8Array> & {
_readableStreamController: ReadableByteStreamController
};
type ReadableStreamState = 'readable' | 'closed' | 'errored';
/**
* A readable stream represents a source of data, from which you can read.
*
* @public
*/
export class ReadableStream<R = any> {
/** @internal */
_state!: ReadableStreamState;
/** @internal */
_reader: ReadableStreamReader<R> | undefined;
/** @internal */
_storedError: any;
/** @internal */
_disturbed!: boolean;
/** @internal */
_readableStreamController!: ReadableStreamDefaultController<R> | ReadableByteStreamController;
constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });
constructor(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>);
constructor(rawUnderlyingSource: UnderlyingSource<R> | UnderlyingByteSource | null | undefined = {},
rawStrategy: QueuingStrategy<R> | null | undefined = {}) {
if (rawUnderlyingSource === undefined) {
rawUnderlyingSource = null;
} else {
assertObject(rawUnderlyingSource, 'First parameter');
}
const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');
InitializeReadableStream(this);
if (underlyingSource.type === 'bytes') {
if (strategy.size !== undefined) {
throw new RangeError('The strategy for a byte stream cannot have a size function');
}
const highWaterMark = ExtractHighWaterMark(strategy, 0);
SetUpReadableByteStreamControllerFromUnderlyingSource(
this as unknown as ReadableByteStream,
underlyingSource,
highWaterMark
);
} else {
assert(underlyingSource.type === undefined);
const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
const highWaterMark = ExtractHighWaterMark(strategy, 1);
SetUpReadableStreamDefaultControllerFromUnderlyingSource(
this,
underlyingSource,
highWaterMark,
sizeAlgorithm
);
}
}
/**
* Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
*/
get locked(): boolean {
if (!IsReadableStream(this)) {
throw streamBrandCheckException('locked');
}
return IsReadableStreamLocked(this);
}
/**
* Cancels the stream, signaling a loss of interest in the stream by a consumer.
*
* The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
* method, which might or might not use it.
*/
cancel(reason: any = undefined): Promise<void> {
if (!IsReadableStream(this)) {
return promiseRejectedWith(streamBrandCheckException('cancel'));
}
if (IsReadableStreamLocked(this)) {
return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
}
return ReadableStreamCancel(this, reason);
}
/**
* Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.
*
* This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,
* i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading.
* The returned BYOB reader provides the ability to directly read individual chunks from the stream via its
* {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise
* control over allocation.
*/
getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;
/**
* Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.
* While the stream is locked, no other reader can be acquired until this one is released.
*
* This functionality is especially useful for creating abstractions that desire the ability to consume a stream
* in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours
* or cancel the stream, which would interfere with your abstraction.
*/
getReader(): ReadableStreamDefaultReader<R>;
getReader(
rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined
): ReadableStreamDefaultReader<R> | ReadableStreamBYOBReader {
if (!IsReadableStream(this)) {
throw streamBrandCheckException('getReader');
}
const options = convertReaderOptions(rawOptions, 'First parameter');
if (options.mode === undefined) {
return AcquireReadableStreamDefaultReader(this);
}
assert(options.mode === 'byob');
return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);
}
/**
* Provides a convenient, chainable way of piping this readable stream through a transform stream
* (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream
* into the writable side of the supplied pair, and returns the readable side for further use.
*
* Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
*/
pipeThrough<RS extends ReadableStream>(
transform: { readable: RS; writable: WritableStream<R> },
options?: StreamPipeOptions
): RS;
pipeThrough<RS extends ReadableStream>(
rawTransform: { readable: RS; writable: WritableStream<R> } | null | undefined,
rawOptions: StreamPipeOptions | null | undefined = {}
): RS {
if (!IsReadableStream(this)) {
throw streamBrandCheckException('pipeThrough');
}
assertRequiredArgument(rawTransform, 1, 'pipeThrough');
const transform = convertReadableWritablePair(rawTransform, 'First parameter');
const options = convertPipeOptions(rawOptions, 'Second parameter');
if (IsReadableStreamLocked(this)) {
throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
}
if (IsWritableStreamLocked(transform.writable)) {
throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
}
const promise = ReadableStreamPipeTo(
this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal
);
setPromiseIsHandledToTrue(promise);
return transform.readable;
}
/**
* Pipes this readable stream to a given writable stream. The way in which the piping process behaves under
* various error conditions can be customized with a number of passed options. It returns a promise that fulfills
* when the piping process completes successfully, or rejects if any errors were encountered.
*
* Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
*/
pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
pipeTo(destination: WritableStream<R> | null | undefined,
rawOptions: StreamPipeOptions | null | undefined = {}): Promise<void> {
if (!IsReadableStream(this)) {
return promiseRejectedWith(streamBrandCheckException('pipeTo'));
}
if (destination === undefined) {
return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
}
if (!IsWritableStream(destination)) {
return promiseRejectedWith(
new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)
);
}
let options: ValidatedStreamPipeOptions;
try {
options = convertPipeOptions(rawOptions, 'Second parameter');
} catch (e) {
return promiseRejectedWith(e);
}
if (IsReadableStreamLocked(this)) {
return promiseRejectedWith(
new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')
);
}
if (IsWritableStreamLocked(destination)) {
return promiseRejectedWith(
new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')
);
}
return ReadableStreamPipeTo<R>(
this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal
);
}
/**
* Tees this readable stream, returning a two-element array containing the two resulting branches as
* new {@link ReadableStream} instances.
*
* Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
* To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
* propagated to the stream's underlying source.
*
* Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
* this could allow interference between the two branches.
*/
tee(): [ReadableStream<R>, ReadableStream<R>] {
if (!IsReadableStream(this)) {
throw streamBrandCheckException('tee');
}
const branches = ReadableStreamTee(this, false);
return CreateArrayFromList(branches);
}
/**
* Asynchronously iterates over the chunks in the stream's internal queue.
*
* Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.
* The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method
* is called, e.g. by breaking out of the loop.
*
* By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also
* cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing
* `true` for the `preventCancel` option.
*/
values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator<R> {
if (!IsReadableStream(this)) {
throw streamBrandCheckException('values');
}
const options = convertIteratorOptions(rawOptions, 'First parameter');
return AcquireReadableStreamAsyncIterator<R>(this, options.preventCancel);
}
/**
* {@inheritDoc ReadableStream.values}
*/
[Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator<R>;
}
Object.defineProperties(ReadableStream.prototype, {
cancel: { enumerable: true },
getReader: { enumerable: true },
pipeThrough: { enumerable: true },
pipeTo: { enumerable: true },
tee: { enumerable: true },
values: { enumerable: true },
locked: { enumerable: true }
});
if (typeof Symbol.toStringTag === 'symbol') {
Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {
value: 'ReadableStream',
configurable: true
});
}
if (typeof Symbol.asyncIterator === 'symbol') {
Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {
value: ReadableStream.prototype.values,
writable: true,
configurable: true
});
}
export {
ReadableStreamAsyncIterator,
ReadableStreamDefaultReadResult,
ReadableStreamBYOBReadResult,
UnderlyingByteSource,
UnderlyingSource,
UnderlyingSourceStartCallback,
UnderlyingSourcePullCallback,
UnderlyingSourceCancelCallback,
UnderlyingByteSourceStartCallback,
UnderlyingByteSourcePullCallback,
StreamPipeOptions,
ReadableWritablePair,
ReadableStreamIteratorOptions
};
// Abstract operations for the ReadableStream.
// Throws if and only if startAlgorithm throws.
export function CreateReadableStream<R>(startAlgorithm: () => void | PromiseLike<void>,
pullAlgorithm: () => Promise<void>,
cancelAlgorithm: (reason: any) => Promise<void>,
highWaterMark = 1,
sizeAlgorithm: QueuingStrategySizeCallback<R> = () => 1): ReadableStream<R> {
assert(IsNonNegativeNumber(highWaterMark));
const stream: ReadableStream<R> = Object.create(ReadableStream.prototype);
InitializeReadableStream(stream);
const controller: ReadableStreamDefaultController<R> = Object.create(ReadableStreamDefaultController.prototype);
SetUpReadableStreamDefaultController(
stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm
);
return stream;
}
// Throws if and only if startAlgorithm throws.
export function CreateReadableByteStream(
startAlgorithm: () => void | PromiseLike<void>,
pullAlgorithm: () => Promise<void>,
cancelAlgorithm: (reason: any) => Promise<void>
): ReadableByteStream {
const stream: ReadableByteStream = Object.create(ReadableStream.prototype);
InitializeReadableStream(stream);
const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);
SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);
return stream;
}
function InitializeReadableStream(stream: ReadableStream) {
stream._state = 'readable';
stream._reader = undefined;
stream._storedError = undefined;
stream._disturbed = false;
}
export function IsReadableStream(x: unknown): x is ReadableStream {
if (!typeIsObject(x)) {
return false;
}
if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
return false;
}
return x instanceof ReadableStream;
}
export function IsReadableStreamDisturbed(stream: ReadableStream): boolean {
assert(IsReadableStream(stream));
return stream._disturbed;
}
export function IsReadableStreamLocked(stream: ReadableStream): boolean {
assert(IsReadableStream(stream));
if (stream._reader === undefined) {
return false;
}
return true;
}
// ReadableStream API exposed for controllers.
export function ReadableStreamCancel<R>(stream: ReadableStream<R>, reason: any): Promise<undefined> {
stream._disturbed = true;
if (stream._state === 'closed') {
return promiseResolvedWith(undefined);
}
if (stream._state === 'errored') {
return promiseRejectedWith(stream._storedError);
}
ReadableStreamClose(stream);
const reader = stream._reader;
if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {
reader._readIntoRequests.forEach(readIntoRequest => {
readIntoRequest._closeSteps(undefined);
});
reader._readIntoRequests = new SimpleQueue();
}
const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
return transformPromiseWith(sourceCancelPromise, noop);
}
export function ReadableStreamClose<R>(stream: ReadableStream<R>): void {
assert(stream._state === 'readable');
stream._state = 'closed';
const reader = stream._reader;
if (reader === undefined) {
return;
}
defaultReaderClosedPromiseResolve(reader);
if (IsReadableStreamDefaultReader<R>(reader)) {
reader._readRequests.forEach(readRequest => {
readRequest._closeSteps();
});
reader._readRequests = new SimpleQueue();
}
}
export function ReadableStreamError<R>(stream: ReadableStream<R>, e: any): void {
assert(IsReadableStream(stream));
assert(stream._state === 'readable');
stream._state = 'errored';
stream._storedError = e;
const reader = stream._reader;
if (reader === undefined) {
return;
}
defaultReaderClosedPromiseReject(reader, e);
if (IsReadableStreamDefaultReader<R>(reader)) {
reader._readRequests.forEach(readRequest => {
readRequest._errorSteps(e);
});
reader._readRequests = new SimpleQueue();
} else {
assert(IsReadableStreamBYOBReader(reader));
reader._readIntoRequests.forEach(readIntoRequest => {
readIntoRequest._errorSteps(e);
});
reader._readIntoRequests = new SimpleQueue();
}
}
// Readers
export type ReadableStreamReader<R> = ReadableStreamDefaultReader<R> | ReadableStreamBYOBReader;
export {
ReadableStreamDefaultReader,
ReadableStreamBYOBReader
};
// Controllers
export {
ReadableStreamDefaultController,
ReadableStreamBYOBRequest,
ReadableByteStreamController
};
// Helper functions for the ReadableStream.
function streamBrandCheckException(name: string): TypeError {
return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
}