@gjsify/stream 0.3.15 → 0.3.17

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/lib/esm/index.js CHANGED
@@ -1,1353 +1 @@
1
- import { makeCallable } from "./callable.js";
2
- import { nextTick, queueMicrotask } from "@gjsify/utils";
3
- import { EventEmitter } from "@gjsify/events";
4
-
5
- //#region src/index.ts
6
- let defaultHighWaterMark = 16384;
7
- let defaultObjectHighWaterMark = 16;
8
- function getDefaultHighWaterMark(objectMode) {
9
- return objectMode ? defaultObjectHighWaterMark : defaultHighWaterMark;
10
- }
11
- function setDefaultHighWaterMark(objectMode, value) {
12
- if (typeof value !== "number" || value < 0 || Number.isNaN(value)) {
13
- throw new TypeError(`Invalid highWaterMark: ${value}`);
14
- }
15
- if (objectMode) {
16
- defaultObjectHighWaterMark = value;
17
- } else {
18
- defaultHighWaterMark = value;
19
- }
20
- }
21
- /** Validate a named high-water-mark option and throw ERR_INVALID_ARG_VALUE on NaN/non-number. */
22
- function validateHighWaterMark(name, value) {
23
- if (value === undefined) return;
24
- if (typeof value !== "number" || Number.isNaN(value)) {
25
- const err = new TypeError(`The value of "${name}" is invalid. Received ${value}`);
26
- err.code = "ERR_INVALID_ARG_VALUE";
27
- throw err;
28
- }
29
- }
30
- var Stream_ = class extends EventEmitter {
31
- constructor(opts) {
32
- super(opts);
33
- }
34
- pipe(destination, options) {
35
- const source = this;
36
- const doEnd = options?.end !== false;
37
- let drainListenerAdded = false;
38
- const ondrain = () => {
39
- drainListenerAdded = false;
40
- destination.removeListener("drain", ondrain);
41
- if (typeof source.resume === "function") {
42
- source.resume();
43
- }
44
- };
45
- const ondata = (chunk) => {
46
- if (destination.writable) {
47
- if (destination.write(chunk) === false && typeof source.pause === "function") {
48
- source.pause();
49
- if (!drainListenerAdded) {
50
- drainListenerAdded = true;
51
- destination.on("drain", ondrain);
52
- }
53
- }
54
- }
55
- };
56
- source.on("data", ondata);
57
- let didEnd = false;
58
- const onend = () => {
59
- if (didEnd) return;
60
- didEnd = true;
61
- if (doEnd) destination.end();
62
- };
63
- const onclose = () => {
64
- if (didEnd) return;
65
- didEnd = true;
66
- if (doEnd) {
67
- if (!(source instanceof Readable) && typeof destination.destroy === "function") {
68
- destination.destroy();
69
- }
70
- }
71
- };
72
- if (doEnd) {
73
- source.on("end", onend);
74
- source.on("close", onclose);
75
- }
76
- const cleanup = () => {
77
- source.removeListener("data", ondata);
78
- if (drainListenerAdded) destination.removeListener("drain", ondrain);
79
- source.removeListener("end", onend);
80
- source.removeListener("close", onclose);
81
- source.removeListener("end", cleanup);
82
- source.removeListener("close", cleanup);
83
- destination.removeListener("close", cleanup);
84
- };
85
- source.on("end", cleanup);
86
- source.on("close", cleanup);
87
- destination.on("close", cleanup);
88
- if (source instanceof Readable) {
89
- source._pipeDests.push({
90
- dest: destination,
91
- cleanup
92
- });
93
- source._readableState.pipes.push(destination);
94
- }
95
- destination.emit("pipe", source);
96
- return destination;
97
- }
98
- };
99
- var Readable_ = class Readable_ extends Stream_ {
100
- readable = true;
101
- readableFlowing = null;
102
- readableLength = 0;
103
- readableHighWaterMark;
104
- readableEncoding;
105
- readableObjectMode;
106
- readableEnded = false;
107
- readableAborted = false;
108
- destroyed = false;
109
- /** @internal Tracked pipe destinations for unpipe. */
110
- _pipeDests = [];
111
- _buffer = [];
112
- _readableState = {
113
- ended: false,
114
- endEmitted: false,
115
- reading: false,
116
- constructed: true,
117
- highWaterMark: 0,
118
- objectMode: false,
119
- pipes: []
120
- };
121
- _readablePending = false;
122
- _readImpl;
123
- _destroyImpl;
124
- _constructImpl;
125
- constructor(opts) {
126
- super(opts);
127
- this.readableHighWaterMark = opts?.highWaterMark ?? getDefaultHighWaterMark(opts?.objectMode ?? false);
128
- this.readableEncoding = opts?.encoding ?? null;
129
- this.readableObjectMode = opts?.objectMode ?? false;
130
- this._readableState.highWaterMark = this.readableHighWaterMark;
131
- this._readableState.objectMode = this.readableObjectMode;
132
- if (opts?.read) this._readImpl = opts.read;
133
- if (opts?.destroy) this._destroyImpl = opts.destroy;
134
- if (opts?.construct) this._constructImpl = opts.construct;
135
- const hasConstruct = this._constructImpl || this._construct !== Readable.prototype._construct;
136
- if (hasConstruct) {
137
- this._readableState.constructed = false;
138
- nextTick(() => {
139
- this._construct((err) => {
140
- this._readableState.constructed = true;
141
- if (err) {
142
- this.destroy(err);
143
- } else {
144
- if (this.readableFlowing === true) {
145
- this._flow();
146
- }
147
- }
148
- });
149
- });
150
- }
151
- }
152
- _construct(callback) {
153
- if (this._constructImpl) {
154
- this._constructImpl.call(this, callback);
155
- } else {
156
- callback();
157
- }
158
- }
159
- _read(_size) {
160
- if (this._readImpl) {
161
- this._readImpl.call(this, _size);
162
- }
163
- }
164
- read(size) {
165
- if (!this._readableState.constructed) return null;
166
- if (this._buffer.length === 0) {
167
- if (this._readableState.ended) return null;
168
- this._readableState.reading = true;
169
- this._read(size ?? this.readableHighWaterMark);
170
- this._readableState.reading = false;
171
- }
172
- if (this._buffer.length === 0) return null;
173
- if (size === 0) return null;
174
- if (this.readableObjectMode) {
175
- if (size === undefined) {
176
- const chunk = this._buffer.shift();
177
- this.readableLength -= 1;
178
- if (this._readableState.ended && this._buffer.length === 0 && !this._readableState.endEmitted) {
179
- this._emitEnd();
180
- }
181
- return chunk;
182
- }
183
- if (size > this.readableLength) return null;
184
- const chunk = this._buffer.shift();
185
- this.readableLength -= 1;
186
- return chunk;
187
- }
188
- if (size !== undefined && size !== null) {
189
- if (size > this.readableLength) return null;
190
- return this._readBytes(size);
191
- }
192
- const result = this._buffer.splice(0);
193
- this.readableLength = 0;
194
- if (this._readableState.ended && this._buffer.length === 0 && !this._readableState.endEmitted) {
195
- this._emitEnd();
196
- }
197
- if (result.length === 1) return result[0];
198
- if (result.length === 0) return null;
199
- if (typeof result[0] === "string") return result.join("");
200
- const BufCtor = globalThis.Buffer;
201
- return BufCtor?.concat ? BufCtor.concat(result) : result;
202
- }
203
- /** @internal Extract exactly `size` bytes from the internal buffer. */
204
- _readBytes(size) {
205
- let collected = 0;
206
- const parts = [];
207
- while (collected < size && this._buffer.length > 0) {
208
- const chunk = this._buffer[0];
209
- const chunkLen = chunk.length ?? 1;
210
- if (collected + chunkLen <= size) {
211
- parts.push(this._buffer.shift());
212
- collected += chunkLen;
213
- this.readableLength -= chunkLen;
214
- } else {
215
- const needed = size - collected;
216
- const BufCtor = globalThis.Buffer;
217
- if (BufCtor && BufCtor.isBuffer(chunk)) {
218
- parts.push(chunk.slice(0, needed));
219
- this._buffer[0] = chunk.slice(needed);
220
- } else if (typeof chunk === "string") {
221
- parts.push(chunk.slice(0, needed));
222
- this._buffer[0] = chunk.slice(needed);
223
- } else {
224
- parts.push(chunk.slice(0, needed));
225
- this._buffer[0] = chunk.slice(needed);
226
- }
227
- this.readableLength -= needed;
228
- collected += needed;
229
- }
230
- }
231
- if (parts.length === 1) return parts[0];
232
- const BufCtor = globalThis.Buffer;
233
- return BufCtor?.concat ? BufCtor.concat(parts) : parts;
234
- }
235
- push(chunk, encoding) {
236
- if (chunk === null) {
237
- this._readableState.ended = true;
238
- this.readableEnded = true;
239
- if (this._buffer.length === 0 && !this._readableState.endEmitted) {
240
- nextTick(() => this._emitEnd());
241
- }
242
- this._scheduleReadable();
243
- return false;
244
- }
245
- if (!this.readableObjectMode) {
246
- const isValid = typeof chunk === "string" || ArrayBuffer.isView(chunk);
247
- if (!isValid) {
248
- const err = Object.assign(new TypeError(`Invalid non-string/buffer chunk type: ${typeof chunk}`), { code: "ERR_INVALID_ARG_TYPE" });
249
- nextTick(() => this.emit("error", err));
250
- return false;
251
- }
252
- }
253
- this._buffer.push(chunk);
254
- this.readableLength += this.readableObjectMode ? 1 : chunk.length ?? 1;
255
- if (this.readableFlowing && !this._flowing) {
256
- nextTick(() => this._flow());
257
- }
258
- if (this.readableFlowing !== true) {
259
- this._scheduleReadable();
260
- }
261
- return this.readableLength < this.readableHighWaterMark;
262
- }
263
- /** Emit 'end' followed by 'close' (matches Node.js autoDestroy behavior). */
264
- _emitEnd() {
265
- if (this._readableState.endEmitted) return;
266
- this._readableState.endEmitted = true;
267
- this.emit("end");
268
- nextTick(() => this._autoClose());
269
- }
270
- /** Override in subclasses to suppress automatic 'close' after 'end'. */
271
- _autoClose() {
272
- this.emit("close");
273
- }
274
- /** Schedule a single 'readable' event per microtask cycle (deduplicates multiple pushes). */
275
- _scheduleReadable() {
276
- if (this._readablePending || this.listenerCount("readable") === 0) return;
277
- this._readablePending = true;
278
- nextTick(() => {
279
- this._readablePending = false;
280
- if (!this.destroyed) this.emit("readable");
281
- });
282
- }
283
- on(event, listener) {
284
- super.on(event, listener);
285
- if (event === "data" && this.readableFlowing !== false) {
286
- this.resume();
287
- }
288
- if (event === "readable" && (this._buffer.length > 0 || this._readableState.ended)) {
289
- this._scheduleReadable();
290
- }
291
- return this;
292
- }
293
- unshift(chunk) {
294
- this._buffer.unshift(chunk);
295
- this.readableLength += this.readableObjectMode ? 1 : chunk.length ?? 1;
296
- }
297
- setEncoding(encoding) {
298
- this.readableEncoding = encoding;
299
- return this;
300
- }
301
- pause() {
302
- this.readableFlowing = false;
303
- this.emit("pause");
304
- return this;
305
- }
306
- resume() {
307
- if (this.readableFlowing !== true) {
308
- this.readableFlowing = true;
309
- this.emit("resume");
310
- if (this._readableState.constructed) {
311
- this._flow();
312
- }
313
- }
314
- return this;
315
- }
316
- _flowing = false;
317
- _flow() {
318
- if (this.readableFlowing !== true || this._flowing || this.destroyed) return;
319
- if (!this._readableState.constructed) return;
320
- this._flowing = true;
321
- try {
322
- while (this._buffer.length > 0 && this.readableFlowing && !this.destroyed) {
323
- let chunk = this._buffer.shift();
324
- this.readableLength -= this.readableObjectMode ? 1 : chunk.length ?? 1;
325
- if (this.readableEncoding && typeof chunk !== "string") {
326
- const BufCtor = globalThis.Buffer;
327
- if (BufCtor && BufCtor.isBuffer(chunk)) {
328
- chunk = chunk.toString(this.readableEncoding);
329
- } else if (chunk instanceof Uint8Array) {
330
- chunk = new TextDecoder(this.readableEncoding).decode(chunk);
331
- }
332
- }
333
- this.emit("data", chunk);
334
- }
335
- if (this.destroyed) return;
336
- if (this._readableState.ended && this._buffer.length === 0 && !this._readableState.endEmitted) {
337
- nextTick(() => this._emitEnd());
338
- return;
339
- }
340
- if (!this._readableState.ended && !this._readableState.reading && !this.destroyed) {
341
- this._readableState.reading = true;
342
- this._read(this.readableHighWaterMark);
343
- this._readableState.reading = false;
344
- }
345
- } finally {
346
- this._flowing = false;
347
- }
348
- if (this._buffer.length > 0 && this.readableFlowing && !this.destroyed) {
349
- nextTick(() => this._flow());
350
- }
351
- }
352
- isPaused() {
353
- return this.readableFlowing === false;
354
- }
355
- unpipe(destination) {
356
- if (!destination) {
357
- for (const state of this._pipeDests) {
358
- state.cleanup();
359
- state.dest.emit("unpipe", this);
360
- }
361
- this._pipeDests = [];
362
- this._readableState.pipes = [];
363
- this.readableFlowing = false;
364
- } else {
365
- const idx = this._pipeDests.findIndex((s) => s.dest === destination);
366
- if (idx !== -1) {
367
- const state = this._pipeDests[idx];
368
- state.cleanup();
369
- this._pipeDests.splice(idx, 1);
370
- const pipeIdx = this._readableState.pipes.indexOf(destination);
371
- if (pipeIdx !== -1) this._readableState.pipes.splice(pipeIdx, 1);
372
- destination.emit("unpipe", this);
373
- if (this._pipeDests.length === 0) {
374
- this.readableFlowing = false;
375
- }
376
- }
377
- }
378
- return this;
379
- }
380
- _destroy(error, callback) {
381
- if (this._destroyImpl) {
382
- this._destroyImpl.call(this, error, callback);
383
- } else {
384
- callback(error ?? undefined);
385
- }
386
- }
387
- destroy(error) {
388
- if (this.destroyed) return this;
389
- this.destroyed = true;
390
- this.readable = false;
391
- this.readableAborted = !this.readableEnded;
392
- if (error) this._err = error;
393
- const cb = (err) => {
394
- if (err) nextTick(() => this.emit("error", err));
395
- nextTick(() => this.emit("close"));
396
- };
397
- if (Object.prototype.hasOwnProperty.call(this, "_destroy")) {
398
- this._destroy(error ?? null, cb);
399
- } else if (this._destroyImpl) {
400
- this._destroyImpl.call(this, error ?? null, cb);
401
- } else {
402
- cb(error);
403
- }
404
- return this;
405
- }
406
- /**
407
- * Converts this Node.js Readable to a Web ReadableStream.
408
- * Used by @hono/node-server to bridge Node.js HTTP → Web Standard Request.
409
- */
410
- static toWeb(nodeReadable) {
411
- return new ReadableStream({
412
- start(controller) {
413
- nodeReadable.on("data", (chunk) => {
414
- if (typeof chunk === "string") {
415
- controller.enqueue(new TextEncoder().encode(chunk));
416
- } else if (chunk instanceof Uint8Array) {
417
- controller.enqueue(chunk);
418
- } else if (chunk && typeof chunk.length === "number") {
419
- controller.enqueue(new Uint8Array(chunk));
420
- }
421
- });
422
- nodeReadable.on("end", () => {
423
- controller.close();
424
- });
425
- nodeReadable.on("error", (err) => {
426
- controller.error(err);
427
- });
428
- },
429
- cancel() {
430
- nodeReadable.destroy();
431
- }
432
- });
433
- }
434
- /**
435
- * Creates a Node.js Readable from a Web ReadableStream.
436
- */
437
- static fromWeb(webStream, options) {
438
- const reader = webStream.getReader();
439
- return new Readable_({
440
- ...options,
441
- read() {
442
- reader.read().then(({ done, value }) => {
443
- if (done) {
444
- this.push(null);
445
- } else {
446
- this.push(value);
447
- }
448
- }, (err) => {
449
- this.destroy(err);
450
- });
451
- },
452
- destroy(error, callback) {
453
- reader.cancel(error?.message).then(() => callback(null), callback);
454
- }
455
- });
456
- }
457
- [Symbol.asyncIterator]() {
458
- const readable = this;
459
- const buffer = [];
460
- let done = false;
461
- let error = null;
462
- let waitingResolve = null;
463
- let waitingReject = null;
464
- readable.on("data", (chunk) => {
465
- if (waitingResolve) {
466
- const resolve = waitingResolve;
467
- waitingResolve = null;
468
- waitingReject = null;
469
- resolve({
470
- value: chunk,
471
- done: false
472
- });
473
- } else {
474
- buffer.push(chunk);
475
- }
476
- });
477
- readable.on("end", () => {
478
- done = true;
479
- if (waitingResolve) {
480
- const resolve = waitingResolve;
481
- waitingResolve = null;
482
- waitingReject = null;
483
- resolve({
484
- value: undefined,
485
- done: true
486
- });
487
- }
488
- });
489
- readable.on("error", (err) => {
490
- error = err;
491
- done = true;
492
- if (waitingReject) {
493
- const reject = waitingReject;
494
- waitingResolve = null;
495
- waitingReject = null;
496
- reject(err);
497
- }
498
- });
499
- return {
500
- next() {
501
- if (error) return Promise.reject(error);
502
- if (buffer.length > 0) return Promise.resolve({
503
- value: buffer.shift(),
504
- done: false
505
- });
506
- if (done) return Promise.resolve({
507
- value: undefined,
508
- done: true
509
- });
510
- return new Promise((resolve, reject) => {
511
- waitingResolve = resolve;
512
- waitingReject = reject;
513
- });
514
- },
515
- return() {
516
- readable.destroy();
517
- return Promise.resolve({
518
- value: undefined,
519
- done: true
520
- });
521
- },
522
- [Symbol.asyncIterator]() {
523
- return this;
524
- }
525
- };
526
- }
527
- static from(iterable, opts) {
528
- const readable = new Readable({
529
- objectMode: true,
530
- ...opts,
531
- read() {}
532
- });
533
- if (typeof iterable === "string" || ArrayBuffer.isView(iterable)) {
534
- readable.push(iterable);
535
- readable.push(null);
536
- return readable;
537
- }
538
- (async () => {
539
- try {
540
- for await (const chunk of iterable) {
541
- if (!readable.push(chunk)) {
542
- await new Promise((resolve) => readable.once("drain", resolve));
543
- }
544
- }
545
- readable.push(null);
546
- } catch (err) {
547
- readable.destroy(err);
548
- }
549
- })();
550
- return readable;
551
- }
552
- };
553
- var Writable_ = class Writable_ extends Stream_ {
554
- static [Symbol.hasInstance](obj) {
555
- if (typeof this.prototype !== "undefined" && Object.prototype.isPrototypeOf.call(this.prototype, obj)) return true;
556
- if (this.prototype !== Writable_.prototype) return false;
557
- return obj !== null && obj !== undefined && typeof obj.writableHighWaterMark === "number";
558
- }
559
- writable = true;
560
- writableHighWaterMark;
561
- writableLength = 0;
562
- writableObjectMode;
563
- writableEnded = false;
564
- writableFinished = false;
565
- writableCorked = 0;
566
- writableNeedDrain = false;
567
- destroyed = false;
568
- _writableState = {
569
- ended: false,
570
- finished: false,
571
- constructed: true,
572
- writing: false
573
- };
574
- _corkedBuffer = [];
575
- _writeBuffer = [];
576
- _pendingConstruct = [];
577
- _ending = false;
578
- _endCallback;
579
- _pendingEnd = null;
580
- _writeImpl;
581
- _writev;
582
- _finalImpl;
583
- _destroyImpl;
584
- _constructImpl;
585
- _decodeStrings;
586
- _defaultEncoding = "utf8";
587
- constructor(opts) {
588
- super(opts);
589
- this.writableHighWaterMark = opts?.highWaterMark ?? getDefaultHighWaterMark(opts?.objectMode ?? false);
590
- this.writableObjectMode = opts?.objectMode ?? false;
591
- this._decodeStrings = opts?.decodeStrings !== false;
592
- if (opts?.write) this._writeImpl = opts.write;
593
- if (opts?.writev) this._writev = opts.writev;
594
- if (opts?.final) this._finalImpl = opts.final;
595
- if (opts?.destroy) this._destroyImpl = opts.destroy;
596
- if (opts?.construct) this._constructImpl = opts.construct;
597
- const hasConstruct = this._constructImpl || this._construct !== Writable.prototype._construct;
598
- if (hasConstruct) {
599
- this._writableState.constructed = false;
600
- nextTick(() => {
601
- this._construct((err) => {
602
- this._writableState.constructed = true;
603
- if (err) {
604
- this.destroy(err);
605
- } else {
606
- this._maybeFlush();
607
- }
608
- });
609
- });
610
- }
611
- }
612
- _construct(callback) {
613
- if (this._constructImpl) {
614
- this._constructImpl.call(this, callback);
615
- } else {
616
- callback();
617
- }
618
- }
619
- _write(chunk, encoding, callback) {
620
- if (this._writeImpl) {
621
- this._writeImpl.call(this, chunk, encoding, callback);
622
- } else {
623
- callback();
624
- }
625
- }
626
- _final(callback) {
627
- if (this._finalImpl) {
628
- this._finalImpl.call(this, callback);
629
- } else {
630
- callback();
631
- }
632
- }
633
- _maybeFlush() {
634
- const pending = this._pendingConstruct.splice(0);
635
- if (pending.length > 0) {
636
- const [first, ...rest] = pending;
637
- this._writeBuffer.push(...rest);
638
- this._doWrite(first.chunk, first.encoding, first.callback);
639
- }
640
- if (this._pendingEnd) {
641
- const { chunk, encoding, callback } = this._pendingEnd;
642
- this._pendingEnd = null;
643
- this._doEnd(chunk, encoding, callback);
644
- }
645
- }
646
- _doWrite(chunk, encoding, callback) {
647
- this._writableState.writing = true;
648
- let sync = true;
649
- this._write(chunk, encoding, (err) => {
650
- this.writableLength -= this.writableObjectMode ? 1 : chunk?.length ?? 1;
651
- if (sync) {
652
- nextTick(() => {
653
- if (err) {
654
- callback(err);
655
- this.emit("error", err);
656
- return;
657
- }
658
- callback();
659
- if (this.writableNeedDrain && this.writableLength <= this.writableHighWaterMark) {
660
- this.writableNeedDrain = false;
661
- this.emit("drain");
662
- }
663
- });
664
- if (!err) this._drainWriteBuffer();
665
- return;
666
- }
667
- if (err) {
668
- nextTick(() => {
669
- callback(err);
670
- this.emit("error", err);
671
- this._drainWriteBuffer();
672
- });
673
- } else {
674
- nextTick(() => {
675
- callback();
676
- if (this.writableNeedDrain && this.writableLength <= this.writableHighWaterMark) {
677
- this.writableNeedDrain = false;
678
- this.emit("drain");
679
- }
680
- this._drainWriteBuffer();
681
- });
682
- }
683
- });
684
- sync = false;
685
- }
686
- _drainWriteBuffer() {
687
- if (this._writeBuffer.length > 0) {
688
- const next = this._writeBuffer.shift();
689
- this._doWrite(next.chunk, next.encoding, next.callback);
690
- } else {
691
- this._writableState.writing = false;
692
- this._maybeFinish();
693
- }
694
- }
695
- _maybeFinish() {
696
- if (!this._ending || this._writableState.finished || this._writableState.writing || this._writeBuffer.length > 0) return;
697
- this._ending = false;
698
- this._final((err) => {
699
- this.writableFinished = true;
700
- this._writableState.finished = true;
701
- nextTick(() => {
702
- if (err) {
703
- this.emit("error", err);
704
- }
705
- this.emit("finish");
706
- nextTick(() => this.emit("close"));
707
- if (this._endCallback) this._endCallback();
708
- });
709
- });
710
- }
711
- write(chunk, encoding, callback) {
712
- if (typeof encoding === "function") {
713
- callback = encoding;
714
- encoding = undefined;
715
- }
716
- if (encoding === undefined) encoding = this._defaultEncoding;
717
- callback = callback || (() => {});
718
- if (this._decodeStrings && !this.writableObjectMode && typeof chunk === "string") {
719
- const BufCtor = globalThis.Buffer;
720
- if (BufCtor) {
721
- chunk = BufCtor.from(chunk, encoding);
722
- encoding = "buffer";
723
- }
724
- }
725
- if (typeof chunk !== "string" && !this.writableObjectMode) {
726
- const BufCtor = globalThis.Buffer;
727
- if (BufCtor && BufCtor.isBuffer(chunk) || chunk instanceof Uint8Array) {
728
- encoding = "buffer";
729
- }
730
- }
731
- if (this.writableEnded) {
732
- const err = new Error("write after end");
733
- nextTick(() => {
734
- if (callback) callback(err);
735
- this.emit("error", err);
736
- });
737
- return false;
738
- }
739
- this.writableLength += this.writableObjectMode ? 1 : chunk?.length ?? 1;
740
- if (this.writableCorked > 0) {
741
- this._corkedBuffer.push({
742
- chunk,
743
- encoding,
744
- callback
745
- });
746
- return this.writableLength < this.writableHighWaterMark;
747
- }
748
- if (!this._writableState.constructed) {
749
- this._pendingConstruct.push({
750
- chunk,
751
- encoding,
752
- callback
753
- });
754
- return this.writableLength < this.writableHighWaterMark;
755
- }
756
- const belowHWM = this.writableLength < this.writableHighWaterMark;
757
- if (!belowHWM) {
758
- this.writableNeedDrain = true;
759
- }
760
- if (this._writableState.writing) {
761
- this._writeBuffer.push({
762
- chunk,
763
- encoding,
764
- callback
765
- });
766
- } else {
767
- this._doWrite(chunk, encoding, callback);
768
- }
769
- return belowHWM;
770
- }
771
- _doEnd(chunk, encoding, callback) {
772
- if (chunk !== undefined && chunk !== null) {
773
- this.write(chunk, encoding);
774
- }
775
- this.writableEnded = true;
776
- this._writableState.ended = true;
777
- this._ending = true;
778
- this._endCallback = callback;
779
- this._maybeFinish();
780
- }
781
- end(chunk, encoding, callback) {
782
- if (typeof chunk === "function") {
783
- callback = chunk;
784
- chunk = undefined;
785
- }
786
- if (typeof encoding === "function") {
787
- callback = encoding;
788
- encoding = undefined;
789
- }
790
- if (this.writableEnded) {
791
- if (callback) nextTick(callback);
792
- return this;
793
- }
794
- if (!this._writableState.constructed) {
795
- this._pendingEnd = {
796
- chunk,
797
- encoding,
798
- callback
799
- };
800
- return this;
801
- }
802
- this._doEnd(chunk, encoding, callback);
803
- return this;
804
- }
805
- cork() {
806
- this.writableCorked++;
807
- }
808
- uncork() {
809
- if (this.writableCorked > 0) {
810
- this.writableCorked--;
811
- if (this.writableCorked === 0 && this._corkedBuffer.length > 0) {
812
- this._flushCorkedBuffer();
813
- }
814
- }
815
- }
816
- _flushCorkedBuffer() {
817
- if (this._writev && this._corkedBuffer.length > 1) {
818
- const buffered = this._corkedBuffer.splice(0);
819
- const chunks = buffered.map((b) => ({
820
- chunk: b.chunk,
821
- encoding: b.encoding
822
- }));
823
- this._writev.call(this, chunks, (err) => {
824
- for (const b of buffered) {
825
- this.writableLength -= this.writableObjectMode ? 1 : b.chunk?.length ?? 1;
826
- }
827
- if (err) {
828
- for (const b of buffered) b.callback(err);
829
- this.emit("error", err);
830
- } else {
831
- for (const b of buffered) b.callback();
832
- if (this.writableNeedDrain && this.writableLength <= this.writableHighWaterMark) {
833
- this.writableNeedDrain = false;
834
- this.emit("drain");
835
- }
836
- }
837
- });
838
- } else {
839
- const buffered = this._corkedBuffer.splice(0);
840
- if (buffered.length > 0) {
841
- const [first, ...rest] = buffered;
842
- this._writeBuffer.push(...rest);
843
- this._doWrite(first.chunk, first.encoding, first.callback);
844
- }
845
- }
846
- }
847
- setDefaultEncoding(encoding) {
848
- this._defaultEncoding = encoding;
849
- return this;
850
- }
851
- destroy(error) {
852
- if (this.destroyed) return this;
853
- this.destroyed = true;
854
- this.writable = false;
855
- if (error) this._err = error;
856
- const cb = (err) => {
857
- if (err) nextTick(() => this.emit("error", err));
858
- nextTick(() => this.emit("close"));
859
- };
860
- if (this._destroyImpl) {
861
- this._destroyImpl.call(this, error ?? null, cb);
862
- } else {
863
- cb(error);
864
- }
865
- return this;
866
- }
867
- };
868
- var Duplex_ = class extends Readable_ {
869
- writable = true;
870
- writableHighWaterMark;
871
- writableLength = 0;
872
- writableObjectMode;
873
- writableEnded = false;
874
- writableFinished = false;
875
- writableCorked = 0;
876
- writableNeedDrain = false;
877
- allowHalfOpen;
878
- _decodeStrings;
879
- _writableState = {
880
- highWaterMark: 0,
881
- objectMode: false
882
- };
883
- _duplexCorkedBuffer = [];
884
- _duplexWriting = false;
885
- _duplexWriteQueue = [];
886
- _writeImpl;
887
- _finalImpl;
888
- _defaultEncoding = "utf8";
889
- _pendingWrites = 0;
890
- _pendingEndCb = null;
891
- constructor(opts) {
892
- super(opts);
893
- validateHighWaterMark("writableHighWaterMark", opts?.writableHighWaterMark);
894
- validateHighWaterMark("readableHighWaterMark", opts?.readableHighWaterMark);
895
- this.writableObjectMode = opts?.writableObjectMode ?? opts?.objectMode ?? false;
896
- this.writableHighWaterMark = opts?.highWaterMark ?? opts?.writableHighWaterMark ?? getDefaultHighWaterMark(this.writableObjectMode);
897
- this._writableState.highWaterMark = this.writableHighWaterMark;
898
- this._writableState.objectMode = this.writableObjectMode;
899
- if (opts?.highWaterMark === undefined && opts?.readableHighWaterMark !== undefined) {
900
- this.readableHighWaterMark = opts.readableHighWaterMark;
901
- this._readableState.highWaterMark = opts.readableHighWaterMark;
902
- }
903
- if (opts?.readableObjectMode !== undefined) {
904
- this.readableObjectMode = opts.readableObjectMode;
905
- this._readableState.objectMode = opts.readableObjectMode;
906
- if (opts?.readableHighWaterMark === undefined && opts?.highWaterMark === undefined) {
907
- this.readableHighWaterMark = getDefaultHighWaterMark(opts.readableObjectMode);
908
- this._readableState.highWaterMark = this.readableHighWaterMark;
909
- }
910
- }
911
- this.allowHalfOpen = opts?.allowHalfOpen !== false;
912
- this._decodeStrings = opts?.decodeStrings !== false;
913
- if (opts?.write) this._writeImpl = opts.write;
914
- if (opts?.final) this._finalImpl = opts.final;
915
- if (!this.allowHalfOpen) {
916
- this.once("end", () => {
917
- if (!this.writableEnded) {
918
- nextTick(() => this.end());
919
- }
920
- });
921
- }
922
- }
923
- _write(chunk, encoding, callback) {
924
- if (this._writeImpl) {
925
- this._writeImpl.call(this, chunk, encoding, callback);
926
- } else {
927
- callback();
928
- }
929
- }
930
- _final(callback) {
931
- if (this._finalImpl) {
932
- this._finalImpl.call(this, callback);
933
- } else {
934
- callback();
935
- }
936
- }
937
- destroy(error) {
938
- if (this.destroyed) return this;
939
- this.writable = false;
940
- return super.destroy(error);
941
- }
942
- write(chunk, encoding, callback) {
943
- if (typeof encoding === "function") {
944
- callback = encoding;
945
- encoding = undefined;
946
- }
947
- if (encoding === undefined) encoding = this._defaultEncoding;
948
- if (this._decodeStrings && !this.writableObjectMode && typeof chunk === "string") {
949
- const BufCtor = globalThis.Buffer;
950
- if (BufCtor) {
951
- chunk = BufCtor.from(chunk, encoding);
952
- encoding = "buffer";
953
- }
954
- }
955
- if (typeof chunk !== "string" && !this.writableObjectMode) {
956
- const BufCtor = globalThis.Buffer;
957
- if (BufCtor && BufCtor.isBuffer(chunk) || chunk instanceof Uint8Array) {
958
- encoding = "buffer";
959
- }
960
- }
961
- if (this.writableEnded) {
962
- const err = new Error("write after end");
963
- const cb = callback || (() => {});
964
- nextTick(() => {
965
- cb(err);
966
- this.emit("error", err);
967
- });
968
- return false;
969
- }
970
- this.writableLength += this.writableObjectMode ? 1 : chunk?.length ?? 1;
971
- if (this.writableCorked > 0) {
972
- this._duplexCorkedBuffer.push({
973
- chunk,
974
- encoding,
975
- callback: callback || (() => {})
976
- });
977
- return this.writableLength < this.writableHighWaterMark;
978
- }
979
- const belowHWM = this.writableLength < this.writableHighWaterMark;
980
- if (!belowHWM) {
981
- this.writableNeedDrain = true;
982
- }
983
- const cb = callback || (() => {});
984
- this._duplexDoWrite(chunk, encoding, cb);
985
- return belowHWM;
986
- }
987
- _duplexDoWrite(chunk, encoding, cb) {
988
- if (this._duplexWriting) {
989
- this._duplexWriteQueue.push({
990
- chunk,
991
- encoding,
992
- callback: cb
993
- });
994
- return;
995
- }
996
- this._duplexWriting = true;
997
- this._duplexStartWrite(chunk, encoding, cb);
998
- }
999
- _duplexStartWrite(chunk, encoding, cb) {
1000
- this._pendingWrites++;
1001
- this._write(chunk, encoding, (err) => {
1002
- this._pendingWrites--;
1003
- this.writableLength -= this.writableObjectMode ? 1 : chunk?.length ?? 1;
1004
- if (err) {
1005
- nextTick(() => {
1006
- cb(err);
1007
- this._duplexWriting = false;
1008
- this.emit("error", err);
1009
- if (this._duplexWriteQueue.length > 0) {
1010
- const next = this._duplexWriteQueue.shift();
1011
- this._duplexWriting = true;
1012
- this._duplexStartWrite(next.chunk, next.encoding, next.callback);
1013
- }
1014
- });
1015
- } else {
1016
- nextTick(() => {
1017
- cb();
1018
- if (this._duplexWriteQueue.length > 0) {
1019
- const next = this._duplexWriteQueue.shift();
1020
- this._duplexStartWrite(next.chunk, next.encoding, next.callback);
1021
- return;
1022
- }
1023
- this._duplexWriting = false;
1024
- if (this.writableNeedDrain && this.writableLength <= this.writableHighWaterMark) {
1025
- this.writableNeedDrain = false;
1026
- this.emit("drain");
1027
- }
1028
- if (this._pendingWrites === 0 && this._pendingEndCb) {
1029
- const endCb = this._pendingEndCb;
1030
- this._pendingEndCb = null;
1031
- endCb();
1032
- }
1033
- });
1034
- }
1035
- });
1036
- }
1037
- _duplexDrainQueue() {
1038
- if (this._duplexWriteQueue.length > 0) {
1039
- const next = this._duplexWriteQueue.shift();
1040
- this._duplexDoWrite(next.chunk, next.encoding, next.callback);
1041
- }
1042
- }
1043
- end(chunk, encoding, callback) {
1044
- if (typeof chunk === "function") {
1045
- callback = chunk;
1046
- chunk = undefined;
1047
- }
1048
- if (typeof encoding === "function") {
1049
- callback = encoding;
1050
- encoding = undefined;
1051
- }
1052
- if (chunk !== undefined && chunk !== null) {
1053
- this.write(chunk, encoding);
1054
- }
1055
- this.writableEnded = true;
1056
- const doFinal = () => {
1057
- this._final((err) => {
1058
- this.writableFinished = true;
1059
- this._doPrefinishHooks(() => {
1060
- nextTick(() => {
1061
- if (err) this.emit("error", err);
1062
- this.emit("finish");
1063
- nextTick(() => this.emit("close"));
1064
- if (callback) callback();
1065
- });
1066
- });
1067
- });
1068
- };
1069
- if (this._pendingWrites > 0 || this._duplexWriting || this._duplexWriteQueue.length > 0) {
1070
- this._pendingEndCb = doFinal;
1071
- } else {
1072
- doFinal();
1073
- }
1074
- return this;
1075
- }
1076
- /** Hook for subclasses to run logic between _final and 'finish'. Default: no-op. */
1077
- _doPrefinishHooks(cb) {
1078
- cb();
1079
- }
1080
- cork() {
1081
- this.writableCorked++;
1082
- }
1083
- uncork() {
1084
- if (this.writableCorked > 0) {
1085
- this.writableCorked--;
1086
- if (this.writableCorked === 0 && this._duplexCorkedBuffer.length > 0) {
1087
- const buffered = this._duplexCorkedBuffer.splice(0);
1088
- for (const { chunk, encoding, callback } of buffered) {
1089
- this._write(chunk, encoding, (err) => {
1090
- this.writableLength -= this.writableObjectMode ? 1 : chunk?.length ?? 1;
1091
- if (err) {
1092
- callback(err);
1093
- this.emit("error", err);
1094
- } else {
1095
- callback();
1096
- }
1097
- });
1098
- }
1099
- if (this.writableNeedDrain && this.writableLength <= this.writableHighWaterMark) {
1100
- this.writableNeedDrain = false;
1101
- nextTick(() => this.emit("drain"));
1102
- }
1103
- }
1104
- }
1105
- }
1106
- setDefaultEncoding(encoding) {
1107
- this._defaultEncoding = encoding;
1108
- return this;
1109
- }
1110
- };
1111
- var Transform_ = class Transform_ extends Duplex_ {
1112
- constructor(opts) {
1113
- super({
1114
- ...opts,
1115
- write: undefined,
1116
- final: undefined
1117
- });
1118
- if (opts?.transform) this._transform = opts.transform;
1119
- if (opts?.flush) this._flush = opts.flush;
1120
- if (opts?.final) this._final = opts.final;
1121
- }
1122
- _transform(_chunk, _encoding, _callback) {
1123
- const err = Object.assign(new Error("The _transform() method is not implemented"), { code: "ERR_METHOD_NOT_IMPLEMENTED" });
1124
- throw err;
1125
- }
1126
- _flush(callback) {
1127
- callback();
1128
- }
1129
- _write(chunk, encoding, callback) {
1130
- let called = false;
1131
- try {
1132
- this._transform(chunk, encoding, (err, data) => {
1133
- if (called) {
1134
- const e = Object.assign(new Error("Callback called multiple times"), { code: "ERR_MULTIPLE_CALLBACK" });
1135
- nextTick(() => this.emit("error", e));
1136
- return;
1137
- }
1138
- called = true;
1139
- if (err) {
1140
- callback(err);
1141
- return;
1142
- }
1143
- if (data !== undefined && data !== null) {
1144
- this.push(data);
1145
- }
1146
- callback();
1147
- });
1148
- } catch (err) {
1149
- if (err?.code === "ERR_METHOD_NOT_IMPLEMENTED") throw err;
1150
- callback(err);
1151
- }
1152
- }
1153
- _final(callback) {
1154
- this._flush((err, data) => {
1155
- if (err) {
1156
- callback(err);
1157
- return;
1158
- }
1159
- if (data !== undefined && data !== null) {
1160
- this.push(data);
1161
- }
1162
- this.push(null);
1163
- callback();
1164
- });
1165
- }
1166
- _doPrefinishHooks(cb) {
1167
- const protoFinal = Transform_.prototype._final;
1168
- if (this._final !== protoFinal) {
1169
- protoFinal.call(this, cb);
1170
- } else {
1171
- cb();
1172
- }
1173
- }
1174
- };
1175
- var PassThrough_ = class extends Transform_ {
1176
- constructor(opts) {
1177
- super({
1178
- ...opts,
1179
- transform(chunk, _encoding, callback) {
1180
- callback(null, chunk);
1181
- }
1182
- });
1183
- }
1184
- };
1185
- function pipeline(...args) {
1186
- const callback = typeof args[args.length - 1] === "function" ? args.pop() : undefined;
1187
- const streams = args;
1188
- if (streams.length < 2) {
1189
- throw new Error("pipeline requires at least 2 streams");
1190
- }
1191
- let error = null;
1192
- function onError(err) {
1193
- if (!error) {
1194
- error = err;
1195
- for (const stream of streams) {
1196
- if (typeof stream.destroy === "function") {
1197
- stream.destroy();
1198
- }
1199
- }
1200
- if (callback) callback(err);
1201
- }
1202
- }
1203
- let current = streams[0];
1204
- for (let i = 1; i < streams.length; i++) {
1205
- const next = streams[i];
1206
- current.pipe(next);
1207
- current.on("error", onError);
1208
- current = next;
1209
- }
1210
- const last = streams[streams.length - 1];
1211
- last.on("error", onError);
1212
- last.on("finish", () => {
1213
- if (callback && !error) callback(null);
1214
- });
1215
- return last;
1216
- }
1217
- function finished(stream, optsOrCb, callback) {
1218
- let cb;
1219
- let _opts = {};
1220
- if (typeof optsOrCb === "function") {
1221
- cb = optsOrCb;
1222
- } else {
1223
- _opts = optsOrCb || {};
1224
- cb = callback;
1225
- }
1226
- let called = false;
1227
- function done(err) {
1228
- if (!called) {
1229
- called = true;
1230
- cb(err);
1231
- }
1232
- }
1233
- const onFinish = () => done();
1234
- const onEnd = () => done();
1235
- const onError = (err) => done(err);
1236
- const onClose = () => {
1237
- if (!stream.writableFinished && !stream.readableEnded) {
1238
- done(new Error("premature close"));
1239
- }
1240
- };
1241
- stream.on("finish", onFinish);
1242
- stream.on("end", onEnd);
1243
- stream.on("error", onError);
1244
- stream.on("close", onClose);
1245
- const isWritableStream = typeof stream.write === "function";
1246
- const isReadableStream = typeof stream.read === "function";
1247
- const writableFinished = stream.writableFinished === true;
1248
- const readableEnded = stream.readableEnded === true;
1249
- const destroyed = stream.destroyed === true;
1250
- if (destroyed) {
1251
- const storedErr = stream._err;
1252
- if (storedErr) {
1253
- queueMicrotask(() => done(storedErr));
1254
- } else if (isWritableStream && writableFinished || isReadableStream && readableEnded) {
1255
- queueMicrotask(() => done());
1256
- } else {
1257
- queueMicrotask(() => done(new Error("premature close")));
1258
- }
1259
- } else if (isWritableStream && !isReadableStream && writableFinished) {
1260
- queueMicrotask(() => done());
1261
- } else if (!isWritableStream && isReadableStream && readableEnded) {
1262
- queueMicrotask(() => done());
1263
- } else if (isWritableStream && isReadableStream && writableFinished && readableEnded) {
1264
- queueMicrotask(() => done());
1265
- }
1266
- return function cleanup() {
1267
- stream.removeListener("finish", onFinish);
1268
- stream.removeListener("end", onEnd);
1269
- stream.removeListener("error", onError);
1270
- stream.removeListener("close", onClose);
1271
- };
1272
- }
1273
- function addAbortSignal(signal, stream) {
1274
- if (!(signal instanceof AbortSignal)) {
1275
- throw new TypeError("The first argument must be an AbortSignal");
1276
- }
1277
- if (!(stream instanceof Stream)) {
1278
- throw new TypeError("The second argument must be a Stream");
1279
- }
1280
- if (signal.aborted) {
1281
- stream.destroy(new Error("The operation was aborted"));
1282
- } else {
1283
- const onAbort = () => {
1284
- stream.destroy(new Error("The operation was aborted"));
1285
- };
1286
- signal.addEventListener("abort", onAbort, { once: true });
1287
- stream.once("close", () => {
1288
- signal.removeEventListener("abort", onAbort);
1289
- });
1290
- }
1291
- return stream;
1292
- }
1293
- function isReadable(stream) {
1294
- if (stream == null) return false;
1295
- const s = stream;
1296
- if (typeof s.readable !== "boolean") return false;
1297
- if (typeof s.read !== "function") return false;
1298
- if (s.destroyed === true) return false;
1299
- if (s.readableEnded === true) return false;
1300
- return s.readable === true;
1301
- }
1302
- function isWritable(stream) {
1303
- if (stream == null) return false;
1304
- const s = stream;
1305
- if (typeof s.writable !== "boolean") return false;
1306
- if (typeof s.write !== "function") return false;
1307
- if (s.destroyed === true) return false;
1308
- if (s.writableEnded === true) return false;
1309
- return s.writable === true;
1310
- }
1311
- function isDestroyed(stream) {
1312
- if (stream == null) return false;
1313
- return stream.destroyed === true;
1314
- }
1315
- function isDisturbed(stream) {
1316
- if (stream == null) return false;
1317
- const s = stream;
1318
- return s.readableDidRead === true || s.readableFlowing !== null && s.readableFlowing !== undefined;
1319
- }
1320
- function isErrored(stream) {
1321
- if (stream == null) return false;
1322
- const s = stream;
1323
- if (s.destroyed === true && typeof s.readable === "boolean" && s.readable === false) return true;
1324
- if (s.destroyed === true && typeof s.writable === "boolean" && s.writable === false) return true;
1325
- return false;
1326
- }
1327
- const Stream = makeCallable(Stream_);
1328
- const Readable = makeCallable(Readable_);
1329
- const Writable = makeCallable(Writable_);
1330
- const Duplex = makeCallable(Duplex_);
1331
- const Transform = makeCallable(Transform_);
1332
- const PassThrough = makeCallable(PassThrough_);
1333
- const _default = Object.assign(Stream, {
1334
- Stream,
1335
- Readable,
1336
- Writable,
1337
- Duplex,
1338
- Transform,
1339
- PassThrough,
1340
- pipeline,
1341
- finished,
1342
- addAbortSignal,
1343
- isReadable,
1344
- isWritable,
1345
- isDestroyed,
1346
- isDisturbed,
1347
- isErrored,
1348
- getDefaultHighWaterMark,
1349
- setDefaultHighWaterMark
1350
- });
1351
-
1352
- //#endregion
1353
- export { Duplex, PassThrough, Readable, Stream, Transform, Writable, addAbortSignal, _default as default, finished, getDefaultHighWaterMark, isDestroyed, isDisturbed, isErrored, isReadable, isWritable, pipeline, setDefaultHighWaterMark };
1
+ import{makeCallable as e}from"./callable.js";import{nextTick as t,queueMicrotask as n}from"@gjsify/utils";import{EventEmitter as r}from"@gjsify/events";let i=16384,a=16;function o(e){return e?a:i}function s(e,t){if(typeof t!=`number`||t<0||Number.isNaN(t))throw TypeError(`Invalid highWaterMark: ${t}`);e?a=t:i=t}function c(e,t){if(t!==void 0&&(typeof t!=`number`||Number.isNaN(t))){let n=TypeError(`The value of "${e}" is invalid. Received ${t}`);throw n.code=`ERR_INVALID_ARG_VALUE`,n}}var l=class extends r{constructor(e){super(e)}pipe(e,t){let n=this,r=t?.end!==!1,i=!1,a=()=>{i=!1,e.removeListener(`drain`,a),typeof n.resume==`function`&&n.resume()},o=t=>{e.writable&&e.write(t)===!1&&typeof n.pause==`function`&&(n.pause(),i||(i=!0,e.on(`drain`,a)))};n.on(`data`,o);let s=!1,c=()=>{s||(s=!0,r&&e.end())},l=()=>{s||(s=!0,r&&!(n instanceof w)&&typeof e.destroy==`function`&&e.destroy())};r&&(n.on(`end`,c),n.on(`close`,l));let u=()=>{n.removeListener(`data`,o),i&&e.removeListener(`drain`,a),n.removeListener(`end`,c),n.removeListener(`close`,l),n.removeListener(`end`,u),n.removeListener(`close`,u),e.removeListener(`close`,u)};return n.on(`end`,u),n.on(`close`,u),e.on(`close`,u),n instanceof w&&(n._pipeDests.push({dest:e,cleanup:u}),n._readableState.pipes.push(e)),e.emit(`pipe`,n),e}},u=class e extends l{readable=!0;readableFlowing=null;readableLength=0;readableHighWaterMark;readableEncoding;readableObjectMode;readableEnded=!1;readableAborted=!1;destroyed=!1;_pipeDests=[];_buffer=[];_readableState={ended:!1,endEmitted:!1,reading:!1,constructed:!0,highWaterMark:0,objectMode:!1,pipes:[]};_readablePending=!1;_readImpl;_destroyImpl;_constructImpl;constructor(e){super(e),this.readableHighWaterMark=e?.highWaterMark??o(e?.objectMode??!1),this.readableEncoding=e?.encoding??null,this.readableObjectMode=e?.objectMode??!1,this._readableState.highWaterMark=this.readableHighWaterMark,this._readableState.objectMode=this.readableObjectMode,e?.read&&(this._readImpl=e.read),e?.destroy&&(this._destroyImpl=e.destroy),e?.construct&&(this._constructImpl=e.construct),(this._constructImpl||this._construct!==w.prototype._construct)&&(this._readableState.constructed=!1,t(()=>{this._construct(e=>{this._readableState.constructed=!0,e?this.destroy(e):this.readableFlowing===!0&&this._flow()})}))}_construct(e){this._constructImpl?this._constructImpl.call(this,e):e()}_read(e){this._readImpl&&this._readImpl.call(this,e)}read(e){if(!this._readableState.constructed)return null;if(this._buffer.length===0){if(this._readableState.ended)return null;this._readableState.reading=!0,this._read(e??this.readableHighWaterMark),this._readableState.reading=!1}if(this._buffer.length===0||e===0)return null;if(this.readableObjectMode){if(e===void 0){let e=this._buffer.shift();return--this.readableLength,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),e}if(e>this.readableLength)return null;let t=this._buffer.shift();return--this.readableLength,t}if(e!=null)return e>this.readableLength?null:this._readBytes(e);let t=this._buffer.splice(0);if(this.readableLength=0,this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted&&this._emitEnd(),t.length===1)return t[0];if(t.length===0)return null;if(typeof t[0]==`string`)return t.join(``);let n=globalThis.Buffer;return n?.concat?n.concat(t):t}_readBytes(e){let t=0,n=[];for(;t<e&&this._buffer.length>0;){let r=this._buffer[0],i=r.length??1;if(t+i<=e)n.push(this._buffer.shift()),t+=i,this.readableLength-=i;else{let i=e-t,a=globalThis.Buffer;a&&a.isBuffer(r),n.push(r.slice(0,i)),this._buffer[0]=r.slice(i),this.readableLength-=i,t+=i}}if(n.length===1)return n[0];let r=globalThis.Buffer;return r?.concat?r.concat(n):n}push(e,n){if(e===null)return this._readableState.ended=!0,this.readableEnded=!0,this._buffer.length===0&&!this._readableState.endEmitted&&t(()=>this._emitEnd()),this._scheduleReadable(),!1;if(!this.readableObjectMode&&!(typeof e==`string`||ArrayBuffer.isView(e))){let n=Object.assign(TypeError(`Invalid non-string/buffer chunk type: ${typeof e}`),{code:`ERR_INVALID_ARG_TYPE`});return t(()=>this.emit(`error`,n)),!1}return this._buffer.push(e),this.readableLength+=this.readableObjectMode?1:e.length??1,this.readableFlowing&&!this._flowing&&t(()=>this._flow()),this.readableFlowing!==!0&&this._scheduleReadable(),this.readableLength<this.readableHighWaterMark}_emitEnd(){this._readableState.endEmitted||(this._readableState.endEmitted=!0,this.emit(`end`),t(()=>this._autoClose()))}_autoClose(){this.emit(`close`)}_scheduleReadable(){this._readablePending||this.listenerCount(`readable`)===0||(this._readablePending=!0,t(()=>{this._readablePending=!1,this.destroyed||this.emit(`readable`)}))}on(e,t){return super.on(e,t),e===`data`&&this.readableFlowing!==!1&&this.resume(),e===`readable`&&(this._buffer.length>0||this._readableState.ended)&&this._scheduleReadable(),this}unshift(e){this._buffer.unshift(e),this.readableLength+=this.readableObjectMode?1:e.length??1}setEncoding(e){return this.readableEncoding=e,this}pause(){return this.readableFlowing=!1,this.emit(`pause`),this}resume(){return this.readableFlowing!==!0&&(this.readableFlowing=!0,this.emit(`resume`),this._readableState.constructed&&this._flow()),this}_flowing=!1;_flow(){if(!(this.readableFlowing!==!0||this._flowing||this.destroyed)&&this._readableState.constructed){this._flowing=!0;try{for(;this._buffer.length>0&&this.readableFlowing&&!this.destroyed;){let e=this._buffer.shift();if(this.readableLength-=this.readableObjectMode?1:e.length??1,this.readableEncoding&&typeof e!=`string`){let t=globalThis.Buffer;t&&t.isBuffer(e)?e=e.toString(this.readableEncoding):e instanceof Uint8Array&&(e=new TextDecoder(this.readableEncoding).decode(e))}this.emit(`data`,e)}if(this.destroyed)return;if(this._readableState.ended&&this._buffer.length===0&&!this._readableState.endEmitted){t(()=>this._emitEnd());return}!this._readableState.ended&&!this._readableState.reading&&!this.destroyed&&(this._readableState.reading=!0,this._read(this.readableHighWaterMark),this._readableState.reading=!1)}finally{this._flowing=!1}this._buffer.length>0&&this.readableFlowing&&!this.destroyed&&t(()=>this._flow())}}isPaused(){return this.readableFlowing===!1}unpipe(e){if(e){let t=this._pipeDests.findIndex(t=>t.dest===e);if(t!==-1){this._pipeDests[t].cleanup(),this._pipeDests.splice(t,1);let n=this._readableState.pipes.indexOf(e);n!==-1&&this._readableState.pipes.splice(n,1),e.emit(`unpipe`,this),this._pipeDests.length===0&&(this.readableFlowing=!1)}}else{for(let e of this._pipeDests)e.cleanup(),e.dest.emit(`unpipe`,this);this._pipeDests=[],this._readableState.pipes=[],this.readableFlowing=!1}return this}_destroy(e,t){this._destroyImpl?this._destroyImpl.call(this,e,t):t(e??void 0)}destroy(e){if(this.destroyed)return this;this.destroyed=!0,this.readable=!1,this.readableAborted=!this.readableEnded,e&&(this._err=e);let n=e=>{e&&t(()=>this.emit(`error`,e)),t(()=>this.emit(`close`))};return Object.prototype.hasOwnProperty.call(this,`_destroy`)?this._destroy(e??null,n):this._destroyImpl?this._destroyImpl.call(this,e??null,n):n(e),this}static toWeb(e){return new ReadableStream({start(t){e.on(`data`,e=>{typeof e==`string`?t.enqueue(new TextEncoder().encode(e)):e instanceof Uint8Array?t.enqueue(e):e&&typeof e.length==`number`&&t.enqueue(new Uint8Array(e))}),e.on(`end`,()=>{t.close()}),e.on(`error`,e=>{t.error(e)})},cancel(){e.destroy()}})}static fromWeb(t,n){let r=t.getReader();return new e({...n,read(){r.read().then(({done:e,value:t})=>{e?this.push(null):this.push(t)},e=>{this.destroy(e)})},destroy(e,t){r.cancel(e?.message).then(()=>t(null),t)}})}[Symbol.asyncIterator](){let e=this,t=[],n=!1,r=null,i=null,a=null;return e.on(`data`,e=>{if(i){let t=i;i=null,a=null,t({value:e,done:!1})}else t.push(e)}),e.on(`end`,()=>{if(n=!0,i){let e=i;i=null,a=null,e({value:void 0,done:!0})}}),e.on(`error`,e=>{if(r=e,n=!0,a){let t=a;i=null,a=null,t(e)}}),{next(){return r?Promise.reject(r):t.length>0?Promise.resolve({value:t.shift(),done:!1}):n?Promise.resolve({value:void 0,done:!0}):new Promise((e,t)=>{i=e,a=t})},return(){return e.destroy(),Promise.resolve({value:void 0,done:!0})},[Symbol.asyncIterator](){return this}}}static from(e,t){let n=new w({objectMode:!0,...t,read(){}});return typeof e==`string`||ArrayBuffer.isView(e)?(n.push(e),n.push(null),n):((async()=>{try{for await(let t of e)n.push(t)||await new Promise(e=>n.once(`drain`,e));n.push(null)}catch(e){n.destroy(e)}})(),n)}},d=class e extends l{static[Symbol.hasInstance](t){return this.prototype!==void 0&&Object.prototype.isPrototypeOf.call(this.prototype,t)?!0:this.prototype===e.prototype?t!=null&&typeof t.writableHighWaterMark==`number`:!1}writable=!0;writableHighWaterMark;writableLength=0;writableObjectMode;writableEnded=!1;writableFinished=!1;writableCorked=0;writableNeedDrain=!1;destroyed=!1;_writableState={ended:!1,finished:!1,constructed:!0,writing:!1};_corkedBuffer=[];_writeBuffer=[];_pendingConstruct=[];_ending=!1;_endCallback;_pendingEnd=null;_writeImpl;_writev;_finalImpl;_destroyImpl;_constructImpl;_decodeStrings;_defaultEncoding=`utf8`;constructor(e){super(e),this.writableHighWaterMark=e?.highWaterMark??o(e?.objectMode??!1),this.writableObjectMode=e?.objectMode??!1,this._decodeStrings=e?.decodeStrings!==!1,e?.write&&(this._writeImpl=e.write),e?.writev&&(this._writev=e.writev),e?.final&&(this._finalImpl=e.final),e?.destroy&&(this._destroyImpl=e.destroy),e?.construct&&(this._constructImpl=e.construct),(this._constructImpl||this._construct!==T.prototype._construct)&&(this._writableState.constructed=!1,t(()=>{this._construct(e=>{this._writableState.constructed=!0,e?this.destroy(e):this._maybeFlush()})}))}_construct(e){this._constructImpl?this._constructImpl.call(this,e):e()}_write(e,t,n){this._writeImpl?this._writeImpl.call(this,e,t,n):n()}_final(e){this._finalImpl?this._finalImpl.call(this,e):e()}_maybeFlush(){let e=this._pendingConstruct.splice(0);if(e.length>0){let[t,...n]=e;this._writeBuffer.push(...n),this._doWrite(t.chunk,t.encoding,t.callback)}if(this._pendingEnd){let{chunk:e,encoding:t,callback:n}=this._pendingEnd;this._pendingEnd=null,this._doEnd(e,t,n)}}_doWrite(e,n,r){this._writableState.writing=!0;let i=!0;this._write(e,n,n=>{if(this.writableLength-=this.writableObjectMode?1:e?.length??1,i){t(()=>{if(n){r(n),this.emit(`error`,n);return}r(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}),n||this._drainWriteBuffer();return}t(n?()=>{r(n),this.emit(`error`,n),this._drainWriteBuffer()}:()=>{r(),this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._drainWriteBuffer()})}),i=!1}_drainWriteBuffer(){if(this._writeBuffer.length>0){let e=this._writeBuffer.shift();this._doWrite(e.chunk,e.encoding,e.callback)}else this._writableState.writing=!1,this._maybeFinish()}_maybeFinish(){!this._ending||this._writableState.finished||this._writableState.writing||this._writeBuffer.length>0||(this._ending=!1,this._final(e=>{this.writableFinished=!0,this._writableState.finished=!0,t(()=>{e&&this.emit(`error`,e),this.emit(`finish`),t(()=>this.emit(`close`)),this._endCallback&&this._endCallback()})}))}write(e,n,r){if(typeof n==`function`&&(r=n,n=void 0),n===void 0&&(n=this._defaultEncoding),r||=(()=>{}),this._decodeStrings&&!this.writableObjectMode&&typeof e==`string`){let t=globalThis.Buffer;t&&(e=t.from(e,n),n=`buffer`)}if(typeof e!=`string`&&!this.writableObjectMode){let t=globalThis.Buffer;(t&&t.isBuffer(e)||e instanceof Uint8Array)&&(n=`buffer`)}if(this.writableEnded){let e=Error(`write after end`);return t(()=>{r&&r(e),this.emit(`error`,e)}),!1}if(this.writableLength+=this.writableObjectMode?1:e?.length??1,this.writableCorked>0)return this._corkedBuffer.push({chunk:e,encoding:n,callback:r}),this.writableLength<this.writableHighWaterMark;if(!this._writableState.constructed)return this._pendingConstruct.push({chunk:e,encoding:n,callback:r}),this.writableLength<this.writableHighWaterMark;let i=this.writableLength<this.writableHighWaterMark;return i||(this.writableNeedDrain=!0),this._writableState.writing?this._writeBuffer.push({chunk:e,encoding:n,callback:r}):this._doWrite(e,n,r),i}_doEnd(e,t,n){e!=null&&this.write(e,t),this.writableEnded=!0,this._writableState.ended=!0,this._ending=!0,this._endCallback=n,this._maybeFinish()}end(e,n,r){return typeof e==`function`&&(r=e,e=void 0),typeof n==`function`&&(r=n,n=void 0),this.writableEnded?(r&&t(r),this):this._writableState.constructed?(this._doEnd(e,n,r),this):(this._pendingEnd={chunk:e,encoding:n,callback:r},this)}cork(){this.writableCorked++}uncork(){this.writableCorked>0&&(this.writableCorked--,this.writableCorked===0&&this._corkedBuffer.length>0&&this._flushCorkedBuffer())}_flushCorkedBuffer(){if(this._writev&&this._corkedBuffer.length>1){let e=this._corkedBuffer.splice(0),t=e.map(e=>({chunk:e.chunk,encoding:e.encoding}));this._writev.call(this,t,t=>{for(let t of e)this.writableLength-=this.writableObjectMode?1:t.chunk?.length??1;if(t){for(let n of e)n.callback(t);this.emit(`error`,t)}else{for(let t of e)t.callback();this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`))}})}else{let e=this._corkedBuffer.splice(0);if(e.length>0){let[t,...n]=e;this._writeBuffer.push(...n),this._doWrite(t.chunk,t.encoding,t.callback)}}}setDefaultEncoding(e){return this._defaultEncoding=e,this}destroy(e){if(this.destroyed)return this;this.destroyed=!0,this.writable=!1,e&&(this._err=e);let n=e=>{e&&t(()=>this.emit(`error`,e)),t(()=>this.emit(`close`))};return this._destroyImpl?this._destroyImpl.call(this,e??null,n):n(e),this}},f=class extends u{writable=!0;writableHighWaterMark;writableLength=0;writableObjectMode;writableEnded=!1;writableFinished=!1;writableCorked=0;writableNeedDrain=!1;allowHalfOpen;_decodeStrings;_writableState={highWaterMark:0,objectMode:!1};_duplexCorkedBuffer=[];_duplexWriting=!1;_duplexWriteQueue=[];_writeImpl;_finalImpl;_defaultEncoding=`utf8`;_pendingWrites=0;_pendingEndCb=null;constructor(e){super(e),c(`writableHighWaterMark`,e?.writableHighWaterMark),c(`readableHighWaterMark`,e?.readableHighWaterMark),this.writableObjectMode=e?.writableObjectMode??e?.objectMode??!1,this.writableHighWaterMark=e?.highWaterMark??e?.writableHighWaterMark??o(this.writableObjectMode),this._writableState.highWaterMark=this.writableHighWaterMark,this._writableState.objectMode=this.writableObjectMode,e?.highWaterMark===void 0&&e?.readableHighWaterMark!==void 0&&(this.readableHighWaterMark=e.readableHighWaterMark,this._readableState.highWaterMark=e.readableHighWaterMark),e?.readableObjectMode!==void 0&&(this.readableObjectMode=e.readableObjectMode,this._readableState.objectMode=e.readableObjectMode,e?.readableHighWaterMark===void 0&&e?.highWaterMark===void 0&&(this.readableHighWaterMark=o(e.readableObjectMode),this._readableState.highWaterMark=this.readableHighWaterMark)),this.allowHalfOpen=e?.allowHalfOpen!==!1,this._decodeStrings=e?.decodeStrings!==!1,e?.write&&(this._writeImpl=e.write),e?.final&&(this._finalImpl=e.final),this.allowHalfOpen||this.once(`end`,()=>{this.writableEnded||t(()=>this.end())})}_write(e,t,n){this._writeImpl?this._writeImpl.call(this,e,t,n):n()}_final(e){this._finalImpl?this._finalImpl.call(this,e):e()}destroy(e){return this.destroyed?this:(this.writable=!1,super.destroy(e))}write(e,n,r){if(typeof n==`function`&&(r=n,n=void 0),n===void 0&&(n=this._defaultEncoding),this._decodeStrings&&!this.writableObjectMode&&typeof e==`string`){let t=globalThis.Buffer;t&&(e=t.from(e,n),n=`buffer`)}if(typeof e!=`string`&&!this.writableObjectMode){let t=globalThis.Buffer;(t&&t.isBuffer(e)||e instanceof Uint8Array)&&(n=`buffer`)}if(this.writableEnded){let e=Error(`write after end`),n=r||(()=>{});return t(()=>{n(e),this.emit(`error`,e)}),!1}if(this.writableLength+=this.writableObjectMode?1:e?.length??1,this.writableCorked>0)return this._duplexCorkedBuffer.push({chunk:e,encoding:n,callback:r||(()=>{})}),this.writableLength<this.writableHighWaterMark;let i=this.writableLength<this.writableHighWaterMark;i||(this.writableNeedDrain=!0);let a=r||(()=>{});return this._duplexDoWrite(e,n,a),i}_duplexDoWrite(e,t,n){if(this._duplexWriting){this._duplexWriteQueue.push({chunk:e,encoding:t,callback:n});return}this._duplexWriting=!0,this._duplexStartWrite(e,t,n)}_duplexStartWrite(e,n,r){this._pendingWrites++,this._write(e,n,n=>{this._pendingWrites--,this.writableLength-=this.writableObjectMode?1:e?.length??1,t(n?()=>{if(r(n),this._duplexWriting=!1,this.emit(`error`,n),this._duplexWriteQueue.length>0){let e=this._duplexWriteQueue.shift();this._duplexWriting=!0,this._duplexStartWrite(e.chunk,e.encoding,e.callback)}}:()=>{if(r(),this._duplexWriteQueue.length>0){let e=this._duplexWriteQueue.shift();this._duplexStartWrite(e.chunk,e.encoding,e.callback);return}if(this._duplexWriting=!1,this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,this.emit(`drain`)),this._pendingWrites===0&&this._pendingEndCb){let e=this._pendingEndCb;this._pendingEndCb=null,e()}})})}_duplexDrainQueue(){if(this._duplexWriteQueue.length>0){let e=this._duplexWriteQueue.shift();this._duplexDoWrite(e.chunk,e.encoding,e.callback)}}end(e,n,r){typeof e==`function`&&(r=e,e=void 0),typeof n==`function`&&(r=n,n=void 0),e!=null&&this.write(e,n),this.writableEnded=!0;let i=()=>{this._final(e=>{this.writableFinished=!0,this._doPrefinishHooks(()=>{t(()=>{e&&this.emit(`error`,e),this.emit(`finish`),t(()=>this.emit(`close`)),r&&r()})})})};return this._pendingWrites>0||this._duplexWriting||this._duplexWriteQueue.length>0?this._pendingEndCb=i:i(),this}_doPrefinishHooks(e){e()}cork(){this.writableCorked++}uncork(){if(this.writableCorked>0&&(this.writableCorked--,this.writableCorked===0&&this._duplexCorkedBuffer.length>0)){let e=this._duplexCorkedBuffer.splice(0);for(let{chunk:t,encoding:n,callback:r}of e)this._write(t,n,e=>{this.writableLength-=this.writableObjectMode?1:t?.length??1,e?(r(e),this.emit(`error`,e)):r()});this.writableNeedDrain&&this.writableLength<=this.writableHighWaterMark&&(this.writableNeedDrain=!1,t(()=>this.emit(`drain`)))}}setDefaultEncoding(e){return this._defaultEncoding=e,this}},p=class e extends f{constructor(e){super({...e,write:void 0,final:void 0}),e?.transform&&(this._transform=e.transform),e?.flush&&(this._flush=e.flush),e?.final&&(this._final=e.final)}_transform(e,t,n){throw Object.assign(Error(`The _transform() method is not implemented`),{code:`ERR_METHOD_NOT_IMPLEMENTED`})}_flush(e){e()}_write(e,n,r){let i=!1;try{this._transform(e,n,(e,n)=>{if(i){let e=Object.assign(Error(`Callback called multiple times`),{code:`ERR_MULTIPLE_CALLBACK`});t(()=>this.emit(`error`,e));return}if(i=!0,e){r(e);return}n!=null&&this.push(n),r()})}catch(e){if(e?.code===`ERR_METHOD_NOT_IMPLEMENTED`)throw e;r(e)}}_final(e){this._flush((t,n)=>{if(t){e(t);return}n!=null&&this.push(n),this.push(null),e()})}_doPrefinishHooks(t){let n=e.prototype._final;this._final===n?t():n.call(this,t)}},m=class extends p{constructor(e){super({...e,transform(e,t,n){n(null,e)}})}};function h(...e){let t=typeof e[e.length-1]==`function`?e.pop():void 0,n=e;if(n.length<2)throw Error(`pipeline requires at least 2 streams`);let r=null;function i(e){if(!r){r=e;for(let e of n)typeof e.destroy==`function`&&e.destroy();t&&t(e)}}let a=n[0];for(let e=1;e<n.length;e++){let t=n[e];a.pipe(t),a.on(`error`,i),a=t}let o=n[n.length-1];return o.on(`error`,i),o.on(`finish`,()=>{t&&!r&&t(null)}),o}function g(e,t,r){let i;i=typeof t==`function`?t:r;let a=!1;function o(e){a||(a=!0,i(e))}let s=()=>o(),c=()=>o(),l=e=>o(e),u=()=>{!e.writableFinished&&!e.readableEnded&&o(Error(`premature close`))};e.on(`finish`,s),e.on(`end`,c),e.on(`error`,l),e.on(`close`,u);let d=typeof e.write==`function`,f=typeof e.read==`function`,p=e.writableFinished===!0,m=e.readableEnded===!0;if(e.destroyed===!0){let t=e._err;n(t?()=>o(t):d&&p||f&&m?()=>o():()=>o(Error(`premature close`)))}else (d&&!f&&p||!d&&f&&m||d&&f&&p&&m)&&n(()=>o());return function(){e.removeListener(`finish`,s),e.removeListener(`end`,c),e.removeListener(`error`,l),e.removeListener(`close`,u)}}function _(e,t){if(!(e instanceof AbortSignal))throw TypeError(`The first argument must be an AbortSignal`);if(!(t instanceof C))throw TypeError(`The second argument must be a Stream`);if(e.aborted)t.destroy(Error(`The operation was aborted`));else{let n=()=>{t.destroy(Error(`The operation was aborted`))};e.addEventListener(`abort`,n,{once:!0}),t.once(`close`,()=>{e.removeEventListener(`abort`,n)})}return t}function v(e){if(e==null)return!1;let t=e;return typeof t.readable!=`boolean`||typeof t.read!=`function`||t.destroyed===!0||t.readableEnded===!0?!1:t.readable===!0}function y(e){if(e==null)return!1;let t=e;return typeof t.writable!=`boolean`||typeof t.write!=`function`||t.destroyed===!0||t.writableEnded===!0?!1:t.writable===!0}function b(e){return e==null?!1:e.destroyed===!0}function x(e){if(e==null)return!1;let t=e;return t.readableDidRead===!0||t.readableFlowing!==null&&t.readableFlowing!==void 0}function S(e){if(e==null)return!1;let t=e;return t.destroyed===!0&&typeof t.readable==`boolean`&&t.readable===!1||t.destroyed===!0&&typeof t.writable==`boolean`&&t.writable===!1}const C=e(l),w=e(u),T=e(d),E=e(f),D=e(p),O=e(m),k=Object.assign(C,{Stream:C,Readable:w,Writable:T,Duplex:E,Transform:D,PassThrough:O,pipeline:h,finished:g,addAbortSignal:_,isReadable:v,isWritable:y,isDestroyed:b,isDisturbed:x,isErrored:S,getDefaultHighWaterMark:o,setDefaultHighWaterMark:s});export{E as Duplex,O as PassThrough,w as Readable,C as Stream,D as Transform,T as Writable,_ as addAbortSignal,k as default,g as finished,o as getDefaultHighWaterMark,b as isDestroyed,x as isDisturbed,S as isErrored,v as isReadable,y as isWritable,h as pipeline,s as setDefaultHighWaterMark};