h2lean 0.9.1 → 0.10.0

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/stream.js CHANGED
@@ -6,19 +6,23 @@
6
6
  // extends Duplex (internal/http2/core.js:2128), but the part of that surface real code reaches
7
7
  // for is pipe() on the readable half, and the Duplex machinery behind it -- two state objects
8
8
  // plus the nextTick read loop -- is what OPTIMIZATION.md item 41 measured as ~+1.4 us/req
9
- // against the EventEmitter arm. Stream.prototype.pipe supplies that one method without the
10
- // cost. So `stream.pipe(dest)` works (test/pipe-parity.test.js). cork()/uncork() and the
11
- // writableCorked/writableHighWaterMark getters are present too, but as a counting stub:
9
+ // against the EventEmitter arm. h2lean therefore carries the Duplex SURFACE as methods and
10
+ // getters over the hand-rolled core: pipe() is not the legacy Stream.prototype.pipe but
11
+ // node's Readable.prototype.pipe reimplemented on this base (tracked destinations,
12
+ // unpipe(), the destroy-time EOF that ends and unpipes the dest -- test/pipe-parity.test.js),
13
+ // and read()/push()/setEncoding() are node's readable pull surface with the same
14
+ // member-by-member derivation (test/duplex-surface.test.js), and so is the async
15
+ // iteration surface -- [Symbol.asyncIterator], iterator(), the operator helpers and
16
+ // compose() -- ported member-by-member from node v26's createAsyncIterator,
17
+ // operators.js and compose.js; web streams are refused by compose() where node
18
+ // composes them; writev() is absent because
19
+ // node itself throws TypeError on it here, and cork()/uncork() and the
20
+ // writableCorked/writableHighWaterMark getters are present as a counting stub:
12
21
  // node's Writable cork buffers write()/end() and defers the DATA until corked reaches 0
13
22
  // (measured on v26.12.1: write('AAA') while corked leaves writableLength 3 and the peer
14
23
  // receives nothing until the second uncork), while h2lean writes straight through -- its
15
24
  // per-read socket batch already coalesces a synchronous burst, so only the cross-tick
16
- // deferral differs. KNOWN DIVERGENCE, pinned in test/cork-parity.test.js. The rest of the
17
- // Duplex surface -- unpipe(), read(), writev() and the readable/writable/writableLength
18
- // state getters -- is still absent (AGENTS.md section 10). The one behavioural difference the
19
- // bare base leaves is pipe teardown: legacy Stream.prototype.pipe ends the dest only on the
20
- // source 'end', so a stream destroyed mid-pipe leaves the dest without the 'finish'/'unpipe'
21
- // node's Duplex pipe emits. Measured and pinned in test/pipe-parity.test.js.
25
+ // deferral differs. KNOWN DIVERGENCE, pinned in test/cork-parity.test.js.
22
26
  // * the read side releases flow-control credit as the application takes the
23
27
  // bytes. With no reader the peer's window stays shut, so an unread body
24
28
  // costs the sender instead of our heap; data that arrives before anyone is
@@ -83,8 +87,10 @@
83
87
 
84
88
  const fs = require('node:fs');
85
89
  const { inspect } = require('node:util');
86
- const { Stream, Writable } = require('node:stream');
90
+ const { Stream, Writable, Readable, Duplex, finished, addAbortSignal, destroy: destroyStream } =
91
+ require('node:stream');
87
92
  const { deprecate } = require('node:util');
93
+ const { StringDecoder } = require('node:string_decoder');
88
94
  const frames = require('./frames');
89
95
  const hdr = require('./headers');
90
96
 
@@ -97,6 +103,12 @@ const EMPTY = Buffer.alloc(0);
97
103
  // stream's writableHighWaterMark on v26.12.1.
98
104
  const WRITABLE_HWM = new Writable().writableHighWaterMark;
99
105
 
106
+ // The same for the readable half: node's Http2Stream sets no readable highWaterMark
107
+ // either, so readableHighWaterMark is the Readable default -- 16384 on node 20, 65536
108
+ // from 22 on, measured on live server streams of all four majors and equal to
109
+ // `new Readable().readableHighWaterMark` on each.
110
+ const READABLE_HWM = new Readable().readableHighWaterMark;
111
+
100
112
  // process.nextTick(fn, args) instead of an arrow closure per event: the arrow
101
113
  // allocated a new function object for every request, and in the compat layer
102
114
  // that showed up as GC time.
@@ -109,10 +121,35 @@ function emitNT(target, name, arg) {
109
121
  }
110
122
 
111
123
  function emitErrorCloseNT(target, err) {
124
+ target._errorEmitted = true;
125
+ target._streamErrored = err;
112
126
  target.emit('error', err);
113
127
  target.emit('close');
114
128
  }
115
129
 
130
+ // The 'error' of the write-after-end shape: emitted on a stream that closes by itself
131
+ // a moment later, so 'close' is NOT this helper's job -- but the Duplex getters read the
132
+ // same two slots, and node's errorOrDestroy fills state.errored BEFORE the event, not at
133
+ // the emit (destroy.js checkError). Same moment here: the nextTick that carries the
134
+ // event is the nextTick that ran the flag set in emitErrorCloseNT anyway.
135
+ function emitErrorOnlyNT(target, err) {
136
+ target._errorEmitted = true;
137
+ if (target._streamErrored === undefined) {
138
+ target._streamErrored = err;
139
+ }
140
+ target.emit('error', err);
141
+ }
142
+
143
+ // 'end' with the Duplex bookkeeping: readableEnded/buffer-free readable read node's
144
+ // endEmitted bit, and the bit flips at the delivery, not at the schedule.
145
+ function emitEndNT(target) {
146
+ if (target._eofEmitted === true) {
147
+ return; // the 'end' of a Duplex is once-only; the drain paths can re-arm it
148
+ }
149
+ target._eofEmitted = true;
150
+ target.emit('end');
151
+ }
152
+
116
153
  // node's onStreamTrailers (internal/http2/core.js), the callback nghttp2 runs when the
117
154
  // writable half of a stream that asked for trailers finishes. Two parts of it are easy
118
155
  // to lose: `trailersReady` is set before the destroyed/closed check (so a stream that is
@@ -146,7 +183,10 @@ function emitEndCloseNT(target) {
146
183
  // events go out (internal/http2/core.js:2546) -- see _closeNow for why the drop waits
147
184
  // for this tick here.
148
185
  target.session = undefined;
149
- target.emit('end');
186
+ if (target._eofEmitted !== true) {
187
+ target._eofEmitted = true;
188
+ target.emit('end');
189
+ }
150
190
  target.emit('close');
151
191
  }
152
192
 
@@ -168,7 +208,7 @@ function autoCloseNT(stream) {
168
208
  if (stream._destroyed) {
169
209
  return;
170
210
  }
171
- process.nextTick(emitNT, stream, 'end');
211
+ process.nextTick(emitEndNT, stream);
172
212
  stream._destroy(NO_ERROR, undefined, true);
173
213
  }
174
214
 
