@yume-chan/stream-extra 0.0.0-20240714132542

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.
Files changed (106) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/LICENSE +21 -0
  3. package/README.md +43 -0
  4. package/esm/buffered-transform.d.ts +11 -0
  5. package/esm/buffered-transform.d.ts.map +1 -0
  6. package/esm/buffered-transform.js +57 -0
  7. package/esm/buffered-transform.js.map +1 -0
  8. package/esm/buffered.d.ts +23 -0
  9. package/esm/buffered.d.ts.map +1 -0
  10. package/esm/buffered.js +138 -0
  11. package/esm/buffered.js.map +1 -0
  12. package/esm/concat.d.ts +36 -0
  13. package/esm/concat.d.ts.map +1 -0
  14. package/esm/concat.js +130 -0
  15. package/esm/concat.js.map +1 -0
  16. package/esm/consumable.d.ts +40 -0
  17. package/esm/consumable.d.ts.map +1 -0
  18. package/esm/consumable.js +130 -0
  19. package/esm/consumable.js.map +1 -0
  20. package/esm/distribution.d.ts +22 -0
  21. package/esm/distribution.d.ts.map +1 -0
  22. package/esm/distribution.js +103 -0
  23. package/esm/distribution.js.map +1 -0
  24. package/esm/duplex.d.ts +45 -0
  25. package/esm/duplex.d.ts.map +1 -0
  26. package/esm/duplex.js +93 -0
  27. package/esm/duplex.js.map +1 -0
  28. package/esm/encoding.d.ts +21 -0
  29. package/esm/encoding.d.ts.map +1 -0
  30. package/esm/encoding.js +4 -0
  31. package/esm/encoding.js.map +1 -0
  32. package/esm/index.d.ts +19 -0
  33. package/esm/index.d.ts.map +1 -0
  34. package/esm/index.js +19 -0
  35. package/esm/index.js.map +1 -0
  36. package/esm/inspect.d.ts +5 -0
  37. package/esm/inspect.d.ts.map +1 -0
  38. package/esm/inspect.js +12 -0
  39. package/esm/inspect.js.map +1 -0
  40. package/esm/maybe-consumable.d.ts +21 -0
  41. package/esm/maybe-consumable.d.ts.map +1 -0
  42. package/esm/maybe-consumable.js +62 -0
  43. package/esm/maybe-consumable.js.map +1 -0
  44. package/esm/pipe-from.d.ts +13 -0
  45. package/esm/pipe-from.d.ts.map +1 -0
  46. package/esm/pipe-from.js +24 -0
  47. package/esm/pipe-from.js.map +1 -0
  48. package/esm/push-readable.d.ts +35 -0
  49. package/esm/push-readable.d.ts.map +1 -0
  50. package/esm/push-readable.js +240 -0
  51. package/esm/push-readable.js.map +1 -0
  52. package/esm/split-string.d.ts +5 -0
  53. package/esm/split-string.d.ts.map +1 -0
  54. package/esm/split-string.js +25 -0
  55. package/esm/split-string.js.map +1 -0
  56. package/esm/stream.d.ts +25 -0
  57. package/esm/stream.d.ts.map +1 -0
  58. package/esm/stream.js +7 -0
  59. package/esm/stream.js.map +1 -0
  60. package/esm/struct-deserialize.d.ts +7 -0
  61. package/esm/struct-deserialize.d.ts.map +1 -0
  62. package/esm/struct-deserialize.js +9 -0
  63. package/esm/struct-deserialize.js.map +1 -0
  64. package/esm/struct-serialize.d.ts +6 -0
  65. package/esm/struct-serialize.d.ts.map +1 -0
  66. package/esm/struct-serialize.js +11 -0
  67. package/esm/struct-serialize.js.map +1 -0
  68. package/esm/task.d.ts +5 -0
  69. package/esm/task.d.ts.map +1 -0
  70. package/esm/task.js +9 -0
  71. package/esm/task.js.map +1 -0
  72. package/esm/types.d.ts +777 -0
  73. package/esm/types.d.ts.map +1 -0
  74. package/esm/types.js +3 -0
  75. package/esm/types.js.map +1 -0
  76. package/esm/wrap-readable.d.ts +22 -0
  77. package/esm/wrap-readable.d.ts.map +1 -0
  78. package/esm/wrap-readable.js +57 -0
  79. package/esm/wrap-readable.js.map +1 -0
  80. package/esm/wrap-writable.d.ts +15 -0
  81. package/esm/wrap-writable.d.ts.map +1 -0
  82. package/esm/wrap-writable.js +63 -0
  83. package/esm/wrap-writable.js.map +1 -0
  84. package/package.json +48 -0
  85. package/src/buffered-transform.ts +71 -0
  86. package/src/buffered.ts +160 -0
  87. package/src/concat.ts +162 -0
  88. package/src/consumable.ts +205 -0
  89. package/src/distribution.ts +123 -0
  90. package/src/duplex.ts +146 -0
  91. package/src/encoding.ts +39 -0
  92. package/src/index.ts +18 -0
  93. package/src/inspect.ts +12 -0
  94. package/src/maybe-consumable.ts +101 -0
  95. package/src/pipe-from.ts +28 -0
  96. package/src/push-readable.ts +307 -0
  97. package/src/split-string.ts +32 -0
  98. package/src/stream.ts +46 -0
  99. package/src/struct-deserialize.ts +14 -0
  100. package/src/struct-serialize.ts +15 -0
  101. package/src/task.ts +21 -0
  102. package/src/types.ts +881 -0
  103. package/src/wrap-readable.ts +93 -0
  104. package/src/wrap-writable.ts +88 -0
  105. package/tsconfig.build.json +8 -0
  106. package/tsconfig.build.tsbuildinfo +1 -0
