@gjsify/stream 0.3.13 → 0.3.15

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