web-utility-streams 0.1.1 → 1.0.0-canary-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,6 +6,8 @@ Various utility streams that are very useful for working with web streams.
6
6
 
7
7
  **Transform streams**
8
8
 
9
+ - [`AddPrefixStream`](#addprefixstream) - Emit some chunks before the rest of the stream.
10
+ - [`DebounceStream`](#debouncestream) - Emit at most one chunk per period, dropping the rest.
9
11
  - [`DebugStream`](#debugstream) - Call a function with each chunk as it passes through.
10
12
  - [`EventSourceDecoderStream`](#eventsourcedecoderstream) - Decode `text/event-stream` (Server-Sent Events) text into events.
11
13
  - [`EventSourceEncoderStream`](#eventsourceencoderstream) - Encode events as `text/event-stream` (Server-Sent Events) text.
@@ -18,7 +20,9 @@ Various utility streams that are very useful for working with web streams.
18
20
  - [`NewlineDelimitedJsonDecoderStream`](#newlinedelimitedjsondecoderstream) - Parse each line of NDJSON text into a value.
19
21
  - [`NewlineDelimitedJsonEncoderStream`](#newlinedelimitedjsonencoderstream) - Encode each value as a line of NDJSON.
20
22
  - [`SplitLinesStream`](#splitlinesstream) - Split text into lines.
23
+ - [`TimeoutStream`](#timeoutstream) - Error the stream if no chunk arrives for too long.
21
24
  - [`TransformPipelineStream`](#transformpipelinestream) - Combine several transform streams into one.
25
+ - [`TransformStreamWithCancel`](#transformstreamwithcancel) - A `TransformStream` that calls the transformer's `cancel` method, in any runtime.
22
26
 
23
27
  **Readable streams**
24
28
 
@@ -53,6 +57,40 @@ try {
53
57
 
54
58
  ## Transform streams
55
59
 
60
+ ### AddPrefixStream
61
+
62
+ Emit the chunks of a prefix, then pass the rest of the stream through unchanged. The prefix can be an array (or any other iterable), an async iterable, a `ReadableStream`, or a promise for one of these.
63
+
64
+ ```ts
65
+ import AddPrefixStream from "web-utility-streams/AddPrefixStream";
66
+
67
+ const events = updates.pipeThrough(
68
+ new AddPrefixStream(getCurrentState().then((state) => [state])),
69
+ );
70
+ ```
71
+
72
+ The prefix is only read as the output is read, and written chunks wait until it's done. If the prefix errors, the stream errors. If the stream is cancelled or errors first, the prefix is closed, so a generator's `finally` blocks run and a `ReadableStream` is cancelled.
73
+
74
+ ### DebounceStream
75
+
76
+ Emit at most one chunk every `debounceMs` milliseconds, dropping the rest. This is useful for things like progress updates, where only the latest value matters.
77
+
78
+ ```ts
79
+ import DebounceStream from "web-utility-streams/DebounceStream";
80
+
81
+ const progress = progressEvents.pipeThrough(
82
+ new DebounceStream({ debounceMs: 100 }),
83
+ );
84
+ ```
85
+
86
+ A period starts when a chunk is written and nothing has been emitted in the last `debounceMs`. The `mode` option controls which chunks of each period are emitted:
87
+
88
+ - `"BOTH"` (the default): the first chunk straight away, and the most recent chunk at the end of the period, if there was another.
89
+ - `"LEADING"`: only the first chunk, straight away.
90
+ - `"TRAILING"`: only the most recent chunk, at the end of the period.
91
+
92
+ Emitting a trailing chunk starts a new period. Pass `restartTimerOnChunk: true` to extend the period each time a chunk is written, so it only ends after a gap of `debounceMs`. When the input closes, a waiting trailing chunk is emitted straight away. Writes never wait for the output to be read; if it falls behind, only the most recent chunk is kept.
93
+
56
94
  ### DebugStream
57
95
 
58
96
  Pass every chunk through unchanged, calling a function with each one as it goes past. By default, chunks are logged with `console.log`. This is useful for debugging a pipeline. If the function throws, the stream is errored.
@@ -316,6 +354,55 @@ for await (const line of lines) {
316
354
  }
317
355
  ```
318
356
 
357
+ ### TimeoutStream
358
+
359
+ Pass chunks through unchanged, but error the stream if no chunk is written for `timeoutMs` milliseconds. This is useful for detecting a connection that has stalled, such as a streaming API response that stops sending data without closing. When the timeout is reached, the stream is errored with a `TimeoutStreamError` (which has `code: "TIMEOUT_STREAM_TIMEOUT"`), so in a pipeline the source is cancelled and the error is thrown from `pipeTo`.
360
+
361
+ ```ts
362
+ import TimeoutStream, {
363
+ TimeoutStreamError,
364
+ } from "web-utility-streams/TimeoutStream";
365
+
366
+ try {
367
+ await response
368
+ .body!.pipeThrough(new TimeoutStream({ timeoutMs: 30_000 }))
369
+ .pipeTo(destination);
370
+ } catch (ex) {
371
+ if (ex instanceof TimeoutStreamError) {
372
+ // No data was received for 30 seconds
373
+ }
374
+ }
375
+ ```
376
+
377
+ The timeout starts when the stream is created, and is stopped when the input closes, or the stream is cancelled or errored.
378
+
379
+ Chunks are only written to a `TimeoutStream` when its output has room for them (it reads one chunk ahead of the output), so if the output is read slowly, for example because the destination of a pipeline is slow, the input is held back by backpressure, and that can cause a timeout too. Choose a timeout that allows for the slowest reader you expect, or put the `TimeoutStream` before any slow steps in the pipeline.
380
+
381
+ `timeoutMs` can also be a function, which is called to choose the first timeout (with `remainingMs` of `0` and no chunk), and then each time a chunk is written, with the time that was left of the previous timeout and the chunk. For example, when streaming audio to a player that reads it in real time, each chunk gives the input longer before the next one is needed:
382
+
383
+ ```ts
384
+ await audioStream
385
+ .pipeThrough(
386
+ new TimeoutStream<AudioChunk>({
387
+ // Allow 5 seconds for the first chunk. After that, add the length of
388
+ // each chunk to the time that was left, as the player won't ask for
389
+ // more until it has played it.
390
+ timeoutMs: (remainingMs, chunk) =>
391
+ chunk === undefined ? 5_000 : remainingMs + getAudioDuration(chunk),
392
+ }),
393
+ )
394
+ .pipeTo(audioPlayer);
395
+ ```
396
+
397
+ Pass `onTimeout` to choose what happens when the timeout is reached. It's called with the stream's `TransformStreamDefaultController`, so it can error the stream with your own error, end it cleanly with `controller.terminate()`, or enqueue a chunk. If it doesn't error or terminate the stream, the timeout starts again when the next chunk is written. If it throws, the stream is errored.
398
+
399
+ ```ts
400
+ const stream = new TimeoutStream({
401
+ timeoutMs: 10_000,
402
+ onTimeout: (controller) => controller.error(new MyTimeoutError()),
403
+ });
404
+ ```
405
+
319
406
  ### TransformPipelineStream
320
407
 
321
408
  Combine a series of transform streams into a single transform stream. The function you pass is given an `input` with a `pipeThrough` method, and must return the final readable stream.
@@ -342,6 +429,31 @@ class BytesToEventsStream extends TransformPipelineStream<
342
429
  const events = response.body!.pipeThrough(new BytesToEventsStream());
343
430
  ```
344
431
 
432
+ ### TransformStreamWithCancel
433
+
434
+ `TransformStream`, with support for the transformer's `cancel` method in every runtime. `cancel` is called with the reason when the readable side is cancelled or the writable side is aborted (e.g. because another part of a pipeline errored), which makes it the place to clean up resources such as timers or connections. It was added to the Streams standard in 2023, but isn't supported everywhere yet.
435
+
436
+ In runtimes that support `cancel` (such as Node.js), `TransformStreamWithCancel` is just `TransformStream`. Elsewhere it's `TransformStreamWithCancelPolyfill`, which implements the standard's `TransformStream` with a `ReadableStream` and a `WritableStream`. It supports everything `TransformStream` does, including queuing strategies and backpressure, but `instanceof TransformStream` is `false`.
437
+
438
+ ```ts
439
+ import TransformStreamWithCancel from "web-utility-streams/TransformStreamWithCancel";
440
+
441
+ const subscription = subscribe();
442
+ const stream = new TransformStreamWithCancel<Message, Message>({
443
+ transform(message, controller) {
444
+ if (subscription.isWanted(message)) controller.enqueue(message);
445
+ },
446
+ flush() {
447
+ subscription.unsubscribe();
448
+ },
449
+ cancel(reason) {
450
+ subscription.unsubscribe();
451
+ },
452
+ });
453
+ ```
454
+
455
+ You can extend it like `TransformStream`, e.g. `class MyStream extends TransformStreamWithCancel<In, Out>`. The module also exports `supportsTransformerCancel`, which is `true` if the native `TransformStream` supports `cancel`, the `TransformStreamWithCancelPolyfill` class (if you want to use it regardless), and the `TransformerWithCancel` type (TypeScript's own `Transformer` type doesn't include `cancel` yet).
456
+
345
457
  ## Readable streams
346
458
 
347
459
  ### ConcatStream
@@ -0,0 +1,19 @@
1
+ export type AddPrefixStreamPrefix<TChunk> = AsyncIterable<TChunk> | Iterable<TChunk> | ReadableStream<TChunk> | PromiseLike<AsyncIterable<TChunk> | Iterable<TChunk> | ReadableStream<TChunk>>;
2
+ /**
3
+ * Emit the chunks of `prefix`, then pass every chunk written to the stream
4
+ * through unchanged. The prefix can be an iterable, an async iterable, a
5
+ * `ReadableStream`, or a promise for any of these.
6
+ *
7
+ * - The prefix is read as the output is read. Written chunks wait until the
8
+ * prefix is done, and then up to 4 are read ahead of the output.
9
+ * - If the prefix errors, the stream is errored, cancelling the source.
10
+ * - If the writable side is aborted, the output is errored straight away.
11
+ * - If the stream is cancelled or errors before the prefix is done, the
12
+ * prefix is closed (by calling its iterator's `return` method, or by
13
+ * cancelling the `ReadableStream`).
14
+ */
15
+ export default class AddPrefixStream<TChunk> implements TransformStream<TChunk, TChunk> {
16
+ readonly readable: ReadableStream<TChunk>;
17
+ readonly writable: WritableStream<TChunk>;
18
+ constructor(prefix: AddPrefixStreamPrefix<TChunk>);
19
+ }
@@ -0,0 +1,139 @@
1
+ // src/AddPrefixStream.ts
2
+ const noop = () => {};
3
+ /**
4
+ * Emit the chunks of `prefix`, then pass every chunk written to the stream
5
+ * through unchanged. The prefix can be an iterable, an async iterable, a
6
+ * `ReadableStream`, or a promise for any of these.
7
+ *
8
+ * - The prefix is read as the output is read. Written chunks wait until the
9
+ * prefix is done, and then up to 4 are read ahead of the output.
10
+ * - If the prefix errors, the stream is errored, cancelling the source.
11
+ * - If the writable side is aborted, the output is errored straight away.
12
+ * - If the stream is cancelled or errors before the prefix is done, the
13
+ * prefix is closed (by calling its iterator's `return` method, or by
14
+ * cancelling the `ReadableStream`).
15
+ */
16
+ var AddPrefixStream = class {
17
+ readable;
18
+ writable;
19
+ constructor(prefix) {
20
+ let readableController;
21
+ let writableController;
22
+ let isFinished = false;
23
+ let finishReason;
24
+ let iterator;
25
+ let isAsyncIterator = false;
26
+ let isPrefixDone = false;
27
+ let pendingWrite;
28
+ let isWritableClosed = false;
29
+ const closePrefix = () => {
30
+ const it = iterator;
31
+ const reason = finishReason;
32
+ iterator = void 0;
33
+ if (it?.return) Promise.resolve().then(() => it.return(reason)).catch(noop);
34
+ };
35
+ const finish = (reason) => {
36
+ isFinished = true;
37
+ finishReason = reason;
38
+ pendingWrite?.reject(reason);
39
+ closePrefix();
40
+ };
41
+ const fail = (err) => {
42
+ if (isFinished) return;
43
+ readableController.error(err);
44
+ writableController.error(err);
45
+ finish(err);
46
+ };
47
+ const abort = (reason) => {
48
+ if (isFinished) return;
49
+ readableController.error(reason);
50
+ finish(reason);
51
+ };
52
+ const pullWritten = () => {
53
+ if (pendingWrite) {
54
+ const { chunk, resolve } = pendingWrite;
55
+ pendingWrite = void 0;
56
+ readableController.enqueue(chunk);
57
+ resolve();
58
+ } else if (isWritableClosed) {
59
+ isFinished = true;
60
+ readableController.close();
61
+ }
62
+ };
63
+ const onPrefixResult = (result) => {
64
+ if (isFinished) return;
65
+ if (!result.done) {
66
+ readableController.enqueue(result.value);
67
+ return;
68
+ }
69
+ iterator = void 0;
70
+ isPrefixDone = true;
71
+ pullWritten();
72
+ };
73
+ this.writable = new WritableStream({
74
+ start(controller) {
75
+ writableController = controller;
76
+ controller.signal?.addEventListener("abort", () => abort(controller.signal.reason));
77
+ },
78
+ write(chunk) {
79
+ if (isPrefixDone && readableController.desiredSize >= -2) {
80
+ readableController.enqueue(chunk);
81
+ return;
82
+ }
83
+ return new Promise((resolve, reject) => {
84
+ pendingWrite = {
85
+ chunk,
86
+ resolve,
87
+ reject
88
+ };
89
+ });
90
+ },
91
+ close() {
92
+ isWritableClosed = true;
93
+ if (isPrefixDone && !isFinished) {
94
+ isFinished = true;
95
+ readableController.close();
96
+ }
97
+ },
98
+ abort
99
+ });
100
+ this.readable = new ReadableStream({
101
+ async start(controller) {
102
+ readableController = controller;
103
+ try {
104
+ const iterable = await prefix;
105
+ if (typeof iterable.getReader === "function") {
106
+ const reader = iterable.getReader();
107
+ isAsyncIterator = true;
108
+ iterator = {
109
+ next: () => reader.read(),
110
+ return: (reason) => reader.cancel(reason)
111
+ };
112
+ } else {
113
+ isAsyncIterator = typeof iterable[Symbol.asyncIterator] === "function";
114
+ iterator = isAsyncIterator ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
115
+ }
116
+ if (isFinished) closePrefix();
117
+ } catch (ex) {
118
+ fail(ex);
119
+ }
120
+ },
121
+ pull() {
122
+ if (isPrefixDone) return pullWritten();
123
+ if (isAsyncIterator) return iterator.next().then(onPrefixResult, fail);
124
+ let result;
125
+ try {
126
+ result = iterator.next();
127
+ } catch (ex) {
128
+ return fail(ex);
129
+ }
130
+ onPrefixResult(result);
131
+ },
132
+ cancel(reason) {
133
+ writableController.error(reason);
134
+ finish(reason);
135
+ }
136
+ }, { highWaterMark: 0 });
137
+ }
138
+ };
139
+ export { AddPrefixStream as default };
@@ -0,0 +1,33 @@
1
+ export interface DebounceStreamOptions {
2
+ debounceMs: number;
3
+ /**
4
+ * Which chunks of each period to emit:
5
+ * - `"BOTH"` (the default): the first chunk straight away, and the most
6
+ * recent chunk at the end of the period, if there was another.
7
+ * - `"LEADING"`: only the first chunk, straight away.
8
+ * - `"TRAILING"`: only the most recent chunk, at the end of the period.
9
+ */
10
+ mode?: "LEADING" | "TRAILING" | "BOTH";
11
+ /**
12
+ * Extend the period each time a chunk is written, so it only ends once no
13
+ * chunks have been written for `debounceMs`.
14
+ *
15
+ * @default false
16
+ */
17
+ restartTimerOnChunk?: boolean;
18
+ }
19
+ /**
20
+ * Emit at most one chunk every `debounceMs` milliseconds, dropping the rest.
21
+ *
22
+ * - A period starts when a chunk is written and nothing has been emitted in
23
+ * the last `debounceMs`. Emitting a trailing chunk starts a new period.
24
+ * - When the writable side closes, a trailing chunk that is waiting is
25
+ * emitted straight away.
26
+ * - Writes never wait for the output to be read. If the output isn't read
27
+ * before the next chunk is emitted, only the most recent one is kept.
28
+ */
29
+ export default class DebounceStream<TChunk> implements TransformStream<TChunk, TChunk> {
30
+ readonly readable: ReadableStream<TChunk>;
31
+ readonly writable: WritableStream<TChunk>;
32
+ constructor({ debounceMs, mode, restartTimerOnChunk }: DebounceStreamOptions);
33
+ }
@@ -0,0 +1,102 @@
1
+ // src/DebounceStream.ts
2
+ /**
3
+ * Emit at most one chunk every `debounceMs` milliseconds, dropping the rest.
4
+ *
5
+ * - A period starts when a chunk is written and nothing has been emitted in
6
+ * the last `debounceMs`. Emitting a trailing chunk starts a new period.
7
+ * - When the writable side closes, a trailing chunk that is waiting is
8
+ * emitted straight away.
9
+ * - Writes never wait for the output to be read. If the output isn't read
10
+ * before the next chunk is emitted, only the most recent one is kept.
11
+ */
12
+ var DebounceStream = class {
13
+ readable;
14
+ writable;
15
+ constructor({ debounceMs, mode = "BOTH", restartTimerOnChunk = false }) {
16
+ if (!(debounceMs >= 0)) throw new RangeError(`debounceMs must be a number >= 0, but got ${debounceMs}`);
17
+ if (mode !== "LEADING" && mode !== "TRAILING" && mode !== "BOTH") throw new TypeError(`mode must be "LEADING", "TRAILING" or "BOTH", but got ${mode}`);
18
+ const leading = mode !== "TRAILING";
19
+ const trailing = mode !== "LEADING";
20
+ let readableController;
21
+ let writableController;
22
+ let timer;
23
+ let periodEnd = 0;
24
+ let hasTrailing = false;
25
+ let trailingChunk;
26
+ let hasOutput = false;
27
+ let outputChunk;
28
+ let isReadWaiting = false;
29
+ const emit = (chunk) => {
30
+ if (isReadWaiting) {
31
+ isReadWaiting = false;
32
+ readableController.enqueue(chunk);
33
+ } else {
34
+ hasOutput = true;
35
+ outputChunk = chunk;
36
+ }
37
+ };
38
+ const startPeriod = () => {
39
+ if (restartTimerOnChunk) periodEnd = performance.now() + debounceMs;
40
+ timer = setTimeout(endPeriod, debounceMs);
41
+ };
42
+ const endPeriod = () => {
43
+ if (restartTimerOnChunk) {
44
+ const remaining = periodEnd - performance.now();
45
+ if (remaining > 0) {
46
+ timer = setTimeout(endPeriod, remaining);
47
+ return;
48
+ }
49
+ }
50
+ timer = void 0;
51
+ if (!hasTrailing) return;
52
+ const chunk = trailingChunk;
53
+ hasTrailing = false;
54
+ trailingChunk = void 0;
55
+ emit(chunk);
56
+ startPeriod();
57
+ };
58
+ this.readable = new ReadableStream({
59
+ start(c) {
60
+ readableController = c;
61
+ },
62
+ pull() {
63
+ if (hasOutput) {
64
+ const chunk = outputChunk;
65
+ hasOutput = false;
66
+ outputChunk = void 0;
67
+ readableController.enqueue(chunk);
68
+ } else isReadWaiting = true;
69
+ },
70
+ cancel(reason) {
71
+ clearTimeout(timer);
72
+ writableController.error(reason);
73
+ }
74
+ }, { highWaterMark: 0 });
75
+ this.writable = new WritableStream({
76
+ start(c) {
77
+ writableController = c;
78
+ },
79
+ write(chunk) {
80
+ if (timer === void 0) {
81
+ startPeriod();
82
+ if (leading) return emit(chunk);
83
+ } else if (restartTimerOnChunk) periodEnd = performance.now() + debounceMs;
84
+ if (trailing) {
85
+ hasTrailing = true;
86
+ trailingChunk = chunk;
87
+ }
88
+ },
89
+ close() {
90
+ if (hasTrailing) emit(trailingChunk);
91
+ if (hasOutput) readableController.enqueue(outputChunk);
92
+ clearTimeout(timer);
93
+ readableController.close();
94
+ },
95
+ abort(reason) {
96
+ clearTimeout(timer);
97
+ readableController.error(reason);
98
+ }
99
+ });
100
+ }
101
+ };
102
+ export { DebounceStream as default };
@@ -0,0 +1,44 @@
1
+ import TransformStreamWithCancel from "./TransformStreamWithCancel.mjs";
2
+ /**
3
+ * Choose the timeout, in milliseconds, each time a chunk is written.
4
+ *
5
+ * @param remainingMs - How long was left of the previous timeout, or 0 when
6
+ * choosing the first timeout, which starts when the stream is created.
7
+ * @param chunk - The chunk that was just written, or `undefined` when choosing
8
+ * the first timeout.
9
+ */
10
+ export type TimeoutGetter<TChunk> = (remainingMs: number, chunk?: TChunk) => number;
11
+ export interface TimeoutStreamOptions<TChunk> {
12
+ /**
13
+ * How long to wait for the next chunk, in milliseconds, or a function that
14
+ * chooses it each time a chunk is written.
15
+ */
16
+ timeoutMs: number | TimeoutGetter<TChunk>;
17
+ /**
18
+ * Called when the timeout is reached. By default, the stream is errored with
19
+ * a `TimeoutStreamError`. You could instead error it with your own error,
20
+ * end it with `controller.terminate()`, or even enqueue a chunk. If the
21
+ * stream isn't errored or terminated, the timeout starts again when the
22
+ * next chunk is written. If this function throws, the stream is errored.
23
+ */
24
+ onTimeout?: (controller: TransformStreamDefaultController<TChunk>) => void;
25
+ }
26
+ /**
27
+ * The error a `TimeoutStream` is errored with by default
28
+ */
29
+ export declare class TimeoutStreamError extends Error {
30
+ readonly code = "TIMEOUT_STREAM_TIMEOUT";
31
+ constructor(timeoutMs: number);
32
+ }
33
+ /**
34
+ * Pass chunks through unchanged, erroring the stream if no chunk is written
35
+ * for `timeoutMs` milliseconds. The timeout starts when the stream is created,
36
+ * and is stopped when the stream finishes.
37
+ *
38
+ * Chunks are only written when the output has room for them, so if the output
39
+ * is read slowly (e.g. a slow destination in a pipeline), that can cause a
40
+ * timeout too.
41
+ */
42
+ export default class TimeoutStream<TChunk> extends TransformStreamWithCancel<TChunk, TChunk> {
43
+ constructor({ timeoutMs, onTimeout }: TimeoutStreamOptions<TChunk>);
44
+ }
@@ -0,0 +1,94 @@
1
+ import TransformStreamWithCancel from "./TransformStreamWithCancel.mjs";
2
+ // src/TimeoutStream.ts
3
+ /**
4
+ * The error a `TimeoutStream` is errored with by default
5
+ */
6
+ var TimeoutStreamError = class extends Error {
7
+ code = "TIMEOUT_STREAM_TIMEOUT";
8
+ constructor(timeoutMs) {
9
+ super(`TimeoutStream: no chunk was received for ${Math.round(timeoutMs)}ms.`);
10
+ this.name = "TimeoutStreamError";
11
+ }
12
+ };
13
+ /**
14
+ * Pass chunks through unchanged, erroring the stream if no chunk is written
15
+ * for `timeoutMs` milliseconds. The timeout starts when the stream is created,
16
+ * and is stopped when the stream finishes.
17
+ *
18
+ * Chunks are only written when the output has room for them, so if the output
19
+ * is read slowly (e.g. a slow destination in a pipeline), that can cause a
20
+ * timeout too.
21
+ */
22
+ var TimeoutStream = class extends TransformStreamWithCancel {
23
+ constructor({ timeoutMs, onTimeout }) {
24
+ const getTimeout = typeof timeoutMs === "function" ? timeoutMs : void 0;
25
+ const fixedTimeoutMs = getTimeout ? 0 : timeoutMs;
26
+ if (!getTimeout) checkTimeout(fixedTimeoutMs);
27
+ let controller;
28
+ let timer;
29
+ let deadline = 0;
30
+ let timerDue = 0;
31
+ let currentTimeoutMs = 0;
32
+ const startTimer = (now) => {
33
+ timerDue = deadline;
34
+ timer = setTimeout(onTimer, deadline - now);
35
+ };
36
+ const onTimer = () => {
37
+ const now = performance.now();
38
+ if (deadline > now) return startTimer(now);
39
+ timer = void 0;
40
+ try {
41
+ if (onTimeout) onTimeout(controller);
42
+ else controller.error(new TimeoutStreamError(currentTimeoutMs));
43
+ } catch (err) {
44
+ controller.error(err);
45
+ }
46
+ };
47
+ const stopTimer = () => {
48
+ clearTimeout(timer);
49
+ timer = void 0;
50
+ deadline = 1e400;
51
+ };
52
+ super({
53
+ start(c) {
54
+ controller = c;
55
+ const now = performance.now();
56
+ currentTimeoutMs = getTimeout ? checkTimeout(getTimeout(0)) : fixedTimeoutMs;
57
+ deadline = now + currentTimeoutMs;
58
+ startTimer(now);
59
+ },
60
+ transform: getTimeout ? (chunk, controller) => {
61
+ if (deadline !== 1e400) {
62
+ const now = performance.now();
63
+ try {
64
+ currentTimeoutMs = checkTimeout(getTimeout(Math.max(0, deadline - now), chunk));
65
+ } catch (err) {
66
+ stopTimer();
67
+ throw err;
68
+ }
69
+ deadline = now + currentTimeoutMs;
70
+ if (timer === void 0) startTimer(now);
71
+ else if (deadline < timerDue) {
72
+ clearTimeout(timer);
73
+ startTimer(now);
74
+ }
75
+ }
76
+ controller.enqueue(chunk);
77
+ } : (chunk, controller) => {
78
+ if (deadline !== 1e400) {
79
+ const now = performance.now();
80
+ deadline = now + fixedTimeoutMs;
81
+ if (timer === void 0) startTimer(now);
82
+ }
83
+ controller.enqueue(chunk);
84
+ },
85
+ flush: stopTimer,
86
+ cancel: stopTimer
87
+ }, void 0, { highWaterMark: 1 });
88
+ }
89
+ };
90
+ function checkTimeout(timeoutMs) {
91
+ if (!(timeoutMs >= 0)) throw new RangeError(`TimeoutStream: timeoutMs must be a number >= 0, but got ${timeoutMs}`);
92
+ return timeoutMs;
93
+ }
94
+ export { TimeoutStreamError, TimeoutStream as default };
@@ -0,0 +1,48 @@
1
+ /**
2
+ * A `Transformer`, as passed to `new TransformStream()`, including the
3
+ * `cancel` method, which TypeScript's DOM types don't include yet.
4
+ */
5
+ export interface TransformerWithCancel<I = any, O = any> {
6
+ start?: (controller: TransformStreamDefaultController<O>) => any;
7
+ transform?: (chunk: I, controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
8
+ flush?: (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
9
+ /**
10
+ * Called when the readable side is cancelled, or the writable side is
11
+ * aborted, with the reason.
12
+ */
13
+ cancel?: (reason: any) => void | PromiseLike<void>;
14
+ readableType?: undefined;
15
+ writableType?: undefined;
16
+ }
17
+ export interface TransformStreamWithCancelConstructor {
18
+ new <I = any, O = any>(transformer?: TransformerWithCancel<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>): TransformStream<I, O>;
19
+ }
20
+ /**
21
+ * Whether this runtime's `TransformStream` calls the transformer's `cancel`
22
+ * method. The constructor only reads the transformer properties it knows
23
+ * about, so we can check without creating any streams other than this one.
24
+ */
25
+ export declare const supportsTransformerCancel: boolean;
26
+ /**
27
+ * A `TransformStream` that calls the transformer's `cancel` method, built
28
+ * from a `ReadableStream` and a `WritableStream`, following the algorithms in
29
+ * the Streams standard. `TransformStreamWithCancel` is this class in runtimes
30
+ * whose `TransformStream` doesn't call `cancel`. Prefer using
31
+ * `TransformStreamWithCancel`, unless you specifically need the polyfill.
32
+ *
33
+ * Unlike a native `TransformStream`, `instanceof TransformStream` is false.
34
+ */
35
+ export declare class TransformStreamWithCancelPolyfill<I = any, O = any> implements TransformStream<I, O> {
36
+ readonly readable: ReadableStream<O>;
37
+ readonly writable: WritableStream<I>;
38
+ constructor(transformer?: TransformerWithCancel<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);
39
+ }
40
+ /**
41
+ * A `TransformStream` that calls the transformer's `cancel` method when the
42
+ * readable side is cancelled or the writable side is aborted, even in
43
+ * runtimes whose `TransformStream` doesn't support `cancel` yet. In runtimes
44
+ * that do, this is just `TransformStream`.
45
+ */
46
+ declare const TransformStreamWithCancel: TransformStreamWithCancelConstructor;
47
+ type TransformStreamWithCancel<I = any, O = any> = TransformStream<I, O>;
48
+ export { TransformStreamWithCancel as default };
@@ -0,0 +1,197 @@
1
+ import { t as isPromiseLike } from "./isPromiseLike-SjGgF7zP.mjs";
2
+ // src/TransformStreamWithCancel.ts
3
+ /**
4
+ * Whether this runtime's `TransformStream` calls the transformer's `cancel`
5
+ * method. The constructor only reads the transformer properties it knows
6
+ * about, so we can check without creating any streams other than this one.
7
+ */
8
+ const supportsTransformerCancel = (() => {
9
+ let supported = false;
10
+ try {
11
+ new TransformStream({ get cancel() {
12
+ supported = true;
13
+ } });
14
+ } catch {}
15
+ return supported;
16
+ })();
17
+ const resolved = Promise.resolve();
18
+ /**
19
+ * A `TransformStream` that calls the transformer's `cancel` method, built
20
+ * from a `ReadableStream` and a `WritableStream`, following the algorithms in
21
+ * the Streams standard. `TransformStreamWithCancel` is this class in runtimes
22
+ * whose `TransformStream` doesn't call `cancel`. Prefer using
23
+ * `TransformStreamWithCancel`, unless you specifically need the polyfill.
24
+ *
25
+ * Unlike a native `TransformStream`, `instanceof TransformStream` is false.
26
+ */
27
+ var TransformStreamWithCancelPolyfill = class {
28
+ readable;
29
+ writable;
30
+ constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
31
+ if (transformer.readableType !== void 0) throw new RangeError("Invalid readableType specified");
32
+ if (transformer.writableType !== void 0) throw new RangeError("Invalid writableType specified");
33
+ const { start, transform, flush, cancel } = transformer;
34
+ let readableController;
35
+ let writableController;
36
+ let readableOpen = true;
37
+ let readableCancelled = false;
38
+ let readableErrored = false;
39
+ let readableError;
40
+ let writableErrored = false;
41
+ let writableError;
42
+ let backpressure = true;
43
+ let releaseWrite;
44
+ const releaseBackpressure = () => {
45
+ backpressure = false;
46
+ if (releaseWrite !== void 0) {
47
+ const release = releaseWrite;
48
+ releaseWrite = void 0;
49
+ release();
50
+ }
51
+ };
52
+ let finishPromise;
53
+ const errorReadable = (reason) => {
54
+ if (readableErrored || readableCancelled) return;
55
+ readableOpen = false;
56
+ readableController.error(reason);
57
+ if (readableController.desiredSize === null) {
58
+ readableErrored = true;
59
+ readableError = reason;
60
+ }
61
+ };
62
+ const errorWritableAndUnblockWrite = (reason) => {
63
+ if (!writableErrored) {
64
+ writableErrored = true;
65
+ writableError = reason;
66
+ writableController.error(reason);
67
+ }
68
+ if (backpressure) releaseBackpressure();
69
+ };
70
+ const errorStream = (reason) => {
71
+ errorReadable(reason);
72
+ errorWritableAndUnblockWrite(reason);
73
+ };
74
+ const controller = {
75
+ get desiredSize() {
76
+ return readableController.desiredSize;
77
+ },
78
+ enqueue(chunk) {
79
+ if (!readableOpen) throw new TypeError("Readable side is not in a state that permits enqueue");
80
+ try {
81
+ readableController.enqueue(chunk);
82
+ } catch (err) {
83
+ errorWritableAndUnblockWrite(err);
84
+ throw err;
85
+ }
86
+ if (!(readableController.desiredSize > 0)) backpressure = true;
87
+ },
88
+ error(reason) {
89
+ errorStream(reason);
90
+ },
91
+ terminate() {
92
+ if (readableOpen) {
93
+ readableOpen = false;
94
+ readableController.close();
95
+ }
96
+ errorWritableAndUnblockWrite(/* @__PURE__ */ new TypeError("TransformStream terminated"));
97
+ }
98
+ };
99
+ const performTransform = transform ? (chunk) => {
100
+ try {
101
+ const result = transform.call(transformer, chunk, controller);
102
+ if (isPromiseLike(result)) return Promise.resolve(result).then(void 0, (err) => {
103
+ errorStream(err);
104
+ throw err;
105
+ });
106
+ } catch (err) {
107
+ errorStream(err);
108
+ throw err;
109
+ }
110
+ } : (chunk) => {
111
+ controller.enqueue(chunk);
112
+ };
113
+ const call = (fn, arg) => {
114
+ if (fn === void 0) return resolved;
115
+ try {
116
+ return Promise.resolve(fn.call(transformer, arg));
117
+ } catch (err) {
118
+ return Promise.reject(err);
119
+ }
120
+ };
121
+ let resolveStart;
122
+ const startPromise = new Promise((resolve) => resolveStart = resolve);
123
+ this.writable = new WritableStream({
124
+ start(c) {
125
+ writableController = c;
126
+ return startPromise;
127
+ },
128
+ write(chunk) {
129
+ if (!backpressure) return performTransform(chunk);
130
+ return new Promise((resolve) => releaseWrite = resolve).then(() => {
131
+ if (writableErrored) throw writableError;
132
+ const signal = writableController.signal;
133
+ if (signal?.aborted) throw signal.reason;
134
+ return performTransform(chunk);
135
+ });
136
+ },
137
+ close() {
138
+ if (finishPromise) return finishPromise;
139
+ return finishPromise = call(flush, controller).then(() => {
140
+ if (readableErrored) throw readableError;
141
+ if (readableOpen) {
142
+ readableOpen = false;
143
+ readableController.close();
144
+ }
145
+ }, (err) => {
146
+ errorReadable(err);
147
+ throw err;
148
+ });
149
+ },
150
+ abort(reason) {
151
+ if (finishPromise) return finishPromise;
152
+ writableErrored = true;
153
+ writableError = reason;
154
+ return finishPromise = call(cancel, reason).then(() => {
155
+ if (readableErrored) throw readableError;
156
+ errorReadable(reason);
157
+ }, (err) => {
158
+ errorReadable(err);
159
+ throw err;
160
+ });
161
+ }
162
+ }, writableStrategy);
163
+ this.readable = new ReadableStream({
164
+ start(c) {
165
+ readableController = c;
166
+ return startPromise;
167
+ },
168
+ pull() {
169
+ releaseBackpressure();
170
+ },
171
+ cancel(reason) {
172
+ readableOpen = false;
173
+ readableCancelled = true;
174
+ if (finishPromise) return finishPromise;
175
+ return finishPromise = call(cancel, reason).then(() => {
176
+ if (writableErrored) throw writableError;
177
+ errorWritableAndUnblockWrite(reason);
178
+ }, (err) => {
179
+ errorWritableAndUnblockWrite(err);
180
+ throw err;
181
+ });
182
+ }
183
+ }, {
184
+ highWaterMark: readableStrategy.highWaterMark ?? 0,
185
+ size: readableStrategy.size
186
+ });
187
+ resolveStart(start?.call(transformer, controller));
188
+ }
189
+ };
190
+ /**
191
+ * A `TransformStream` that calls the transformer's `cancel` method when the
192
+ * readable side is cancelled or the writable side is aborted, even in
193
+ * runtimes whose `TransformStream` doesn't support `cancel` yet. In runtimes
194
+ * that do, this is just `TransformStream`.
195
+ */
196
+ const TransformStreamWithCancel = supportsTransformerCancel ? TransformStream : TransformStreamWithCancelPolyfill;
197
+ export { TransformStreamWithCancelPolyfill, TransformStreamWithCancel as default, supportsTransformerCancel };
package/package.json CHANGED
@@ -1,9 +1,13 @@
1
1
  {
2
2
  "name": "web-utility-streams",
3
- "version": "0.1.1",
3
+ "version": "1.0.0-canary-1",
4
4
  "description": "Various utility streams that are very useful for working with web streams.",
5
5
  "type": "module",
6
6
  "exports": {
7
+ "./AddPrefixStream": {
8
+ "types": "./lib/AddPrefixStream.d.mts",
9
+ "default": "./lib/AddPrefixStream.mjs"
10
+ },
7
11
  "./ConcatStream": {
8
12
  "types": "./lib/ConcatStream.d.mts",
9
13
  "default": "./lib/ConcatStream.mjs"
@@ -12,6 +16,10 @@
12
16
  "types": "./lib/consumers.d.mts",
13
17
  "default": "./lib/consumers.mjs"
14
18
  },
19
+ "./DebounceStream": {
20
+ "types": "./lib/DebounceStream.d.mts",
21
+ "default": "./lib/DebounceStream.mjs"
22
+ },
15
23
  "./DebugStream": {
16
24
  "types": "./lib/DebugStream.d.mts",
17
25
  "default": "./lib/DebugStream.mjs"
@@ -76,10 +84,18 @@
76
84
  "types": "./lib/SplitLinesStream.d.mts",
77
85
  "default": "./lib/SplitLinesStream.mjs"
78
86
  },
87
+ "./TimeoutStream": {
88
+ "types": "./lib/TimeoutStream.d.mts",
89
+ "default": "./lib/TimeoutStream.mjs"
90
+ },
79
91
  "./TransformPipelineStream": {
80
92
  "types": "./lib/TransformPipelineStream.d.mts",
81
93
  "default": "./lib/TransformPipelineStream.mjs"
82
94
  },
95
+ "./TransformStreamWithCancel": {
96
+ "types": "./lib/TransformStreamWithCancel.d.mts",
97
+ "default": "./lib/TransformStreamWithCancel.mjs"
98
+ },
83
99
  "./UnionStream": {
84
100
  "types": "./lib/UnionStream.d.mts",
85
101
  "default": "./lib/UnionStream.mjs"