@@ -0,0 +1,307 @@
1
+ import { PromiseResolver } from "@yume-chan/async";
2
+
3
+ import type { AbortSignal, QueuingStrategy } from "./stream.js";
4
+ import { AbortController, ReadableStream } from "./stream.js";
5
+
6
+ export interface PushReadableStreamController<T> {
7
+ abortSignal: AbortSignal;
8
+
9
+ enqueue(chunk: T): Promise<void>;
10
+
11
+ close(): void;
12
+
13
+ error(e?: unknown): void;
14
+ }
15
+
16
+ export type PushReadableStreamSource<T> = (
17
+ controller: PushReadableStreamController<T>,
18
+ ) => void | Promise<void>;
19
+
20
+ export type PushReadableLogger<T> = (
21
+ event:
22
+ | {
23
+ source: "producer";
24
+ operation: "enqueue";
25
+ value: T;
26
+ phase: "start" | "waiting" | "ignored" | "complete";
27
+ }
28
+ | {
29
+ source: "producer";
30
+ operation: "close" | "error";
31
+ explicit: boolean;
32
+ phase: "start" | "ignored" | "complete";
33
+ }
34
+ | {
35
+ source: "consumer";
36
+ operation: "pull" | "cancel";
37
+ phase: "start" | "complete";
38
+ },
39
+ ) => void;
40
+
41
+ export class PushReadableStream<T> extends ReadableStream<T> {
42
+ /**
43
+ * Create a new `PushReadableStream` from a source.
44
+ *
45
+ * @param source If `source` returns a `Promise`, the stream will be closed
46
+ * when the `Promise` is resolved, and be errored when the `Promise` is rejected.
47
+ * @param strategy
48
+ */
49
+ constructor(
50
+ source: PushReadableStreamSource<T>,
51
+ strategy?: QueuingStrategy<T>,
52
+ logger?: PushReadableLogger<T>,
53
+ ) {
54
+ let waterMarkLow: PromiseResolver<void> | undefined;
55
+ let zeroHighWaterMarkAllowEnqueue = false;
56
+ const abortController = new AbortController();
57
+
58
+ super(
59
+ {
60
+ start: (controller) => {
61
+ const result = source({
62
+ abortSignal: abortController.signal,
63
+ enqueue: async (chunk) => {
64
+ logger?.({
65
+ source: "producer",
66
+ operation: "enqueue",
67
+ value: chunk,
68
+ phase: "start",
69
+ });
70
+
71
+ if (abortController.signal.aborted) {
72
+ // In original `ReadableStream`, calling `enqueue` or `close`
73
+ // on an cancelled stream will throw an error,
74
+ //
75
+ // But in `PushReadableStream`, `enqueue` is an async function,
76
+ // the producer can't just check `abortSignal.aborted`
77
+ // before calling `enqueue`, as it might change when waiting
78
+ // for the backpressure to be resolved.
79
+ //
80
+ // So IMO it's better to handle this for the producer
81
+ // by simply ignoring the `enqueue` call.
82
+ //
83
+ // Note that we check `abortSignal.aborted` instead of `stopped`,
84
+ // as it's not allowed for the producer to call `enqueue` after
85
+ // they called `close` or `error`.
86
+ //
87
+ // Obviously, the producer should listen to the `abortSignal` and
88
+ // stop producing, but most pushing data sources can't be stopped.
89
+ logger?.({
90
+ source: "producer",
91
+ operation: "enqueue",
92
+ value: chunk,
93
+ phase: "ignored",
94
+ });
95
+ return;
96
+ }
97
+
98
+ if (controller.desiredSize === null) {
99
+ // `desiredSize` being `null` means the stream is in error state,
100
+ // `controller.enqueue` will throw an error for us.
101
+ controller.enqueue(chunk);
102
+ // istanbul ignore next
103
+ return;
104
+ }
105
+
106
+ if (zeroHighWaterMarkAllowEnqueue) {
107
+ // When `highWaterMark` is set to `0`,
108
+ // `controller.desiredSize` will always be `0`,
109
+ // even if the consumer has called `reader.read()`.
110
+ // (in this case, each `reader.read()`/`pull`
111
+ // should allow one `enqueue` of any size)
112
+ //
113
+ // If the consumer has already called `reader.read()`,
114
+ // before the producer tries to `enqueue`,
115
+ // `controller.desiredSize` is `0` and normal `waterMarkLow` signal
116
+ // will never trigger,
117
+ // (because `ReadableStream` prevents reentrance of `pull`)
118
+ // The stream will stuck.
119
+ //
120
+ // So we need a special signal for this case.
121
+ zeroHighWaterMarkAllowEnqueue = false;
122
+ controller.enqueue(chunk);
123
+ logger?.({
124
+ source: "producer",
125
+ operation: "enqueue",
126
+ value: chunk,
127
+ phase: "complete",
128
+ });
129
+ return;
130
+ }
131
+
132
+ if (controller.desiredSize <= 0) {
133
+ logger?.({
134
+ source: "producer",
135
+ operation: "enqueue",
136
+ value: chunk,
137
+ phase: "waiting",
138
+ });
139
+
140
+ waterMarkLow = new PromiseResolver<void>();
141
+ await waterMarkLow.promise;
142
+
143
+ // Recheck consumer cancellation after async operations.
144
+ if (abortController.signal.aborted) {
145
+ logger?.({
146
+ source: "producer",
147
+ operation: "enqueue",
148
+ value: chunk,
149
+ phase: "ignored",
150
+ });
151
+ return;
152
+ }
153
+ }
154
+
155
+ controller.enqueue(chunk);
156
+ logger?.({
157
+ source: "producer",
158
+ operation: "enqueue",
159
+ value: chunk,
160
+ phase: "complete",
161
+ });
162
+ },
163
+ close() {
164
+ logger?.({
165
+ source: "producer",
166
+ operation: "close",
167
+ explicit: true,
168
+ phase: "start",
169
+ });
170
+
171
+ // Since `enqueue` on an cancelled stream won't throw an error,
172
+ // so does `close`.
173
+ if (abortController.signal.aborted) {
174
+ logger?.({
175
+ source: "producer",
176
+ operation: "close",
177
+ explicit: true,
178
+ phase: "ignored",
179
+ });
180
+ return;
181
+ }
182
+
183
+ controller.close();
184
+ logger?.({
185
+ source: "producer",
186
+ operation: "close",
187
+ explicit: true,
188
+ phase: "complete",
189
+ });
190
+ },
191
+ error(e) {
192
+ logger?.({
193
+ source: "producer",
194
+ operation: "error",
195
+ explicit: true,
196
+ phase: "start",
197
+ });
198
+
199
+ // Calling `error` on an already closed or errored stream is a no-op.
200
+ controller.error(e);
201
+
202
+ logger?.({
203
+ source: "producer",
204
+ operation: "error",
205
+ explicit: true,
206
+ phase: "complete",
207
+ });
208
+ },
209
+ });
210
+
211
+ if (result && "then" in result) {
212
+ // If `source` returns a `Promise`,
213
+ // close the stream when the `Promise` is resolved,
214
+ // and error the stream when the `Promise` is rejected.
215
+ // The producer can return a never-settling `Promise`
216
+ // to disable this behavior.
217
+ result.then(
218
+ () => {
219
+ logger?.({
220
+ source: "producer",
221
+ operation: "close",
222
+ explicit: false,
223
+ phase: "start",
224
+ });
225
+
226
+ try {
227
+ controller.close();
228
+
229
+ logger?.({
230
+ source: "producer",
231
+ operation: "close",
232
+ explicit: false,
233
+ phase: "complete",
234
+ });
235
+ } catch {
236
+ logger?.({
237
+ source: "producer",
238
+ operation: "close",
239
+ explicit: false,
240
+ phase: "ignored",
241
+ });
242
+
243
+ // The stream is already closed by the producer,
244
+ // Or cancelled by the consumer.
245
+ }
246
+ },
247
+ (e) => {
248
+ logger?.({
249
+ source: "producer",
250
+ operation: "error",
251
+ explicit: false,
252
+ phase: "start",
253
+ });
254
+
255
+ controller.error(e);
256
+
257
+ logger?.({
258
+ source: "producer",
259
+ operation: "error",
260
+ explicit: false,
261
+ phase: "complete",
262
+ });
263
+ },
264
+ );
265
+ }
266
+ },
267
+ pull: () => {
268
+ logger?.({
269
+ source: "consumer",
270
+ operation: "pull",
271
+ phase: "start",
272
+ });
273
+
274
+ if (waterMarkLow) {
275
+ waterMarkLow.resolve();
276
+ } else if (strategy?.highWaterMark === 0) {
277
+ zeroHighWaterMarkAllowEnqueue = true;
278
+ }
279
+
280
+ logger?.({
281
+ source: "consumer",
282
+ operation: "pull",
283
+ phase: "complete",
284
+ });
285
+ },
286
+ cancel: (reason) => {
287
+ logger?.({
288
+ source: "consumer",
289
+ operation: "cancel",
290
+ phase: "start",
291
+ });
292
+
293
+ abortController.abort(reason);
294
+ // Resolve it on cancellation. `pull` will check `abortSignal.aborted` again.
295
+ waterMarkLow?.resolve();
296
+
297
+ logger?.({
298
+ source: "consumer",
299
+ operation: "cancel",
300
+ phase: "complete",
301
+ });
302
+ },
303
+ },
304
+ strategy,
305
+ );
306
+ }
307
+ }
@@ -0,0 +1,32 @@
1
+ import { TransformStream } from "./stream.js";
2
+
3
+ function* split(
4
+ input: string,
5
+ separator: string,
6
+ ): Generator<string, void, void> {
7
+ let start = 0;
8
+
9
+ while (true) {
10
+ const index = input.indexOf(separator, start);
11
+ if (index === -1) {
12
+ return;
13
+ }
14
+
15
+ const part = input.substring(start, index);
16
+ yield part;
17
+
18
+ start = index + 1;
19
+ }
20
+ }
21
+
22
+ export class SplitStringStream extends TransformStream<string, string> {
23
+ constructor(separator: string) {
24
+ super({
25
+ transform(chunk, controller) {
26
+ for (const part of split(chunk, separator)) {
27
+ controller.enqueue(part);
28
+ }
29
+ },
30
+ });
31
+ }
32
+ }
package/src/stream.ts ADDED
@@ -0,0 +1,46 @@
1
+ import type {
2
+ AbortSignal,
3
+ ReadableStream as ReadableStreamType,
4
+ TransformStream as TransformStreamType,
5
+ WritableStream as WritableStreamType,
6
+ } from "./types.js";
7
+
8
+ export * from "./types.js";
9
+
10
+ /** A controller object that allows you to abort one or more DOM requests as and when desired. */
11
+ export interface AbortController {
12
+ /**
13
+ * Returns the AbortSignal object associated with this object.
14
+ */
15
+ readonly signal: AbortSignal;
16
+
17
+ /**
18
+ * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted.
19
+ */
20
+ abort(reason?: unknown): void;
21
+ }
22
+
23
+ interface AbortControllerConstructor {
24
+ prototype: AbortController;
25
+ new (): AbortController;
26
+ }
27
+
28
+ interface GlobalExtension {
29
+ AbortController: AbortControllerConstructor;
30
+ ReadableStream: typeof ReadableStreamType;
31
+ WritableStream: typeof WritableStreamType;
32
+ TransformStream: typeof TransformStreamType;
33
+ }
34
+
35
+ const Global = globalThis as unknown as GlobalExtension;
36
+
37
+ export const AbortController = Global.AbortController;
38
+
39
+ export type ReadableStream<out T> = ReadableStreamType<T>;
40
+ export const ReadableStream = Global.ReadableStream;
41
+
42
+ export type WritableStream<in T> = WritableStreamType<T>;
43
+ export const WritableStream = Global.WritableStream;
44
+
45
+ export type TransformStream<I, O> = TransformStreamType<I, O>;
46
+ export const TransformStream = Global.TransformStream;
@@ -0,0 +1,14 @@
1
+ import type Struct from "@yume-chan/struct";
2
+ import type { StructValueType } from "@yume-chan/struct";
3
+
4
+ import { BufferedTransformStream } from "./buffered-transform.js";
5
+
6
+ export class StructDeserializeStream<
7
+ T extends Struct<object, PropertyKey, object, unknown>,
8
+ > extends BufferedTransformStream<StructValueType<T>> {
9
+ constructor(struct: T) {
10
+ super((stream) => {
11
+ return struct.deserialize(stream) as never;
12
+ });
13
+ }
14
+ }
@@ -0,0 +1,15 @@
1
+ import type Struct from "@yume-chan/struct";
2
+
3
+ import { TransformStream } from "./stream.js";
4
+
5
+ export class StructSerializeStream<
6
+ T extends Struct<object, PropertyKey, object, unknown>,
7
+ > extends TransformStream<T["TInit"], Uint8Array> {
8
+ constructor(struct: T) {
9
+ super({
10
+ transform(chunk, controller) {
11
+ controller.enqueue(struct.serialize(chunk));
12
+ },
13
+ });
14
+ }
15
+ }
package/src/task.ts ADDED
@@ -0,0 +1,21 @@
1
+ export interface Task {
2
+ run<T>(callback: () => T): T;
3
+ }
4
+
5
+ interface Console {
6
+ createTask(name: string): Task;
7
+ }
8
+
9
+ interface GlobalExtension {
10
+ console?: Console;
11
+ }
12
+
13
+ // `createTask` allows browser DevTools to track the call stack across async boundaries.
14
+ const { console } = globalThis as unknown as GlobalExtension;
15
+ export const createTask: (name: string) => Task =
16
+ console?.createTask?.bind(console) ??
17
+ (() => ({
18
+ run(callback) {
19
+ return callback();
20
+ },
21
+ }));