@@ -344,6 +384,8 @@ class Http2Stream extends Stream {
344
384
  this._bodyLen = 0; // ...octets of body actually received
345
385
  this._queued = null; // Buffers waiting on window credit
346
386
  this._pending = null; // inbound chunks nobody has read yet
387
+ this._pipes = null; // destinations of pipe(), node's state.pipes
388
+ this._awaitDrain = null; // ...a dest whose false write still parks the flow
347
389
  this._endPending = false; // END_STREAM arrived with no reader
348
390
  this._consumeState = 0; // 0 no reader, 1 delivering, 2 reader is full
349
391
  this._endQueued = false;
@@ -423,6 +465,164 @@ class Http2Stream extends Stream {
423
465
  return this._sentView;
424
466
  }
425
467
 
468
+ // --- the Duplex state surface ------------------------------------------------
469
+ //
470
+ // Measured member-by-member off a live node server stream and read out of node's own
471
+ // internals (internal/streams/readable.js, internal/streams/writable.js, core.js
472
+ // bufferSize/headRequest; tools/probe-duplex-surface.js is the transcript, and
473
+ // test/duplex-surface.test.js pins the table). Every getter is computed from state this
474
+ // file already keeps, plus five lazily-set booleans (_eofEmitted, _errorEmitted,
475
+ // _dataRead, _flowing, _needDrain) written at the event/decision points below --
476
+ // no constructor additions, nothing allocated unless an application reads the member.
477
+ //
478
+ // The one deliberate divergence: writableLength/writableBuffer/bufferSize report the
479
+ // octets THIS stream still parks on window credit. node counts the bytes sitting in the
480
+ // JS Writable buffer before nghttp2 takes them (writableLength) PLUS the ones nghttp2
481
+ // holds (core.js bufferSize = writeQueueSize + writableLength, which double-counts a
482
+ // stalled write: measured 4096 queued reads 4096 and 8192); h2lean accepts a write into
483
+ // the session's staging buffer inside the call, so there is no JS-side buffer to show.
484
+ // Same write-through decision as the cork stub (header above, test/cork-parity.test.js).
485
+
486
+ // node: `!r.destroyed && !r.errorEmitted && !r.endEmitted` -- readable-side, not
487
+ // half-open-ness: a stream that has emitted 'end' reads false with both halves alive.
488
+ get readable() {
489
+ return !this._destroyed && this._errorEmitted !== true && this._eofEmitted !== true;
490
+ }
491
+
492
+ // node's readableDidRead is the dataEmitted bit (readable.js:1857): true once any
493
+ // delivery of octets happened -- through a 'data' event OR a successful read(), because
494
+ // node's read() itself emits 'data' on every chunk it hands back (readable.js read()
495
+ // tail, measured: three reads delivered three data events to a listener attached for
496
+ // the second one).
497
+ get readableDidRead() {
498
+ return this._dataRead === true;
499
+ }
500
+
501
+ // endEmitted, not "the peer's END arrived": false until THIS stream has emitted 'end'.
502
+ get readableEnded() {
503
+ return this._eofEmitted === true;
504
+ }
505
+
506
+ // node's tri-state (readable.js:1901): null until anything ever touches the readable
507
+ // side, true while it flows, false while paused. Measured boundaries: attaching a
508
+ // 'readable' listener reads false, a 'data' listener or resume() reads true, pause()
509
+ // reads false again, and a destroyed stream reads false. The compat path never sets it
510
+ // -- node's compat reads the stream through a 'readable' subscription, so a getter read
511
+ // on a compat stream reports false there; h2lean's compat dispatch does not subscribe
512
+ // (AGENTS.md 5), so an untouched compat-mode stream reads null. Written-up divergence,
513
+ // invisible unless an application mixes the two APIs.
514
+ get readableFlowing() {
515
+ return this._flowing === undefined ? null : this._flowing;
516
+ }
517
+
518
+ // node: `readable !== false && (destroyed || errored) && !endEmitted`.
519
+ get readableAborted() {
520
+ return (this._destroyed || this._streamErrored !== undefined) &&
521
+ this._eofEmitted !== true;
522
+ }
523
+
524
+ get readableEncoding() {
525
+ return this._encoding === undefined ? null : this._encoding;
526
+ }
527
+
528
+ get readableHighWaterMark() {
529
+ return READABLE_HWM;
530
+ }
531
+
532
+ get readableObjectMode() {
533
+ return false;
534
+ }
535
+
536
+ get readableLength() {
537
+ const pending = this._pending;
538
+ if (pending === null) {
539
+ return 0;
540
+ }
541
+ let n = 0;
542
+ for (let i = 0; i < pending.length; i++) {
543
+ const c = pending[i];
544
+ n += c.length === undefined ? c.data.length : c.length;
545
+ }
546
+ return n;
547
+ }
548
+
549
+ get readableBuffer() {
550
+ // node returns the buffer list itself; h2lean hands out a copy -- the live array would
551
+ // let the caller splice chunks out from under the replay queue. Pushed entries are
552
+ // reported as the buffers they hold, which is what node's list shows.
553
+ const pending = this._pending;
554
+ if (pending === null) {
555
+ return [];
556
+ }
557
+ const out = new Array(pending.length);
558
+ for (let i = 0; i < pending.length; i++) {
559
+ const c = pending[i];
560
+ out[i] = c.length === undefined ? c.data : c;
561
+ }
562
+ return out;
563
+ }
564
+
565
+ // node: `(kEnding | kEnded | kDestroyed | kErrored) === 0`.
566
+ get writable() {
567
+ return !this._destroyed && !this._ending && this._streamErrored === undefined;
568
+ }
569
+
570
+ // node's kEnding bit. A plain destroy() ends the writable inside closeStream
571
+ // (`if (!ending) stream.end()`, core.js:2088) -- h2lean reports that without touching
572
+ // _ending (which carries the 'aborted' decision); a destroy WITH an error does not set
573
+ // it, because node's end() skips kEnding on an errored writable (writable.js:876) --
574
+ // measured: the push-after-EOF snapshot reads writableEnded false with writable false.
575
+ get writableEnded() {
576
+ return this._ending || (this._destroyed && this._streamErrored === undefined);
577
+ }
578
+
579
+ get writableObjectMode() {
580
+ return false;
581
+ }
582
+
583
+ get writableLength() {
584
+ const queued = this._queued;
585
+ if (queued === null) {
586
+ return 0;
587
+ }
588
+ let n = 0;
589
+ for (let i = 0; i < queued.length; i++) {
590
+ n += queued[i].length;
591
+ }
592
+ return n;
593
+ }
594
+
595
+ get writableBuffer() {
596
+ return this._queued === null ? [] : this._queued.slice();
597
+ }
598
+
599
+ // node: `kNeedDrain` set and neither destroyed nor ending. h2lean flips the flag from
600
+ // the write()/end() accept verdict -- false when the window still takes bytes, true
601
+ // when the send queue parked them -- and the session clears it as the queue drains.
602
+ get writableNeedDrain() {
603
+ return this._needDrain === true && !this._destroyed && !this._ending;
604
+ }
605
+
606
+ // core.js:2215: `writeQueueSize + writableLength`. The nghttp2 queue this file has no
607
+ // equivalent for (write-through, header above), so the second term is the whole number.
608
+ get bufferSize() {
609
+ return this.writableLength;
610
+ }
611
+
612
+ // node keeps one `errored` per half; the public getter is the READABLE one
613
+ // (readable.js:1939). It holds the Error an 'error' is delivering, set when destroy
614
+ // runs with an error (destroy.js checkError), not when the event fires.
615
+ get errored() {
616
+ return this._streamErrored === undefined ? null : this._streamErrored;
617
+ }
618
+
619
+ // core.js: `!!(flags & STREAM_FLAGS_HEAD_REQUEST)`, set at stream creation from the
620
+ // request line. Same fact in h2lean, read where respond() tests it already: the flag
621
+ // source is the request map, so there is no state to keep out of sync.
622
+ get headRequest() {
623
+ return this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
624
+ }
625
+
426
626
  respond(headers, options) {
427
627
  // node guards the stream's life first (internal/http2/core.js respond():
428
628
  // `if (this.destroyed || this.closed) throw new ERR_HTTP2_INVALID_STREAM()`),
@@ -811,12 +1011,19 @@ class Http2Stream extends Stream {
811
1011
  // the event is owed here instead. A reset or a session destroy is not
812
1012
  // this shape -- there node's errorOrDestroy is a no-op and no 'error'
813
1013
  // goes out (the session-destroy case of test/upstream-push.test.js).
814
- process.nextTick(emitNT, this, 'error', err);
1014
+ process.nextTick(emitErrorOnlyNT, this, err);
815
1015
  }
816
1016
  return false;
817
1017
  }
818
- const buf = typeof chunk === 'string' ? Buffer.from(chunk, encoding || 'utf8') : chunk;
1018
+ // node's encodeString: an encoding-less write(string) uses the writable
1019
+ // default, which setDefaultEncoding is the way to change (writable.js:465).
1020
+ const buf = typeof chunk === 'string'
1021
+ ? Buffer.from(chunk, encoding || this._defaultEnc || 'utf8') : chunk;
819
1022
  const canContinue = this.session.sendData(this, buf, false);
1023
+ // writableNeedDrain is node's needDrain bit: set when a write left the buffer
1024
+ // over the highWaterMark, cleared when the buffer drops back under it (the
1025
+ // session's drain path). It reports the credit stall, nothing else.
1026
+ this._needDrain = !canContinue;
820
1027
  if (cb) {
821
1028
  process.nextTick(cb);
822
1029
  }
@@ -1144,19 +1351,887 @@ class Http2Stream extends Stream {
1144
1351
  // so the sender is the one that waits, and whatever arrives in the meantime is
1145
1352
  // buffered and replayed on resume(). Returns this, like the Duplex does.
1146
1353
  pause() {
1354
+ this._flowing = false;
1147
1355
  this._pauseConsuming();
1148
1356
  return this;
1149
1357
  }
1150
1358
 
1151
1359
  resume() {
1152
- this._startConsuming();
1360
+ this._flowing = true;
1361
+ this._scheduleResume();
1153
1362
  return this;
1154
1363
  }
1155
1364
 
1365
+ // node's resume() flips the flowing bit synchronously but the delivery itself
1366
+ // runs on the kResumeScheduled next tick, and an attaching 'data' listener only
1367
+ // calls resume when the stream is neither explicitly paused nor in pull mode --
1368
+ // the 'readable' attach has set kHasFlowing, and measured: a 'data' attach
1369
+ // inside a pull handler leaves the buffer for read() untouched.
1370
+ _scheduleResume() {
1371
+ if (this._resumeScheduled === true || this._flowing === false ||
1372
+ this._destroyed) {
1373
+ return;
1374
+ }
1375
+ this._resumeScheduled = true;
1376
+ process.nextTick(() => {
1377
+ this._resumeScheduled = false;
1378
+ if (this._destroyed || this._flowing === false) {
1379
+ return;
1380
+ }
1381
+ this._startConsuming();
1382
+ });
1383
+ }
1384
+
1156
1385
  isPaused() {
1157
1386
  return this._consumeState === 2;
1158
1387
  }
1159
1388
 
1389
+ // --- the readable pull surface: read() and push() -----------------------------
1390
+ //
1391
+ // A mini-Readable over the existing `_pending` queue, reproduced member by
1392
+ // member from internal/streams/readable.js (v26) and pinned against a live
1393
+ // node by tools/probe-duplex-surface.js: an arrival emits 'readable' and
1394
+ // nothing else until the application pulls; read() with no argument returns
1395
+ // the whole first chunk, read(n) merges across chunks and hands the
1396
+ // remainder back, an ask past the buffered end returns what the queue can
1397
+ // cover (nothing at all before the EOF is known), every data-returning read
1398
+ // flips dataRead and emits 'data', and a read past the end of an empty,
1399
+ // EOF-known queue schedules the end-of-stream. push() after the EOF errors
1400
+ // with ERR_STREAM_PUSH_AFTER_EOF through 'error', push() on a destroyed
1401
+ // stream is a silent false, push(null) always returns false. The queue holds
1402
+ // two entry kinds: a bare Buffer is octets off the socket (credit-owed), a
1403
+ // `{ data }` wrapper is octets the application pushed (never credited — they
1404
+ // never came off the wire, and crediting them would let a peer send bytes we
1405
+ // never advertised).
1406
+ //
1407
+ // The EOF becomes known to node when the END_STREAM is processed in the read
1408
+ // callback — measured by stack (stream_base_commons:236 -> Readable.push ->
1409
+ // onEofChunk): that push(null) emits 'readable' synchronously from
1410
+ // onEofChunk's non-sync branch, and onStreamClose pushes it again for the
1411
+ // paths that end without a final frame (reset, teardown). h2lean knows the
1412
+ // EOF at the same frame and parks it in `_endPending` when no reader is
1413
+ // watching, which matches the visible sequences (data, end, close, and the
1414
+ // measured-identical push-after-EOF matrix) with the parked EOF standing in
1415
+ // for the buffered one.
1416
+
1417
+ read(n) {
1418
+ // node's argument normalisation, kept exact: no argument is NaN and means
1419
+ // the whole first chunk; a non-integer goes through parseInt.
1420
+ if (n === undefined) {
1421
+ n = NaN;
1422
+ } else if (!Number.isInteger(n)) {
1423
+ n = Number.parseInt(n, 10);
1424
+ }
1425
+ if (this._destroyed) {
1426
+ return null;
1427
+ }
1428
+ const pending = this._pending;
1429
+ let avail = 0;
1430
+ let firstLen = 0;
1431
+ if (pending !== null) {
1432
+ for (let i = 0; i < pending.length; i++) {
1433
+ const c = pending[i];
1434
+ const l = c.length === undefined ? c.data.length : c.length;
1435
+ avail += l;
1436
+ if (i === 0) {
1437
+ firstLen = l;
1438
+ }
1439
+ }
1440
+ }
1441
+ // howMuchToRead, byte mode (readable.js:678): the NaN fast path is the
1442
+ // first chunk's length; more-than-buffered is only satisfiable past the
1443
+ // EOF, where the whole remainder comes back instead.
1444
+ const eofKnown = this._eofSeen === true || this._endPending === true;
1445
+ let want;
1446
+ if (n <= 0 || (avail === 0 && eofKnown)) {
1447
+ want = 0;
1448
+ } else if (Number.isNaN(n)) {
1449
+ // node's decoder branch of howMuchToRead (readable.js:684): the
1450
+ // one-chunk-at-a-time fast path belongs to flowing mode -- in pull mode
1451
+ // an argumentless read returns the WHOLE buffered character count,
1452
+ // because the queue now holds strings, not buffers.
1453
+ want = this._decoder === undefined ? firstLen
1454
+ : (this._flowing === true && avail !== 0) ? firstLen : avail;
1455
+ } else if (n <= avail) {
1456
+ want = n;
1457
+ } else {
1458
+ want = eofKnown ? avail : 0;
1459
+ }
1460
+ let ret = null;
1461
+ if (want > 0) {
1462
+ ret = this._takeQueued(want);
1463
+ }
1464
+ if (this._pending === null || this._pending.length === 0) {
1465
+ // the tail of node's read(): asking past what the queue holds — node
1466
+ // compares the asked amount with what howMuchToRead allowed (nOrig !== n),
1467
+ // which the argumentless NaN form always is — with the EOF known and
1468
+ // nothing left is what schedules the end-of-stream: endReadable.
1469
+ if (n !== want && eofKnown) {
1470
+ this._scheduleEOF();
1471
+ } else if (!eofKnown && typeof this._read === 'function') {
1472
+ // node fires maybeReadMore after a consumption drops the buffer below
1473
+ // the mark, and that is where _read gets called -- the only thing in
1474
+ // h2lean that installs an _read is the legacy wrap(), whose paused
1475
+ // source needs exactly this nudge to continue; the empty-and-not-EOF
1476
+ // condition is where node's own call lands for a pull consumer.
1477
+ this._read();
1478
+ }
1479
+ }
1480
+ if (ret !== null && this._errorEmitted !== true && this._closeDelivered !== true) {
1481
+ // node's read() hands the chunk to the consumer as a 'data' event too —
1482
+ // measured: three reads delivered three data events to a listener
1483
+ // attached for the second one. dataEmitted flips with the emission.
1484
+ this._dataRead = true;
1485
+ this.emit('data', ret);
1486
+ }
1487
+ return ret;
1488
+ }
1489
+
1490
+ // Pull `n` octets off the queue: the exact-first-chunk case returns the buffer
1491
+ // view itself (no copy, the AGENTS.md 5 rule that a chunk the app holds is
1492
+ // never recycled); a read that splits or merges allocates one buffer and
1493
+ // re-queues the remainder with the origin it had. Credit goes out for the
1494
+ // wire octets handed over, in one call, only for them.
1495
+ _takeQueued(n) {
1496
+ const pending = this._pending;
1497
+ const first = pending[0];
1498
+ const firstLen = first.length === undefined ? first.data.length : first.length;
1499
+ if (firstLen === n) {
1500
+ pending.shift();
1501
+ if (pending.length === 0) {
1502
+ this._pending = null;
1503
+ }
1504
+ if (first.length !== undefined) {
1505
+ this._release(n);
1506
+ return first;
1507
+ }
1508
+ if (first.bytes !== undefined) {
1509
+ this._release(first.bytes);
1510
+ }
1511
+ return first.data;
1512
+ }
1513
+ if (first.length === undefined && typeof first.data === 'string') {
1514
+ // node's fromList decoder branch (readable.js:2060): string entries
1515
+ // concatenate toward the asked length and a split lands on character
1516
+ // boundaries. The wire octets an entry stands for are credited per slice
1517
+ // by the slice's own length in the encoding -- the queue is homogeneous
1518
+ // once an encoding is set (setEncoding merged what stood there, every
1519
+ // later arrival is decoded at the door), so a string entry is the only
1520
+ // kind this loop sees.
1521
+ let ret = '';
1522
+ let need = n;
1523
+ let j = 0;
1524
+ while (need > 0) {
1525
+ const e = pending[j];
1526
+ const s = e.data;
1527
+ if (need > s.length) {
1528
+ ret += s;
1529
+ need -= s.length;
1530
+ if (e.bytes !== undefined) {
1531
+ this._release(e.bytes);
1532
+ }
1533
+ j++;
1534
+ } else {
1535
+ if (need === s.length) {
1536
+ ret += s;
1537
+ if (e.bytes !== undefined) {
1538
+ this._release(e.bytes);
1539
+ }
1540
+ j++;
1541
+ } else {
1542
+ const head = s.slice(0, need);
1543
+ ret += head;
1544
+ if (e.bytes !== undefined) {
1545
+ const owed = Math.min(Buffer.byteLength(head, this._encoding), e.bytes);
1546
+ this._release(owed);
1547
+ e.bytes -= owed;
1548
+ }
1549
+ e.data = s.slice(need);
1550
+ }
1551
+ need = 0;
1552
+ }
1553
+ }
1554
+ if (j > 0) {
1555
+ pending.splice(0, j);
1556
+ }
1557
+ if (pending.length === 0) {
1558
+ this._pending = null;
1559
+ }
1560
+ return ret;
1561
+ }
1562
+ const out = Buffer.allocUnsafe(n);
1563
+ let off = 0;
1564
+ let i = 0;
1565
+ let wire = 0;
1566
+ while (off < n) {
1567
+ const c = pending[i];
1568
+ const buf = c.length === undefined ? c.data : c;
1569
+ const take = buf.length <= n - off ? buf.length : n - off;
1570
+ buf.copy(out, off, 0, take);
1571
+ off += take;
1572
+ if (c.length !== undefined) {
1573
+ wire += take;
1574
+ }
1575
+ if (take === buf.length) {
1576
+ i++;
1577
+ } else {
1578
+ pending[i] = c.length === undefined ? { data: buf.subarray(take) } : buf.subarray(take);
1579
+ }
1580
+ }
1581
+ if (i > 0) {
1582
+ pending.splice(0, i);
1583
+ }
1584
+ if (pending.length === 0) {
1585
+ this._pending = null;
1586
+ }
1587
+ if (wire !== 0) {
1588
+ this._release(wire);
1589
+ }
1590
+ return out;
1591
+ }
1592
+
1593
+ // node's Writable-side sibling call: push queued readable data with NO wire
1594
+ // accounting — the octets did not come off the socket, so _release must never
1595
+ // see them (a credit for them would advertise window the peer never spent).
1596
+ push(chunk, encoding) {
1597
+ if (chunk === null) {
1598
+ // push(null) is the EOF into the readable queue: it never returns true and
1599
+ // is silent when the EOF is already owed (node's onEofChunk early return).
1600
+ if (!this._eofSeen && !this._endPending && this._eofEmitted !== true) {
1601
+ this._eofSeen = true;
1602
+ this._endPending = true;
1603
+ this._flushDecoder();
1604
+ if (this._pending === null || this._pending.length === 0) {
1605
+ if (this._isConsuming()) {
1606
+ this._endPending = false;
1607
+ this._scheduleEOF();
1608
+ } else if (this.listenerCount('readable') > 0) {
1609
+ // node's onEofChunk sync branch, same mechanism as the wire EOF in
1610
+ // _remoteEnded: the pull consumer is woken synchronously, and the
1611
+ // 'end' waits for a read() (or a resume) that reaches the EOF.
1612
+ this.emit('readable');
1613
+ }
1614
+ }
1615
+ }
1616
+ return false;
1617
+ }
1618
+ if (chunk === undefined) {
1619
+ // node's byte-mode chain lets undefined fall past the type error into the
1620
+ // empty-chunk branch: no queueing, no event, the canPushMore return only.
1621
+ return this._canPushMore();
1622
+ }
1623
+ // node's readableAddChunkPushByteMode order is load-bearing: convert,
1624
+ // then the empty-chunk branch, and only after it the after-EOF error and
1625
+ // the destroyed silence -- an empty chunk after EOF returns canPushMore,
1626
+ // it does not error.
1627
+ let buf = chunk;
1628
+ let enc = encoding;
1629
+ if (typeof buf === 'string') {
1630
+ if (enc === undefined || enc === '') {
1631
+ enc = 'utf8'; // the readable side's defaultEncoding; setDefaultEncoding is the WRITABLE's
1632
+ }
1633
+ if (this._encoding !== enc) {
1634
+ buf = Buffer.from(buf, enc);
1635
+ enc = '';
1636
+ }
1637
+ } else if (buf instanceof Buffer) {
1638
+ enc = '';
1639
+ } else if (ArrayBuffer.isView(buf)) {
1640
+ buf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
1641
+ enc = '';
1642
+ } else {
1643
+ this.destroy(errorOf('ERR_INVALID_ARG_TYPE',
1644
+ 'The "chunk" argument must be of type string or an instance of Buffer, ArrayBufferView, or DataView'));
1645
+ return false;
1646
+ }
1647
+ if (buf.length === 0) {
1648
+ return this._canPushMore();
1649
+ }
1650
+ if (this._eofSeen === true || this._eofEmitted === true) {
1651
+ const err = errorOf('ERR_STREAM_PUSH_AFTER_EOF', 'push() after EOF');
1652
+ if (!this._destroyed) {
1653
+ // node's errorOrDestroy destroys the stream through its autoDestroy, so
1654
+ // this arrives as 'error' then 'close' on the next ticks — the same
1655
+ // route the write-after-end shape takes in write() above.
1656
+ this.destroy(err);
1657
+ }
1658
+ return false;
1659
+ }
1660
+ if (this._destroyed || this._errorEmitted === true) {
1661
+ return false; // node: kDestroyed|kErrored is the silent false
1662
+ }
1663
+ if (this._decoder !== undefined && !enc) {
1664
+ // decode at the door, node's kDecoder branch: the queue holds characters
1665
+ // from here on. A chunk the decoder swallowed whole (a split multi-byte
1666
+ // sequence) queues nothing and wakes nothing -- canPushMore only.
1667
+ const str = this._decoder.write(buf);
1668
+ if (str.length === 0) {
1669
+ return this._canPushMore();
1670
+ }
1671
+ buf = str;
1672
+ }
1673
+ if (this._pending === null) {
1674
+ this._pending = [];
1675
+ }
1676
+ this._pending.push({ data: buf });
1677
+ this._scheduleReadable();
1678
+ return this._canPushMore();
1679
+ }
1680
+
1681
+ // node's canPushMore: below the watermark, or nothing buffered, and never
1682
+ // past the EOF the readable queue has received.
1683
+ _canPushMore() {
1684
+ if (this._eofSeen === true) {
1685
+ return false;
1686
+ }
1687
+ const n = this.readableLength;
1688
+ return n < READABLE_HWM || n === 0;
1689
+ }
1690
+
1691
+ // node's Readable.prototype.setEncoding (readable.js:631), member by member:
1692
+ // a FRESH StringDecoder replaces whatever was set before (an unknown name
1693
+ // throws ERR_UNKNOWN_ENCODING synchronously out of the StringDecoder
1694
+ // constructor; `null` and `undefined` decode as utf8, and the getter reports
1695
+ // what the decoder normalised, not what the caller passed), the octets
1696
+ // already queued are decoded through it and merged into ONE string entry, and
1697
+ // if the EOF is already known the decoder's flush rides along. From here the
1698
+ // queue holds strings and `readableLength` counts characters -- node's
1699
+ // state.length does the same once a decoder exists, which is why the
1700
+ // watermark arithmetic in _canPushMore needs no special case. The wire
1701
+ // octets the merged string stands for stay credited as a bundle on its
1702
+ // consumption (the `bytes` field), so a setEncoding between DATA frames
1703
+ // cannot leak or invent window.
1704
+ setEncoding(enc) {
1705
+ const decoder = new StringDecoder(enc);
1706
+ this._decoder = decoder;
1707
+ this._encoding = decoder.encoding;
1708
+ const pending = this._pending;
1709
+ if (pending !== null) {
1710
+ let content = '';
1711
+ // octets the old decoder still held: they were never delivered and were
1712
+ // never credited; the merged entry inherits the debt.
1713
+ let wire = this._decHeld === undefined ? 0 : this._decHeld;
1714
+ this._decHeld = undefined;
1715
+ for (let i = 0; i < pending.length; i++) {
1716
+ const c = pending[i];
1717
+ if (c.length !== undefined) {
1718
+ content += decoder.write(c);
1719
+ wire += c.length;
1720
+ } else {
1721
+ content += decoder.write(c.data);
1722
+ if (c.bytes !== undefined) {
1723
+ wire += c.bytes;
1724
+ }
1725
+ }
1726
+ }
1727
+ if (this._eofSeen === true || this._endPending === true) {
1728
+ content += decoder.end();
1729
+ }
1730
+ pending.length = 0;
1731
+ this._pending = null;
1732
+ if (content !== '') {
1733
+ this._pending = [{ data: content, bytes: wire }];
1734
+ }
1735
+ }
1736
+ return this;
1737
+ }
1738
+
1739
+ // node's Writable.prototype.setDefaultEncoding (writable.js:537): the name is
1740
+ // lower-cased first because node::ParseEncoding requires it, an unknown one
1741
+ // throws ERR_UNKNOWN_ENCODING synchronously, and the call returns the stream.
1742
+ // It is the WRITABLE half's default -- what an encoding-less write(string)
1743
+ // encodes with; the readable side keeps its own 'utf8'.
1744
+ setDefaultEncoding(encoding) {
1745
+ if (typeof encoding === 'string') {
1746
+ encoding = encoding.toLowerCase();
1747
+ }
1748
+ if (!Buffer.isEncoding(encoding)) {
1749
+ const err = new TypeError(`Unknown encoding: ${encoding}`);
1750
+ err.code = 'ERR_UNKNOWN_ENCODING';
1751
+ throw err;
1752
+ }
1753
+ this._defaultEnc = encoding;
1754
+ return this;
1755
+ }
1756
+
1757
+ // The EOF flush of the readable decoder -- node's onEofChunk head
1758
+ // (readable.js:849): the tail a split multi-byte sequence left in the decoder
1759
+ // becomes one last queue entry before the end machinery runs, carrying the
1760
+ // octets held there as its credit.
1761
+ _flushDecoder() {
1762
+ if (this._decoder === undefined) {
1763
+ return;
1764
+ }
1765
+ const tail = this._decoder.end();
1766
+ if (tail.length !== 0) {
1767
+ if (this._pending === null) {
1768
+ this._pending = [];
1769
+ }
1770
+ const bytes = this._decHeld === undefined ? 0 : this._decHeld;
1771
+ this._decHeld = undefined;
1772
+ this._pending.push({ data: tail, bytes });
1773
+ }
1774
+ }
1775
+
1776
+ // node's Readable.prototype.pipe (internal/streams/readable.js:978), not the
1777
+ // legacy Stream.prototype.pipe the bare base would supply: the tracked
1778
+ // destination list, the unpipe() surface, and the teardown that makes a
1779
+ // destroyed or finished source end and unpipe its destinations -- measured
1780
+ // on a live node the sink of a stream destroyed mid-pipe reports
1781
+ // pipe,finish,unpipe,close where the legacy base stops at pipe,close
1782
+ // (test/pipe-parity.test.js). The await-drain bookkeeping is node's
1783
+ // single-dest fast value promoted to a Set for the second destination.
1784
+ pipe(dest, options) {
1785
+ const src = this;
1786
+ if (src._pipes === null) {
1787
+ src._pipes = [];
1788
+ }
1789
+ src._pipes.push(dest);
1790
+
1791
+ const doEnd = (!options || options.end !== false) &&
1792
+ dest !== process.stdout && dest !== process.stderr;
1793
+ const endFn = doEnd ? onend : unpipe;
1794
+ if (src._eofEmitted === true) {
1795
+ process.nextTick(endFn);
1796
+ } else {
1797
+ src.once('end', endFn);
1798
+ }
1799
+
1800
+ dest.on('unpipe', onunpipe);
1801
+ function onunpipe(readable, unpipeInfo) {
1802
+ if (readable === src) {
1803
+ if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
1804
+ unpipeInfo.hasUnpiped = true;
1805
+ cleanup();
1806
+ }
1807
+ }
1808
+ }
1809
+
1810
+ function onend() {
1811
+ dest.end();
1812
+ }
1813
+
1814
+ let ondrain;
1815
+ let cleanedUp = false;
1816
+ function cleanup() {
1817
+ dest.removeListener('close', onclose);
1818
+ dest.removeListener('finish', onfinish);
1819
+ if (ondrain) {
1820
+ dest.removeListener('drain', ondrain);
1821
+ }
1822
+ dest.removeListener('error', onerror);
1823
+ dest.removeListener('unpipe', onunpipe);
1824
+ src.removeListener('end', onend);
1825
+ src.removeListener('end', unpipe);
1826
+ src.removeListener('data', ondata);
1827
+ cleanedUp = true;
1828
+ // a dest that errored or closed while the source waited on its drain
1829
+ // must not leave the flow parked for a writer that is gone
1830
+ if (ondrain && src._awaitDrain !== null) {
1831
+ ondrain();
1832
+ }
1833
+ }
1834
+
1835
+ function pause() {
1836
+ if (!cleanedUp) {
1837
+ if (src._pipes.length === 1 && src._pipes[0] === dest) {
1838
+ src._awaitDrain = dest;
1839
+ } else if (src._pipes.includes(dest)) {
1840
+ if (!(src._awaitDrain instanceof Set)) {
1841
+ src._awaitDrain = new Set(src._awaitDrain === null ? [] : [src._awaitDrain]);
1842
+ }
1843
+ src._awaitDrain.add(dest);
1844
+ }
1845
+ src.pause();
1846
+ }
1847
+ if (!ondrain) {
1848
+ ondrain = pipeOnDrain;
1849
+ dest.on('drain', ondrain);
1850
+ }
1851
+ }
1852
+
1853
+ function pipeOnDrain() {
1854
+ const a = src._awaitDrain;
1855
+ if (a === dest) {
1856
+ src._awaitDrain = null;
1857
+ } else if (a instanceof Set) {
1858
+ a.delete(dest);
1859
+ }
1860
+ const still = src._awaitDrain;
1861
+ if ((still === null || still.size === 0) && src.listenerCount('data') > 0) {
1862
+ src.resume();
1863
+ }
1864
+ }
1865
+
1866
+ src.on('data', ondata);
1867
+ function ondata(chunk) {
1868
+ try {
1869
+ if (dest.write(chunk) === false) {
1870
+ pause();
1871
+ }
1872
+ } catch (error) {
1873
+ dest.destroy(error);
1874
+ }
1875
+ }
1876
+
1877
+ // If the dest has an error, then stop piping into it. However, don't
1878
+ // suppress the throwing behavior for this (node's comment, verbatim rule).
1879
+ function onerror(er) {
1880
+ unpipe();
1881
+ dest.removeListener('error', onerror);
1882
+ if (dest.listenerCount('error') === 0) {
1883
+ const s = dest._writableState || dest._readableState;
1884
+ if (s && !s.errorEmitted) {
1885
+ dest.destroy(er);
1886
+ } else {
1887
+ dest.emit('error', er);
1888
+ }
1889
+ }
1890
+ }
1891
+ dest.prependListener('error', onerror);
1892
+
1893
+ // Both close and finish should trigger unpipe, but only once.
1894
+ function onclose() {
1895
+ dest.removeListener('finish', onfinish);
1896
+ unpipe();
1897
+ }
1898
+ dest.once('close', onclose);
1899
+ function onfinish() {
1900
+ dest.removeListener('close', onclose);
1901
+ unpipe();
1902
+ }
1903
+ dest.once('finish', onfinish);
1904
+
1905
+ function unpipe() {
1906
+ src.unpipe(dest);
1907
+ }
1908
+
1909
+ dest.emit('pipe', src);
1910
+
1911
+ if (dest.writableNeedDrain === true) {
1912
+ pause();
1913
+ } else if (src._flowing !== true) {
1914
+ src.resume();
1915
+ }
1916
+ return dest;
1917
+ }
1918
+
1919
+ // node's Readable.prototype.unpipe (readable.js:1180): no argument removes
1920
+ // every destination and stops the flow; one argument removes that
1921
+ // destination if it is piped to, and the call is its own 'unpipe' event
1922
+ // onto the dest with the hasUnpiped record the pipe closure cleans up on.
1923
+ unpipe(dest) {
1924
+ const pipes = this._pipes;
1925
+ if (pipes === null || pipes.length === 0) {
1926
+ return this;
1927
+ }
1928
+ if (!dest) {
1929
+ const dests = pipes;
1930
+ this._pipes = [];
1931
+ this.pause();
1932
+ for (let i = 0; i < dests.length; i++) {
1933
+ dests[i].emit('unpipe', this, { hasUnpiped: false });
1934
+ }
1935
+ return this;
1936
+ }
1937
+ const index = pipes.indexOf(dest);
1938
+ if (index === -1) {
1939
+ return this;
1940
+ }
1941
+ pipes.splice(index, 1);
1942
+ if (pipes.length === 0) {
1943
+ this.pause();
1944
+ }
1945
+ dest.emit('unpipe', this, { hasUnpiped: false });
1946
+ return this;
1947
+ }
1948
+
1949
+ // --- the async-iteration surface -------------------------------------------
1950
+ // node's readable-iteration protocol (internal/streams/readable.js:1552-1805)
1951
+ // and the fourteen helpers the public `stream` module bolts onto the same
1952
+ // prototype (stream.js:72-103, wrapping internal/streams/operators): the
1953
+ // transform family returns `Readable.from(generator)` -- measured on a live
1954
+ // node server stream: `map(fn)` yields an objectMode Readable -- and the
1955
+ // promise family returns the operation's promise. The iterator itself is a
1956
+ // pull machine over read(); break over for-await destroys through the
1957
+ // iterator's return() (AbortError into _destroy, RST CANCEL(8), events
1958
+ // aborted, error:ABORT_ERR, close), while a natural end leaves the stream
1959
+ // alive -- node reaches finalize() in both cases, but Http2Stream sets
1960
+ // autoDestroy false (core.js:2132), so only the still-active return()
1961
+ // branch satisfies finalize's second clause (measured: destroyed false,
1962
+ // readableEnded true after a clean loop; destroyed true, rstCode 8 after
1963
+ // break, both read inside the same handler turn).
1964
+ [Symbol.asyncIterator]() {
1965
+ return createStreamIterator(this, undefined);
1966
+ }
1967
+
1968
+ iterator(options) {
1969
+ if (options !== undefined) {
1970
+ validateObjectArg(options, 'options');
1971
+ }
1972
+ return createStreamIterator(this, options);
1973
+ }
1974
+
1975
+ map(fn, options) {
1976
+ return Readable.from(opMap(this, fn, options));
1977
+ }
1978
+
1979
+ filter(fn, options) {
1980
+ return Readable.from(opFilter(this, fn, options));
1981
+ }
1982
+
1983
+ flatMap(fn, options) {
1984
+ return Readable.from(opFlatMap(this, fn, options));
1985
+ }
1986
+
1987
+ drop(number, options) {
1988
+ return Readable.from(opDrop(this, number, options));
1989
+ }
1990
+
1991
+ take(number, options) {
1992
+ return Readable.from(opTake(this, number, options));
1993
+ }
1994
+
1995
+ reduce(reducer, initialValue, options) {
1996
+ // node's reduce tests `arguments.length > 1` inside the operator to tell
1997
+ // "no initial value" from "initial value undefined"; the arity has to be
1998
+ // read at the call, which is here.
1999
+ return opReduce(this, arguments.length > 1, reducer, initialValue, options);
2000
+ }
2001
+
2002
+ forEach(fn, options) {
2003
+ return opForEach(this, fn, options);
2004
+ }
2005
+
2006
+ toArray(options) {
2007
+ return opToArray(this, options);
2008
+ }
2009
+
2010
+ some(fn, options) {
2011
+ return opSome(this, fn, options);
2012
+ }
2013
+
2014
+ every(fn, options) {
2015
+ return opEvery(this, fn, options);
2016
+ }
2017
+
2018
+ find(fn, options) {
2019
+ return opFind(this, fn, options);
2020
+ }
2021
+
2022
+ // node's Readable.prototype.compose (readable.js:1810 plus
2023
+ // internal/streams/compose.js, the Node-stream branch): the composed Duplex
2024
+ // writes into this and reads out of the chain behind it. h2lean drives the
2025
+ // two-stream chain with its own pipe() -- the port of Readable.prototype.pipe
2026
+ // above -- where node uses internal/streams/pipeline; for the prototype
2027
+ // method's single argument those are the same chain (src 'end' -> dest.end(),
2028
+ // src error -> dest teardown), and the rest is node's wiring verbatim:
2029
+ // d._write into head with the drain callback, d._final = head.end(),
2030
+ // tail 'data'/'end' into d.push, teardown destroying the tail. Web streams
2031
+ // (TransformStream and friends) are refused here where node composes them --
2032
+ // KNOWN DIVERGENCE, stated in the header of this file's difference list.
2033
+ compose(stream, options) {
2034
+ if (options != null) {
2035
+ validateObjectArg(options, 'options');
2036
+ }
2037
+ validateSignalArg(options);
2038
+ const tail = typeof stream === 'function' ? Duplex.from(stream) : stream;
2039
+ if (tail === null || typeof tail !== 'object' ||
2040
+ typeof tail.pipe !== 'function' || typeof tail.write !== 'function') {
2041
+ // node's internal compose SKIPS non-streams in its own loop (the
2042
+ // "TODO: add checks for non streams" branch) and the refusal actually
2043
+ // comes from pipeline's `body` validation -- measured code:
2044
+ // ERR_INVALID_ARG_TYPE, not ERR_INVALID_ARG_VALUE.
2045
+ throw errorOf('ERR_INVALID_ARG_TYPE',
2046
+ 'The "body" argument must be of type function or an instance of Stream. ' +
2047
+ `Received type ${typeof stream} (${inspect(stream)}).`);
2048
+ }
2049
+ let ondrain = null;
2050
+ let onfinish = null;
2051
+ let onclose = undefined;
2052
+ const src = this;
2053
+ const d = new Duplex({
2054
+ writableObjectMode: !!src.writableObjectMode,
2055
+ readableObjectMode: !!tail.readableObjectMode,
2056
+ writable: true,
2057
+ readable: true
2058
+ });
2059
+
2060
+ function onfinished(err) {
2061
+ const cb = onclose;
2062
+ onclose = null;
2063
+ if (cb) {
2064
+ cb(err);
2065
+ } else if (err) {
2066
+ d.destroy(err);
2067
+ }
2068
+ }
2069
+
2070
+ // the writable half, node's d._write/d._final over head = this.
2071
+ d._write = function (chunk, encoding, callback) {
2072
+ if (src.write(chunk, encoding)) {
2073
+ callback();
2074
+ } else {
2075
+ ondrain = callback;
2076
+ }
2077
+ };
2078
+ d._final = function (callback) {
2079
+ src.end();
2080
+ onfinish = callback;
2081
+ };
2082
+ src.on('drain', () => {
2083
+ if (ondrain) {
2084
+ const cb = ondrain;
2085
+ ondrain = null;
2086
+ cb();
2087
+ }
2088
+ });
2089
+
2090
+ // node's pipeline([head, tail], onfinished): the chain is this pipe, and
2091
+ // any chain error reaches onfinished the way the pipeline callback takes
2092
+ // it (the pipe's own dest-side teardown is already node's behaviour).
2093
+ src.pipe(tail);
2094
+ src.on('error', onfinished);
2095
+ tail.on('error', onfinished);
2096
+
2097
+ // node's eos(toRead, cb) that releases d._final's callback.
2098
+ finished(tail, () => {
2099
+ if (onfinish) {
2100
+ const cb = onfinish;
2101
+ onfinish = null;
2102
+ cb();
2103
+ }
2104
+ });
2105
+
2106
+ // the readable half, node's tail 'data'/'end' push.
2107
+ d._read = function () {
2108
+ tail.resume();
2109
+ };
2110
+ tail.on('data', (chunk) => {
2111
+ if (!d.push(chunk)) {
2112
+ tail.pause();
2113
+ }
2114
+ });
2115
+ tail.on('end', () => {
2116
+ d.push(null);
2117
+ });
2118
+
2119
+ d._destroy = function (err, callback) {
2120
+ if (!err && onclose !== null) {
2121
+ err = abortError();
2122
+ }
2123
+ ondrain = null;
2124
+ onfinish = null;
2125
+ destroyStream(tail, err);
2126
+ if (onclose === null) {
2127
+ callback(err);
2128
+ } else {
2129
+ onclose = callback;
2130
+ }
2131
+ };
2132
+
2133
+ if (options && options.signal) {
2134
+ addAbortSignal(options.signal, d);
2135
+ }
2136
+ return d;
2137
+ }
2138
+
2139
+ // node's legacy Readable.prototype.wrap (readable.js:1503) -- the "ugly
2140
+ // unfortunate mess of history" that turns any event source into readable
2141
+ // data on this stream. It is honest machinery here because push() is node's
2142
+ // (task 39) and the pull-side resume hook fires where node's maybeReadMore
2143
+ // would call _read.
2144
+ wrap(stream) {
2145
+ let paused = false;
2146
+ stream.on('data', (chunk) => {
2147
+ if (!this.push(chunk) && stream.pause) {
2148
+ paused = true;
2149
+ stream.pause();
2150
+ }
2151
+ });
2152
+ stream.on('end', () => {
2153
+ this.push(null);
2154
+ });
2155
+ stream.on('error', (err) => {
2156
+ if (!this.destroyed) {
2157
+ this.destroy(err);
2158
+ }
2159
+ });
2160
+ stream.on('close', () => {
2161
+ if (!this.destroyed) {
2162
+ this.destroy();
2163
+ }
2164
+ });
2165
+ stream.on('destroy', () => {
2166
+ if (!this.destroyed) {
2167
+ this.destroy();
2168
+ }
2169
+ });
2170
+ this._read = () => {
2171
+ if (paused && stream.resume) {
2172
+ paused = false;
2173
+ stream.resume();
2174
+ }
2175
+ };
2176
+ const streamKeys = Object.keys(stream);
2177
+ for (let j = 0; j < streamKeys.length; j++) {
2178
+ const i = streamKeys[j];
2179
+ if (this[i] === undefined && typeof stream[i] === 'function') {
2180
+ this[i] = stream[i].bind(stream);
2181
+ }
2182
+ }
2183
+ return this;
2184
+ }
2185
+
2186
+ // The pull model's arrival event: node's readable-mode consumer is woken by
2187
+ // 'readable', never by the bytes themselves. Coalescing is node's
2188
+ // needReadable/emitReadable pair — one event per un-observed stretch, so two
2189
+ // DATA frames in one read batch produce one event (measured: readablePasses 2
2190
+ // for three reads over one arrival).
2191
+ _scheduleReadable() {
2192
+ if (this._readableScheduled === true || this.listenerCount('readable') === 0) {
2193
+ return;
2194
+ }
2195
+ this._readableScheduled = true;
2196
+ process.nextTick(() => {
2197
+ this._readableScheduled = false;
2198
+ if (this._destroyed || this._flowing === true ||
2199
+ this.listenerCount('readable') === 0) {
2200
+ return;
2201
+ }
2202
+ // nothing to report if the queue drained between the schedule and the tick
2203
+ // (node's read() clears needReadable the same way)
2204
+ if (this._pending === null && !this._endPending && this._eofSeen !== true) {
2205
+ return;
2206
+ }
2207
+ this.emit('readable');
2208
+ });
2209
+ }
2210
+
2211
+ // The end-of-stream schedule — node's endReadable: the 'end' never overtakes
2212
+ // buffered octets, and one schedule is enough (the kEndScheduled bit).
2213
+ _scheduleEOF() {
2214
+ if (this._eofEmitted === true || this._eofScheduled === true) {
2215
+ return;
2216
+ }
2217
+ this._eofScheduled = true;
2218
+ process.nextTick(() => {
2219
+ this._eofScheduled = false;
2220
+ if (this._destroyed || this._eofEmitted === true) {
2221
+ return;
2222
+ }
2223
+ if (this._pending !== null && this._pending.length > 0) {
2224
+ // a push landed between the trigger and the tick: the EOF is owed to the
2225
+ // drain again (node's endReadableNT re-checks state.length === 0 and
2226
+ // simply skips the emission here)
2227
+ this._endPending = true;
2228
+ return;
2229
+ }
2230
+ this._endPending = false;
2231
+ emitEndNT(this);
2232
+ });
2233
+ }
2234
+
1160
2235
  // node maps a per-stream timeout onto the connection's idle timeout.
1161
2236
  setTimeout(ms, cb) {
1162
2237
  this.session.setTimeout(ms, cb);
@@ -1186,6 +2261,11 @@ class Http2Stream extends Stream {
1186
2261
  }
1187
2262
  this._state.remoteClose = 1;
1188
2263
  this.endAfterHeaders = true;
2264
+ // node's onEofChunk runs when the END_STREAM is processed, and with a
2265
+ // decoder set it flushes the split sequence held there into the queue
2266
+ // BEFORE any of the end machinery below -- the tail octets are owed to the
2267
+ // reader that arrives later, exactly like the bytes before them.
2268
+ this._flushDecoder();
1189
2269
  // the readable side is done: 'end' after the last 'data', like a Readable.
1190
2270
  // No auto-destroy: the application still has to answer. node keeps the
1191
2271
  // writable side of an unanswered request open as well.
@@ -1213,9 +2293,19 @@ class Http2Stream extends Stream {
1213
2293
  // Nothing has read the buffered bytes yet, so 'end' must not overtake them:
1214
2294
  // a reader that attaches later is owed the whole sequence, EOF included.
1215
2295
  this._endPending = true;
2296
+ // node's onEofChunk, measured stack (emitReadable_ <- onEofChunk <- the
2297
+ // stream_base read callback at END_STREAM): the EOF push emits 'readable'
2298
+ // SYNCHRONOUSLY inside the frame batch, not on a tick — the merge arm sees
2299
+ // the second 'readable' fire in the ES callback itself while the arrival
2300
+ // tick still runs its own. With no pull listener the sync emit is the
2301
+ // no-op node's listener-less emit performs, and the parked EOF waits for
2302
+ // the reader exactly as before.
2303
+ if (this.listenerCount('readable') > 0) {
2304
+ this.emit('readable');
2305
+ }
1216
2306
  return;
1217
2307
  }
1218
- process.nextTick(emitNT, this, 'end');
2308
+ process.nextTick(emitEndNT, this);
1219
2309
  }
1220
2310
 
1221
2311
  // The writable-side 'finish' -- node's Writable fires it once every write has been
@@ -1305,7 +2395,8 @@ class Http2Stream extends Stream {
1305
2395
  // touched the request, and node stops there too.
1306
2396
  _maybeAutoClose() {
1307
2397
  if (this._destroyed || !this.headersSent || this._waitForTrailers ||
1308
- this._consumeState !== 0) {
2398
+ this._consumeState !== 0 || this._flowing === false ||
2399
+ this._dataRead === true) {
1309
2400
  return;
1310
2401
  }
1311
2402
  // node's own deferral: the RST goes out a turn after the response, and the
@@ -1326,7 +2417,7 @@ class Http2Stream extends Stream {
1326
2417
  // in _endPending for a reader that never appeared, and the local close below was the last
1327
2418
  // event the stream ever produced. Measured against node on exactly that shape: it emits
1328
2419
  // stream.end then stream.close (test/event-order.test.js, scenario eof).
1329
- if (this._endPending) {
2420
+ if (this._endPending || this._eofSeen === true) {
1330
2421
  this._endPending = false;
1331
2422
  process.nextTick(emitEndCloseNT, this);
1332
2423
  return;
@@ -1354,6 +2445,17 @@ class Http2Stream extends Stream {
1354
2445
  return;
1355
2446
  }
1356
2447
  this._destroyed = true;
2448
+ // node's destroy does not touch state.flowing — the readableFlowing getter keeps
2449
+ // reporting the last resume()/pause()/listener verdict even after the destroy
2450
+ // (measured: snapError inside the 'error' handler reads flowing true post-resume),
2451
+ // and every consumer here gates on _destroyed first.
2452
+ // node's destroy() runs checkError BEFORE the destroyed bit and before the
2453
+ // nextTick that emits: state.errored is already set in the same turn the
2454
+ // destroy happens (destroy.js checkError), so a getter read right after
2455
+ // destroy(err) sees it — the deferred emitErrorCloseNT only carries the event.
2456
+ if (err) {
2457
+ this._streamErrored = err;
2458
+ }
1357
2459
  this.rstCode = code;
1358
2460
  // node's rule for 'aborted' is about the WRITABLE side: "if the writable side of
1359
2461
  // the Http2Stream is still open, emit the 'aborted' event" -- closeStream's
@@ -1386,6 +2488,24 @@ class Http2Stream extends Stream {
1386
2488
  this.session = undefined;
1387
2489
  if (err) {
1388
2490
  process.nextTick(emitErrorCloseNT, this, err);
2491
+ } else if (this._isConsuming() &&
2492
+ (this._endPending || code === NO_ERROR || code === frames.CANCEL)) {
2493
+ // node's _destroy (internal/http2/core.js:2527) calls `this.push(null)`
2494
+ // unconditionally, but the EOF it pushes only reaches the readable when the
2495
+ // destroy was not an error: core.js:2541 turns every other code into
2496
+ // ERR_HTTP2_STREAM_ERROR first, and an errored destroy reports error+close
2497
+ // with no 'end' at all (measured on the over-long content-length refusal:
2498
+ // aborted, error, close). So the owed EOF goes out for exactly the codes
2499
+ // streamErrorOf does not name -- a plain destroy() and an abort (CANCEL) --
2500
+ // plus the parked-END_STREAM case this branch has always replayed. Measured
2501
+ // shapes: respond + close(8), request ended on its HEADERS -- aborted, end,
2502
+ // close; and a stream destroyed mid-pipe with no END_STREAM ever sent --
2503
+ // again aborted, end, close, which is what ends and unpipes the dest
2504
+ // (test/pipe-parity.test.js). Without it the deferred resume of an attached
2505
+ // reader is cancelled by the destroy bit and the owed 'end' never goes out
2506
+ // (test/event-order.test.js, scenario reset).
2507
+ this._endPending = false;
2508
+ process.nextTick(emitEndCloseNT, this);
1389
2509
  } else {
1390
2510
  process.nextTick(emitNT, this, 'close');
1391
2511
  }
@@ -1417,36 +2537,78 @@ class Http2Stream extends Stream {
1417
2537
  }
1418
2538
 
1419
2539
  // --- inbound flow control ----------------------------------------------------
1420
- // Attaching a reader is how the application says "send me the body": replay
1421
- // whatever arrived before it did. attach after super.on(), or the replay would
1422
- // emit into an empty listener list. once()/addListener are covered by the
1423
- // listenerCount() check at delivery time.
2540
+ // Attaching a reader is how the application says "send me the body": whatever
2541
+ // arrived before it did is replayed -- on the next tick, like node's
2542
+ // kResumeScheduled resume_, not inside the on() call (measured: a read() in the
2543
+ // same turn as the attach still sees the buffer). once()/addListener are
2544
+ // covered by the listenerCount() check at delivery time.
1424
2545
  on(name, fn) {
2546
+ const firstReader = (name === 'data' || name === 'readable') &&
2547
+ this.listenerCount(name) === 0;
1425
2548
  const r = super.on(name, fn);
1426
- if (name === 'data' || name === 'readable') {
1427
- this._startConsuming();
2549
+ if (name === 'data') {
2550
+ if (firstReader) {
2551
+ this._readerFlow(name);
2552
+ }
2553
+ this._scheduleResume();
2554
+ } else if (name === 'readable') {
2555
+ if (firstReader) {
2556
+ this._readerFlow(name);
2557
+ }
2558
+ this._scheduleReadable();
1428
2559
  }
1429
2560
  return r;
1430
2561
  }
1431
2562
 
1432
2563
  once(name, fn) {
2564
+ const firstReader = (name === 'data' || name === 'readable') &&
2565
+ this.listenerCount(name) === 0;
1433
2566
  const r = super.once(name, fn);
1434
- if (name === 'data' || name === 'readable') {
1435
- this._startConsuming();
2567
+ if (name === 'data') {
2568
+ if (firstReader) {
2569
+ this._readerFlow(name);
2570
+ }
2571
+ this._scheduleResume();
2572
+ } else if (name === 'readable') {
2573
+ if (firstReader) {
2574
+ this._readerFlow(name);
2575
+ }
2576
+ this._scheduleReadable();
1436
2577
  }
1437
2578
  return r;
1438
2579
  }
1439
2580
 
2581
+ // node's Readable.prototype.on: attaching 'data' resumes, unless the stream was
2582
+ // explicitly paused; attaching 'readable' takes the stream out of flowing mode
2583
+ // even after resume() (measured: resume() then on('readable') reads false).
2584
+ // Both rules show up on the readableFlowing getter only — the replay that
2585
+ // actually moves the bytes stayed where it was.
2586
+ _readerFlow(name) {
2587
+ if (name === 'data') {
2588
+ if (this._flowing !== false) {
2589
+ this._flowing = true;
2590
+ }
2591
+ } else if (this._eofEmitted !== true) {
2592
+ this._flowing = false;
2593
+ }
2594
+ }
2595
+
1440
2596
  // Credit goes back when the application takes the bytes, so a body nobody
1441
2597
  // reads closes the sender's window instead of growing our heap. The buffer of
1442
2598
  // unread chunks cannot exceed the window we advertised, because the peer is
1443
2599
  // not allowed to send more than that without a credit we never gave.
2600
+ // A 'readable' listener is NOT consuming: the pull model buffers and waits
2601
+ // for read(), which is where that credit comes back (node's readable mode
2602
+ // releases nothing until the app pulls). A 'data' listener is not consuming
2603
+ // either while the stream sits in pull or paused mode (_flowing === false) --
2604
+ // node's kHasFlowing rule measured in the merge arm: the chunks stay in the
2605
+ // buffer for read() and only read()'s own data emission delivers them.
1444
2606
  _isConsuming() {
1445
2607
  if (this._consumeState === 2) {
1446
2608
  return false;
1447
2609
  } // the reader asked us to stop
1448
- return this._consumeState === 1 || this.listenerCount('data') > 0 ||
1449
- this.listenerCount('readable') > 0;
2610
+ return this._consumeState === 1 ||
2611
+ (this._flowing !== false && this.listenerCount('data') > 0);
1450
2612
  }
1451
2613
 
1452
2614
  // Called when a reader shows up: replay what was buffered, in order, and let
@@ -1457,14 +2619,25 @@ class Http2Stream extends Stream {
1457
2619
  if (pending !== null) {
1458
2620
  this._pending = null;
1459
2621
  for (let i = 0; i < pending.length; i++) {
1460
- const chunk = pending[i];
1461
- this._release(chunk.length);
1462
- this.emit('data', chunk);
2622
+ const c = pending[i];
2623
+ this._dataRead = true;
2624
+ if (c.length === undefined) {
2625
+ // a pushed or decoded chunk: delivered, and it owes no credit for
2626
+ // itself -- but a string entry that stands for wire octets carries
2627
+ // their count and pays it here
2628
+ if (c.bytes !== undefined) {
2629
+ this._release(c.bytes);
2630
+ }
2631
+ this.emit('data', c.data);
2632
+ } else {
2633
+ this._release(c.length);
2634
+ this.emit('data', c);
2635
+ }
1463
2636
  }
1464
2637
  }
1465
- if (this._endPending && !this._destroyed) {
2638
+ if ((this._endPending || this._eofSeen === true) && !this._destroyed) {
1466
2639
  this._endPending = false;
1467
- process.nextTick(emitNT, this, 'end');
2640
+ this._scheduleEOF();
1468
2641
  }
1469
2642
  }
1470
2643
 
@@ -1486,17 +2659,53 @@ class Http2Stream extends Stream {
1486
2659
  return;
1487
2660
  } // an empty DATA frame carries no payload
1488
2661
  this._recvUsed += n;
1489
- if (this._isConsuming()) {
2662
+ if (this._decoder !== undefined) {
2663
+ // arrival decodes at the door, node's push path with a decoder set: the
2664
+ // queue holds characters from here on. A chunk the decoder swallowed
2665
+ // whole (split multi-byte sequence) produces no entry and no event --
2666
+ // node's `chunk.length === 0` return -- and its octets are held against
2667
+ // the credit of the entry that finally comes out.
2668
+ let held = 0;
2669
+ if (this._decHeld !== undefined) {
2670
+ held = this._decHeld;
2671
+ this._decHeld = undefined;
2672
+ }
2673
+ const str = this._decoder.write(buf);
2674
+ if (str.length === 0) {
2675
+ this._decHeld = n + held;
2676
+ return;
2677
+ }
2678
+ if (this._isConsuming() && this._pending === null) {
2679
+ this._dataRead = true;
2680
+ this._release(n + held);
2681
+ this.emit('data', str);
2682
+ return;
2683
+ }
2684
+ if (this._pending === null) {
2685
+ this._pending = [];
2686
+ }
2687
+ this._pending.push({ data: str, bytes: n + held });
2688
+ this._scheduleReadable();
2689
+ return;
2690
+ }
2691
+ if (this._isConsuming() && this._pending === null) {
2692
+ this._dataRead = true;
1490
2693
  this._release(n);
1491
2694
  this.emit('data', buf);
1492
2695
  return;
1493
2696
  }
1494
2697
  // the chunk is either a view of a socket read or a buffer built for this frame
1495
- // alone; both outlive the tick, so it can simply be queued
2698
+ // alone; both outlive the tick, so it can simply be queued. A consuming reader
2699
+ // with a queue still standing lands here too: resume()'s delivery is scheduled,
2700
+ // not synchronous (node's resume_ tick), and arriving bytes must not overtake
2701
+ // the buffered ones.
1496
2702
  if (this._pending === null) {
1497
2703
  this._pending = [];
1498
2704
  }
1499
2705
  this._pending.push(buf);
2706
+ // readable-mode arrival: the pull consumer learns about it through
2707
+ // 'readable', not through the bytes (node's needReadable/emitReadable).
2708
+ this._scheduleReadable();
1500
2709
  }
1501
2710
  }
1502
2711
 
@@ -1514,6 +2723,626 @@ function errorOf(code, msg) {
1514
2723
  return err;
1515
2724
  }
1516
2725
 
2726
+ // --- the async-iteration machinery ----------------------------------------------
2727
+ // Everything below reproduces node's internal/streams/readable.js:1552-1805
2728
+ // (streamToAsyncIterator/createAsyncIterator) and internal/streams/operators,
2729
+ // read from the binary in the same session as the measurements cited at the
2730
+ // methods. Two simplifications are honest, not inventions: (a) the iterator
2731
+ // never meets a thenable chunk -- push() validates its argument, so the queue
2732
+ // holds only Buffer/string/null and node's `chunk?.then` unwrapping and the
2733
+ // two-error AggregateError race it guards cannot occur (measured: an errored
2734
+ // iteration rejects with the bare error); (b) the FixedQueue node parks
2735
+ // queued requests in is an array here -- queue depth is a behaviour of the
2736
+ // consumer, not of the protocol.
2737
+
2738
+ const kEmpty = Symbol('kEmpty');
2739
+ const kEof = Symbol('kEof');
2740
+ // %AsyncIteratorPrototype% in V8: the function's .prototype is an INSTANCE of
2741
+ // the (shared) async-generator prototype, so the intrinsic with
2742
+ // [Symbol.asyncIterator]/[Symbol.asyncDispose] and no own methods sits TWO
2743
+ // levels up. Verified identity with the proto of a live node v26 iterator
2744
+ // object; the single getPrototypeOf lands on the generator prototype instead.
2745
+ // Node's own iterator is NOT this shape on every major: 22 and 24 hand back a
2746
+ // real async-generator instance, whose proto has no own keys at all. The
2747
+ // intrinsic is the only anchor stable across majors, and the behaviour that
2748
+ // depends on it ([Symbol.asyncIterator] resolving through the chain,
2749
+ // self-identical) is verified per major; exact proto identity is unportable.
2750
+ const ASYNC_ITERATOR_PROTO =
2751
+ Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}.prototype));
2752
+
2753
+ function noop() {}
2754
+
2755
+ // node's internal AbortError as the stream machinery constructs it (measured
2756
+ // on a live node break: name 'AbortError', code 'ABORT_ERR'). core.js:2516
2757
+ // maps it onto RST CANCEL(8) inside _destroy.
2758
+ function abortError(cause) {
2759
+ const err = new Error('The operation was aborted',
2760
+ cause === undefined ? undefined : { cause });
2761
+ err.name = 'AbortError';
2762
+ err.code = 'ABORT_ERR';
2763
+ return err;
2764
+ }
2765
+
2766
+ function validateObjectArg(value, name) {
2767
+ if (value === null || typeof value !== 'object') {
2768
+ throw errorOf('ERR_INVALID_ARG_TYPE',
2769
+ `The "${name}" argument must be of type object. Received ${inspect(value)}`);
2770
+ }
2771
+ }
2772
+
2773
+ function validateFunctionArg(value, name) {
2774
+ if (typeof value !== 'function') {
2775
+ throw errorOf('ERR_INVALID_ARG_TYPE',
2776
+ `The "${name}" argument must be of type function. Received ${inspect(value)}`);
2777
+ }
2778
+ }
2779
+
2780
+ // node's pair in every operator: validateObject(options) then
2781
+ // validateAbortSignal(options.signal).
2782
+ function validateSignalArg(options) {
2783
+ if (options != null && options.signal != null && !(options.signal instanceof AbortSignal)) {
2784
+ throw errorOf('ERR_INVALID_ARG_TYPE',
2785
+ 'The "options.signal" argument must be an instance of type AbortSignal.');
2786
+ }
2787
+ }
2788
+
2789
+ function validateOperatorOptions(options) {
2790
+ if (options != null) {
2791
+ validateObjectArg(options, 'options');
2792
+ }
2793
+ validateSignalArg(options);
2794
+ }
2795
+
2796
+ // node's toIntegerOrInfinity (operators:298): Number coercion per the
2797
+ // iterator-helpers proposal, then the range refusal.
2798
+ function toIntegerOrInfinity(number) {
2799
+ number = Number(number);
2800
+ if (Number.isNaN(number)) {
2801
+ return 0;
2802
+ }
2803
+ if (number < 0) {
2804
+ throw errorOf('ERR_OUT_OF_RANGE',
2805
+ `The value of "number" is out of range. It must be >= 0. Received ${number}`);
2806
+ }
2807
+ return number;
2808
+ }
2809
+
2810
+ // node's createAsyncIterator (readable.js:1576). The request protocol -- next
2811
+ // fast path, queue behind an inFlight request, return/throw draining through
2812
+ // the same pump -- is reproduced member by member; the wake is h2lean's
2813
+ // 'readable' event (node's emitReadable, same coalescing) and the end verdict
2814
+ // comes from the error/end/close trio standing in for
2815
+ // eos(stream, { writable: false }).
2816
+ function createStreamIterator(stream, options) {
2817
+ let callback = noop;
2818
+ let error; // undefined: active, null: ended cleanly, else: the Error
2819
+ let started = false;
2820
+ let completed = false;
2821
+ let inFlight = false; // an asynchronous request is outstanding
2822
+ let queue = null; // requests received while inFlight
2823
+ let draining = false;
2824
+ let detach = noop;
2825
+
2826
+ function fire() {
2827
+ const cb = callback;
2828
+ callback = noop;
2829
+ cb();
2830
+ }
2831
+
2832
+ function wait() {
2833
+ return new Promise((resolve) => {
2834
+ callback = resolve;
2835
+ });
2836
+ }
2837
+
2838
+ function start() {
2839
+ started = true;
2840
+ stream.on('readable', fire);
2841
+ let settled = false;
2842
+ const settle = (err) => {
2843
+ if (settled) {
2844
+ return;
2845
+ }
2846
+ settled = true;
2847
+ detach();
2848
+ error = err;
2849
+ fire();
2850
+ };
2851
+ const onEnd = () => {
2852
+ settle(null);
2853
+ };
2854
+ // a close with neither end nor error is node's eos verdict
2855
+ // ERR_STREAM_PREMATURE_CLOSE ('Premature close', read out of
2856
+ // internal/errors with --expose-internals).
2857
+ const onClose = () => {
2858
+ settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'));
2859
+ };
2860
+ stream.on('error', settle);
2861
+ stream.on('end', onEnd);
2862
+ stream.on('close', onClose);
2863
+ detach = () => {
2864
+ stream.removeListener('readable', fire);
2865
+ stream.removeListener('error', settle);
2866
+ stream.removeListener('end', onEnd);
2867
+ stream.removeListener('close', onClose);
2868
+ };
2869
+ // node's start() hooks eos, not raw 'end'/'close', and an eos on a
2870
+ // stream that has ALREADY settled calls back on the next tick: a second
2871
+ // iterator over an ended stream gets `{done:true}` (measured on live
2872
+ // node: every() after some() on the same stream answers true without
2873
+ // hanging), and over a destroyed one gets the premature-close error.
2874
+ // The one-shot trio below can never fire again, so this is where that
2875
+ // verdict is reproduced.
2876
+ if (stream.readableEnded === true) {
2877
+ process.nextTick(() => settle(null));
2878
+ } else if (stream.destroyed === true) {
2879
+ process.nextTick(() => settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close')));
2880
+ }
2881
+ }
2882
+
2883
+ function finalize() {
2884
+ completed = true;
2885
+ // node's finalize (readable.js:1609) reads autoDestroy off the state
2886
+ // object; Http2Stream fixes it false (core.js:2132), so the second
2887
+ // clause reduces to `error === undefined`: only a still-active
2888
+ // return()/break destroys -- node's destroyer(stream, null) on a
2889
+ // not-finished stream is destroy(new AbortError()), which core.js:2516
2890
+ // turns into RST CANCEL. h2lean's public destroy() derives
2891
+ // INTERNAL_ERROR from any Error object (its own documented rule, task
2892
+ // 17), so the iterator calls the engine with node's derived pair
2893
+ // directly. Measured: break -- destroyed true, rstCode 8, aborted,
2894
+ // error:ABORT_ERR, close; natural end -- destroyed stays false.
2895
+ if ((error || options?.destroyOnReturn !== false) && error === undefined) {
2896
+ if (!stream.destroyed) {
2897
+ stream._destroy(frames.CANCEL, undefined, true, abortError());
2898
+ }
2899
+ } else {
2900
+ stream.removeListener('readable', fire);
2901
+ detach();
2902
+ }
2903
+ }
2904
+
2905
+ function drain() {
2906
+ // node's guard: requests settled synchronously call back into drain(),
2907
+ // and one loop runs instead of one recursion per request.
2908
+ if (draining) {
2909
+ return;
2910
+ }
2911
+ draining = true;
2912
+ try {
2913
+ while (!inFlight && queue !== null && queue.length > 0) {
2914
+ const req = queue.shift();
2915
+ if (req.type === 'next') {
2916
+ processNext(req.resolve, req.reject);
2917
+ } else if (req.type === 'return') {
2918
+ processReturn(req.value, req.resolve);
2919
+ } else {
2920
+ processThrow(req.value, req.reject);
2921
+ }
2922
+ }
2923
+ } finally {
2924
+ draining = false;
2925
+ }
2926
+ }
2927
+
2928
+ function pump(resolve, reject) {
2929
+ const chunk = stream.destroyed ? null : stream.read();
2930
+ if (chunk !== null) {
2931
+ inFlight = false;
2932
+ resolve({ done: false, value: chunk });
2933
+ if (queue !== null) {
2934
+ drain();
2935
+ }
2936
+ } else if (error) {
2937
+ inFlight = false;
2938
+ finalize();
2939
+ reject(error);
2940
+ if (queue !== null) {
2941
+ drain();
2942
+ }
2943
+ } else if (error === null) {
2944
+ inFlight = false;
2945
+ finalize();
2946
+ resolve({ done: true, value: undefined });
2947
+ if (queue !== null) {
2948
+ drain();
2949
+ }
2950
+ } else {
2951
+ // nothing buffered yet: wait for the next 'readable' or end verdict
2952
+ // and retry, node's wakeup-promise tail.
2953
+ wait().then(() => pump(resolve, reject));
2954
+ }
2955
+ }
2956
+
2957
+ function processNext(resolve, reject) {
2958
+ if (completed) {
2959
+ resolve({ done: true, value: undefined });
2960
+ return;
2961
+ }
2962
+ if (!started) {
2963
+ start();
2964
+ }
2965
+ inFlight = true;
2966
+ pump(resolve, reject);
2967
+ }
2968
+
2969
+ function processReturn(value, resolve) {
2970
+ if (!completed) {
2971
+ if (started) {
2972
+ finalize();
2973
+ } else {
2974
+ // never started: complete without touching the stream.
2975
+ completed = true;
2976
+ }
2977
+ }
2978
+ resolve({ done: true, value });
2979
+ }
2980
+
2981
+ function processThrow(err, reject) {
2982
+ if (completed || !started) {
2983
+ completed = true;
2984
+ reject(err);
2985
+ return;
2986
+ }
2987
+ error = err;
2988
+ finalize();
2989
+ reject(err);
2990
+ }
2991
+
2992
+ const iter = {
2993
+ __proto__: ASYNC_ITERATOR_PROTO,
2994
+ next() {
2995
+ if (!inFlight && !completed) {
2996
+ if (!started) {
2997
+ start();
2998
+ }
2999
+ const chunk = stream.destroyed ? null : stream.read();
3000
+ if (chunk !== null) {
3001
+ return Promise.resolve({ done: false, value: chunk });
3002
+ }
3003
+ if (error) {
3004
+ finalize();
3005
+ return Promise.reject(error);
3006
+ }
3007
+ if (error === null) {
3008
+ finalize();
3009
+ return Promise.resolve({ done: true, value: undefined });
3010
+ }
3011
+ inFlight = true;
3012
+ return new Promise((resolve, reject) => {
3013
+ wait().then(() => pump(resolve, reject));
3014
+ });
3015
+ }
3016
+ return new Promise((resolve, reject) => {
3017
+ if (inFlight) {
3018
+ (queue ??= []).push({ __proto__: null, type: 'next', value: undefined, resolve, reject });
3019
+ } else {
3020
+ resolve({ done: true, value: undefined });
3021
+ }
3022
+ });
3023
+ },
3024
+ return(value) {
3025
+ return new Promise((resolve) => {
3026
+ if (inFlight) {
3027
+ (queue ??= []).push({ __proto__: null, type: 'return', value, resolve, reject: null });
3028
+ } else {
3029
+ processReturn(value, resolve);
3030
+ }
3031
+ });
3032
+ },
3033
+ throw(err) {
3034
+ return new Promise((resolve, reject) => {
3035
+ if (inFlight) {
3036
+ (queue ??= []).push({ __proto__: null, type: 'throw', value: err, resolve, reject });
3037
+ } else {
3038
+ processThrow(err, reject);
3039
+ }
3040
+ });
3041
+ }
3042
+ };
3043
+ // node's streamToAsyncIterator hangs the source on the iterator object
3044
+ // (readable.js:1563-1565); measured raw.stream === rd on a live node.
3045
+ iter.stream = stream;
3046
+ return iter;
3047
+ }
3048
+
3049
+ // node's operators (internal/streams/operators). Each is a plain function or
3050
+ // async function mirroring the original's argument shape, so the synchronous
3051
+ // validation the transform family performs (measured: map('nope') throws
3052
+ // ERR_INVALID_ARG_TYPE out of the call) and the rejection the promise family
3053
+ // produces land exactly where node puts them.
3054
+
3055
+ function opMap(stream, fn, options) {
3056
+ validateFunctionArg(fn, 'fn');
3057
+ validateOperatorOptions(options);
3058
+ let concurrency = 1;
3059
+ if (options?.concurrency != null) {
3060
+ concurrency = Math.floor(options.concurrency);
3061
+ }
3062
+ let highWaterMark = concurrency - 1;
3063
+ if (options?.highWaterMark != null) {
3064
+ highWaterMark = Math.floor(options.highWaterMark);
3065
+ }
3066
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
3067
+ throw errorOf('ERR_OUT_OF_RANGE',
3068
+ `The value of "options.concurrency" is out of range. It must be >= 1. Received ${concurrency}`);
3069
+ }
3070
+ if (!Number.isInteger(highWaterMark) || highWaterMark < 0) {
3071
+ throw errorOf('ERR_OUT_OF_RANGE',
3072
+ `The value of "options.highWaterMark" is out of range. It must be >= 0. Received ${highWaterMark}`);
3073
+ }
3074
+ highWaterMark += concurrency;
3075
+ // node builds its always-present signal with AbortSignal.any([...]) --
3076
+ // any([]) is a fresh never-aborted signal, which a never-aborted
3077
+ // controller's signal is byte-equivalent to for everything the operator
3078
+ // reads off it.
3079
+ const signal = options?.signal ?? new AbortController().signal;
3080
+
3081
+ return (async function* map() {
3082
+ const queue = [];
3083
+ const signalOpt = { signal };
3084
+ let next = null;
3085
+ let resume = null;
3086
+ let done = false;
3087
+ let cnt = 0;
3088
+
3089
+ function onCatch() {
3090
+ done = true;
3091
+ afterItemProcessed();
3092
+ }
3093
+
3094
+ function afterItemProcessed() {
3095
+ cnt -= 1;
3096
+ maybeResume();
3097
+ }
3098
+
3099
+ function maybeResume() {
3100
+ if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {
3101
+ const r = resume;
3102
+ resume = null;
3103
+ r();
3104
+ }
3105
+ }
3106
+
3107
+ async function pump() {
3108
+ try {
3109
+ for await (let val of stream) {
3110
+ if (done) {
3111
+ return;
3112
+ }
3113
+ if (signal.aborted) {
3114
+ throw abortError();
3115
+ }
3116
+ try {
3117
+ val = fn(val, signalOpt);
3118
+ if (val === kEmpty) {
3119
+ continue;
3120
+ }
3121
+ val = Promise.resolve(val);
3122
+ } catch (err) {
3123
+ val = Promise.reject(err);
3124
+ }
3125
+ cnt += 1;
3126
+ val.then(afterItemProcessed, onCatch);
3127
+ queue.push(val);
3128
+ if (next) {
3129
+ const n = next;
3130
+ next = null;
3131
+ n();
3132
+ }
3133
+ if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {
3134
+ await new Promise((resolve) => {
3135
+ resume = resolve;
3136
+ });
3137
+ }
3138
+ }
3139
+ queue.push(kEof);
3140
+ } catch (err) {
3141
+ const val = Promise.reject(err);
3142
+ val.then(afterItemProcessed, onCatch);
3143
+ queue.push(val);
3144
+ } finally {
3145
+ done = true;
3146
+ if (next) {
3147
+ const n = next;
3148
+ next = null;
3149
+ n();
3150
+ }
3151
+ }
3152
+ }
3153
+
3154
+ pump();
3155
+
3156
+ try {
3157
+ while (true) {
3158
+ while (queue.length > 0) {
3159
+ const val = await queue[0];
3160
+ if (val === kEof) {
3161
+ return;
3162
+ }
3163
+ if (signal.aborted) {
3164
+ throw abortError();
3165
+ }
3166
+ if (val !== kEmpty) {
3167
+ yield val;
3168
+ }
3169
+ queue.shift();
3170
+ maybeResume();
3171
+ }
3172
+ await new Promise((resolve) => {
3173
+ next = resolve;
3174
+ });
3175
+ }
3176
+ } finally {
3177
+ done = true;
3178
+ if (resume) {
3179
+ const r = resume;
3180
+ resume = null;
3181
+ r();
3182
+ }
3183
+ }
3184
+ })();
3185
+ }
3186
+
3187
+ function opFilter(stream, fn, options) {
3188
+ validateFunctionArg(fn, 'fn');
3189
+ async function filterFn(value, opt) {
3190
+ if (await fn(value, opt)) {
3191
+ return value;
3192
+ }
3193
+ return kEmpty;
3194
+ }
3195
+ return opMap(stream, filterFn, options);
3196
+ }
3197
+
3198
+ async function opForEach(stream, fn, options) {
3199
+ validateFunctionArg(fn, 'fn');
3200
+ async function forEachFn(value, opt) {
3201
+ await fn(value, opt);
3202
+ return kEmpty;
3203
+ }
3204
+ // node drains the mapped generator with an empty for-await body. The same
3205
+ // descent is spelled out here -- an fn error propagates out of the mapped
3206
+ // generator's own body, so its cleanup runs at the throw point and no
3207
+ // abrupt-close return() call from this loop would add anything.
3208
+ const it = opMap(stream, forEachFn, options)[Symbol.asyncIterator]();
3209
+ let res = await it.next();
3210
+ while (!res.done) {
3211
+ res = await it.next();
3212
+ }
3213
+ }
3214
+
3215
+ function opFlatMap(stream, fn, options) {
3216
+ const values = opMap(stream, fn, options);
3217
+ return (async function* flatMap() {
3218
+ for await (const val of values) {
3219
+ yield* val;
3220
+ }
3221
+ })();
3222
+ }
3223
+
3224
+ function opDrop(stream, number, options) {
3225
+ validateOperatorOptions(options);
3226
+ const limit = toIntegerOrInfinity(number);
3227
+ return (async function* drop() {
3228
+ if (options?.signal?.aborted) {
3229
+ throw abortError();
3230
+ }
3231
+ let numberLeft = limit;
3232
+ for await (const val of stream) {
3233
+ if (options?.signal?.aborted) {
3234
+ throw abortError();
3235
+ }
3236
+ if (numberLeft-- <= 0) {
3237
+ yield val;
3238
+ }
3239
+ }
3240
+ })();
3241
+ }
3242
+
3243
+ function opTake(stream, number, options) {
3244
+ validateOperatorOptions(options);
3245
+ const limit = toIntegerOrInfinity(number);
3246
+ return (async function* take() {
3247
+ if (options?.signal?.aborted) {
3248
+ throw abortError();
3249
+ }
3250
+ let numberLeft = limit;
3251
+ for await (const val of stream) {
3252
+ if (options?.signal?.aborted) {
3253
+ throw abortError();
3254
+ }
3255
+ if (numberLeft-- > 0) {
3256
+ yield val;
3257
+ }
3258
+ // Don't get another item from iterator in case we reached the end --
3259
+ // node's comment; the return() this early exit triggers on the source
3260
+ // iterator is what destroys a stream taken short of its EOF.
3261
+ if (numberLeft <= 0) {
3262
+ return;
3263
+ }
3264
+ }
3265
+ })();
3266
+ }
3267
+
3268
+ async function opSome(stream, fn, options) {
3269
+ for await (const unused of opFilter(stream, fn, options)) {
3270
+ return true;
3271
+ }
3272
+ return false;
3273
+ }
3274
+
3275
+ async function opEvery(stream, fn, options) {
3276
+ validateFunctionArg(fn, 'fn');
3277
+ // https://en.wikipedia.org/wiki/De_Morgan%27s_laws -- node's comment.
3278
+ return !(await opSome(stream, async (...args) => !(await fn(...args)), options));
3279
+ }
3280
+
3281
+ async function opFind(stream, fn, options) {
3282
+ for await (const result of opFilter(stream, fn, options)) {
3283
+ return result;
3284
+ }
3285
+ return undefined;
3286
+ }
3287
+
3288
+ async function opReduce(stream, hasInitial, reducer, initialValue, options) {
3289
+ validateFunctionArg(reducer, 'reducer');
3290
+ validateOperatorOptions(options);
3291
+ if (options?.signal?.aborted) {
3292
+ const err = abortError(options.signal.reason);
3293
+ stream.once('error', () => {}); // the error is already propagated
3294
+ // node awaits its internal eos, which RESOLVES on the errored teardown;
3295
+ // the callback form wrapped here is that promise, since the public
3296
+ // callback-less `finished` refuses instead.
3297
+ await new Promise((resolve) => {
3298
+ // h2lean's destroy() returns nothing, unlike node's, so the stream is
3299
+ // handed to eos on its own line.
3300
+ stream.destroy(err);
3301
+ finished(stream, resolve);
3302
+ });
3303
+ throw err;
3304
+ }
3305
+ const ac = new AbortController();
3306
+ const signal = ac.signal;
3307
+ if (options?.signal) {
3308
+ options.signal.addEventListener('abort', () => ac.abort(), { once: true });
3309
+ }
3310
+ let gotAnyItemFromStream = false;
3311
+ try {
3312
+ for await (const value of stream) {
3313
+ gotAnyItemFromStream = true;
3314
+ if (options?.signal?.aborted) {
3315
+ throw abortError();
3316
+ }
3317
+ if (!hasInitial) {
3318
+ initialValue = value;
3319
+ hasInitial = true;
3320
+ } else {
3321
+ initialValue = await reducer(initialValue, value, { signal });
3322
+ }
3323
+ }
3324
+ if (!gotAnyItemFromStream && !hasInitial) {
3325
+ // node's ReduceAwareErrMissingArgs: same code, same custom message.
3326
+ throw errorOf('ERR_MISSING_ARGS', 'Reduce of an empty stream requires an initial value');
3327
+ }
3328
+ } finally {
3329
+ ac.abort();
3330
+ }
3331
+ return initialValue;
3332
+ }
3333
+
3334
+ async function opToArray(stream, options) {
3335
+ validateOperatorOptions(options);
3336
+ const result = [];
3337
+ for await (const val of stream) {
3338
+ if (options?.signal?.aborted) {
3339
+ throw abortError(options.signal.reason);
3340
+ }
3341
+ result.push(val);
3342
+ }
3343
+ return result;
3344
+ }
3345
+
1517
3346
  // The error a stream reports when an RST_STREAM ends it, on either side. node's rule is
1518
3347
  // one line (internal/http2/core.js:2543): `if (err == null && code !== NGHTTP2_NO_ERROR &&
1519
3348
  // code !== NGHTTP2_CANCEL) err = new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code)`.