h2lean 0.9.1 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
@@ -137,6 +174,23 @@ function wantTrailersNT(stream) {
137
174
  }
138
175
  }
139
176
 
177
+ // The tick body of _scheduleFinish, a named function rather than a closure: it runs
178
+ // once per finished stream, and a per-response allocation on the compat finish path
179
+ // was measured into the regression item 44 closes.
180
+ // Not _destroyed here: a stream whose both halves close in the same turn the
181
+ // writable ends flips ST_CLOSED synchronously (_closeNow) while the close EVENTS
182
+ // are deferred -- and node's order for that shape is 'finish' before 'close',
183
+ // with writableFinished true at the close (measured). The only cancel is a
184
+ // writable that never drained: octets still parked on window credit.
185
+ function finishNT(stream) {
186
+ stream._finishQueued = false;
187
+ if (stream._writableFinished || stream._queued !== null) {
188
+ return;
189
+ }
190
+ stream._writableFinished = true;
191
+ stream.emit('finish');
192
+ }
193
+
140
194
  // 'end' and 'close' for a stream whose two halves finished in the same turn.
141
195
  // They were already going to run in the same tick drain, so folding them into
142
196
  // one callback only removes one TickObject per request.
@@ -146,7 +200,10 @@ function emitEndCloseNT(target) {
146
200
  // events go out (internal/http2/core.js:2546) -- see _closeNow for why the drop waits
147
201
  // for this tick here.
148
202
  target.session = undefined;
149
- target.emit('end');
203
+ if (target._eofEmitted !== true) {
204
+ target._eofEmitted = true;
205
+ target.emit('end');
206
+ }
150
207
  target.emit('close');
151
208
  }
152
209
 
@@ -168,7 +225,7 @@ function autoCloseNT(stream) {
168
225
  if (stream._destroyed) {
169
226
  return;
170
227
  }
171
- process.nextTick(emitNT, stream, 'end');
228
+ process.nextTick(emitEndNT, stream);
172
229
  stream._destroy(NO_ERROR, undefined, true);
173
230
  }
174
231
 
@@ -344,6 +401,8 @@ class Http2Stream extends Stream {
344
401
  this._bodyLen = 0; // ...octets of body actually received
345
402
  this._queued = null; // Buffers waiting on window credit
346
403
  this._pending = null; // inbound chunks nobody has read yet
404
+ this._pipes = null; // destinations of pipe(), node's state.pipes
405
+ this._awaitDrain = null; // ...a dest whose false write still parks the flow
347
406
  this._endPending = false; // END_STREAM arrived with no reader
348
407
  this._consumeState = 0; // 0 no reader, 1 delivering, 2 reader is full
349
408
  this._endQueued = false;
@@ -362,6 +421,10 @@ class Http2Stream extends Stream {
362
421
  // sendTrailers() after respond({waitForTrailers:true}) but before 'wantTrailers'
363
422
  // has fired throws ERR_HTTP2_TRAILERS_NOT_READY, measured live.
364
423
  this._trailersReady = false;
424
+ // set by endWithStagedEnd(): the END_STREAM octets are already in the outbound
425
+ // batch, so sendTrailers() closes the stream without staging a second one, and
426
+ // addTrailers() after end() recalls the frame instead
427
+ this._esStaged = false;
365
428
  this._pendingTrailers = null; // trailer block waiting behind a queued body
366
429
  this._pendingTrailersBound = 0; // ...and its outbound estimate, checked when it drains
367
430
  // A refused outbound HEADERS (session._refuseBlock) left the wire a step behind the
@@ -423,6 +486,164 @@ class Http2Stream extends Stream {
423
486
  return this._sentView;
424
487
  }
425
488
 
489
+ // --- the Duplex state surface ------------------------------------------------
490
+ //
491
+ // Measured member-by-member off a live node server stream and read out of node's own
492
+ // internals (internal/streams/readable.js, internal/streams/writable.js, core.js
493
+ // bufferSize/headRequest; tools/probe-duplex-surface.js is the transcript, and
494
+ // test/duplex-surface.test.js pins the table). Every getter is computed from state this
495
+ // file already keeps, plus five lazily-set booleans (_eofEmitted, _errorEmitted,
496
+ // _dataRead, _flowing, _needDrain) written at the event/decision points below --
497
+ // no constructor additions, nothing allocated unless an application reads the member.
498
+ //
499
+ // The one deliberate divergence: writableLength/writableBuffer/bufferSize report the
500
+ // octets THIS stream still parks on window credit. node counts the bytes sitting in the
501
+ // JS Writable buffer before nghttp2 takes them (writableLength) PLUS the ones nghttp2
502
+ // holds (core.js bufferSize = writeQueueSize + writableLength, which double-counts a
503
+ // stalled write: measured 4096 queued reads 4096 and 8192); h2lean accepts a write into
504
+ // the session's staging buffer inside the call, so there is no JS-side buffer to show.
505
+ // Same write-through decision as the cork stub (header above, test/cork-parity.test.js).
506
+
507
+ // node: `!r.destroyed && !r.errorEmitted && !r.endEmitted` -- readable-side, not
508
+ // half-open-ness: a stream that has emitted 'end' reads false with both halves alive.
509
+ get readable() {
510
+ return !this._destroyed && this._errorEmitted !== true && this._eofEmitted !== true;
511
+ }
512
+
513
+ // node's readableDidRead is the dataEmitted bit (readable.js:1857): true once any
514
+ // delivery of octets happened -- through a 'data' event OR a successful read(), because
515
+ // node's read() itself emits 'data' on every chunk it hands back (readable.js read()
516
+ // tail, measured: three reads delivered three data events to a listener attached for
517
+ // the second one).
518
+ get readableDidRead() {
519
+ return this._dataRead === true;
520
+ }
521
+
522
+ // endEmitted, not "the peer's END arrived": false until THIS stream has emitted 'end'.
523
+ get readableEnded() {
524
+ return this._eofEmitted === true;
525
+ }
526
+
527
+ // node's tri-state (readable.js:1901): null until anything ever touches the readable
528
+ // side, true while it flows, false while paused. Measured boundaries: attaching a
529
+ // 'readable' listener reads false, a 'data' listener or resume() reads true, pause()
530
+ // reads false again, and a destroyed stream reads false. The compat path never sets it
531
+ // -- node's compat reads the stream through a 'readable' subscription, so a getter read
532
+ // on a compat stream reports false there; h2lean's compat dispatch does not subscribe
533
+ // (AGENTS.md 5), so an untouched compat-mode stream reads null. Written-up divergence,
534
+ // invisible unless an application mixes the two APIs.
535
+ get readableFlowing() {
536
+ return this._flowing === undefined ? null : this._flowing;
537
+ }
538
+
539
+ // node: `readable !== false && (destroyed || errored) && !endEmitted`.
540
+ get readableAborted() {
541
+ return (this._destroyed || this._streamErrored !== undefined) &&
542
+ this._eofEmitted !== true;
543
+ }
544
+
545
+ get readableEncoding() {
546
+ return this._encoding === undefined ? null : this._encoding;
547
+ }
548
+
549
+ get readableHighWaterMark() {
550
+ return READABLE_HWM;
551
+ }
552
+
553
+ get readableObjectMode() {
554
+ return false;
555
+ }
556
+
557
+ get readableLength() {
558
+ const pending = this._pending;
559
+ if (pending === null) {
560
+ return 0;
561
+ }
562
+ let n = 0;
563
+ for (let i = 0; i < pending.length; i++) {
564
+ const c = pending[i];
565
+ n += c.length === undefined ? c.data.length : c.length;
566
+ }
567
+ return n;
568
+ }
569
+
570
+ get readableBuffer() {
571
+ // node returns the buffer list itself; h2lean hands out a copy -- the live array would
572
+ // let the caller splice chunks out from under the replay queue. Pushed entries are
573
+ // reported as the buffers they hold, which is what node's list shows.
574
+ const pending = this._pending;
575
+ if (pending === null) {
576
+ return [];
577
+ }
578
+ const out = new Array(pending.length);
579
+ for (let i = 0; i < pending.length; i++) {
580
+ const c = pending[i];
581
+ out[i] = c.length === undefined ? c.data : c;
582
+ }
583
+ return out;
584
+ }
585
+
586
+ // node: `(kEnding | kEnded | kDestroyed | kErrored) === 0`.
587
+ get writable() {
588
+ return !this._destroyed && !this._ending && this._streamErrored === undefined;
589
+ }
590
+
591
+ // node's kEnding bit. A plain destroy() ends the writable inside closeStream
592
+ // (`if (!ending) stream.end()`, core.js:2088) -- h2lean reports that without touching
593
+ // _ending (which carries the 'aborted' decision); a destroy WITH an error does not set
594
+ // it, because node's end() skips kEnding on an errored writable (writable.js:876) --
595
+ // measured: the push-after-EOF snapshot reads writableEnded false with writable false.
596
+ get writableEnded() {
597
+ return this._ending || (this._destroyed && this._streamErrored === undefined);
598
+ }
599
+
600
+ get writableObjectMode() {
601
+ return false;
602
+ }
603
+
604
+ get writableLength() {
605
+ const queued = this._queued;
606
+ if (queued === null) {
607
+ return 0;
608
+ }
609
+ let n = 0;
610
+ for (let i = 0; i < queued.length; i++) {
611
+ n += queued[i].length;
612
+ }
613
+ return n;
614
+ }
615
+
616
+ get writableBuffer() {
617
+ return this._queued === null ? [] : this._queued.slice();
618
+ }
619
+
620
+ // node: `kNeedDrain` set and neither destroyed nor ending. h2lean flips the flag from
621
+ // the write()/end() accept verdict -- false when the window still takes bytes, true
622
+ // when the send queue parked them -- and the session clears it as the queue drains.
623
+ get writableNeedDrain() {
624
+ return this._needDrain === true && !this._destroyed && !this._ending;
625
+ }
626
+
627
+ // core.js:2215: `writeQueueSize + writableLength`. The nghttp2 queue this file has no
628
+ // equivalent for (write-through, header above), so the second term is the whole number.
629
+ get bufferSize() {
630
+ return this.writableLength;
631
+ }
632
+
633
+ // node keeps one `errored` per half; the public getter is the READABLE one
634
+ // (readable.js:1939). It holds the Error an 'error' is delivering, set when destroy
635
+ // runs with an error (destroy.js checkError), not when the event fires.
636
+ get errored() {
637
+ return this._streamErrored === undefined ? null : this._streamErrored;
638
+ }
639
+
640
+ // core.js: `!!(flags & STREAM_FLAGS_HEAD_REQUEST)`, set at stream creation from the
641
+ // request line. Same fact in h2lean, read where respond() tests it already: the flag
642
+ // source is the request map, so there is no state to keep out of sync.
643
+ get headRequest() {
644
+ return this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
645
+ }
646
+
426
647
  respond(headers, options) {
427
648
  // node guards the stream's life first (internal/http2/core.js respond():
428
649
  // `if (this.destroyed || this.closed) throw new ERR_HTTP2_INVALID_STREAM()`),
@@ -811,12 +1032,19 @@ class Http2Stream extends Stream {
811
1032
  // the event is owed here instead. A reset or a session destroy is not
812
1033
  // this shape -- there node's errorOrDestroy is a no-op and no 'error'
813
1034
  // goes out (the session-destroy case of test/upstream-push.test.js).
814
- process.nextTick(emitNT, this, 'error', err);
1035
+ process.nextTick(emitErrorOnlyNT, this, err);
815
1036
  }
816
1037
  return false;
817
1038
  }
818
- const buf = typeof chunk === 'string' ? Buffer.from(chunk, encoding || 'utf8') : chunk;
1039
+ // node's encodeString: an encoding-less write(string) uses the writable
1040
+ // default, which setDefaultEncoding is the way to change (writable.js:465).
1041
+ const buf = typeof chunk === 'string'
1042
+ ? Buffer.from(chunk, encoding || this._defaultEnc || 'utf8') : chunk;
819
1043
  const canContinue = this.session.sendData(this, buf, false);
1044
+ // writableNeedDrain is node's needDrain bit: set when a write left the buffer
1045
+ // over the highWaterMark, cleared when the buffer drops back under it (the
1046
+ // session's drain path). It reports the credit stall, nothing else.
1047
+ this._needDrain = !canContinue;
820
1048
  if (cb) {
821
1049
  process.nextTick(cb);
822
1050
  }
@@ -883,6 +1111,41 @@ class Http2Stream extends Stream {
883
1111
  return this;
884
1112
  }
885
1113
 
1114
+ // The compat layer's empty-trailer finish: stage the END_STREAM frame HERE, inside
1115
+ // the read batch that produced the response, instead of from the 'wantTrailers'
1116
+ // tick after the batch has left. The octets, the frame order and every event are
1117
+ // the ones the deferred path produces -- _waitForTrailers stays set, so the tick
1118
+ // still fires 'wantTrailers', the compat handler still answers through
1119
+ // sendTrailers(), and the close machinery still runs from that tick; sendTrailers
1120
+ // sees _esStaged and skips only the second staging. What changes is which socket
1121
+ // batch the frame leaves in: measured, moving it out of the tick was worth ~2.4
1122
+ // microseconds of cpuPerReq on the compat showcase arm (item 44). Only for a stream
1123
+ // with nothing queued and nothing refused -- a body parked on window credit needs
1124
+ // its END_STREAM behind the queued DATA, which the deferred path already arranges.
1125
+ // addTrailers() after end() recalls the frame the way the pushStream cut does:
1126
+ // node withholds END_STREAM until the tick, so a trailer legally added in the
1127
+ // same turn as end() must supersede it; after the flush the frame is gone and the
1128
+ // trailer is lost on node too, because its tick already answered the empty block.
1129
+ endWithStagedEnd() {
1130
+ // end() sets _ending before anything is sent, and the peer-reset 'aborted' rule
1131
+ // reads it -- the fast path must carry the same state (test/compat.test.js).
1132
+ this._ending = true;
1133
+ this.session._frame(frames.DATA, frames.F_END_STREAM, this.id, null);
1134
+ this._esStaged = true;
1135
+ this._endLocalSide();
1136
+ }
1137
+
1138
+ // Undo endWithStagedEnd() while the frame is still in the staging buffer: cut it
1139
+ // out the way the pushStream path cuts a parent's not-yet-written END_STREAM, and
1140
+ // re-arm the deferred machinery. Returns false -- leaving everything as it is --
1141
+ // when the frame has already been committed to the queue or written.
1142
+ _recallStagedEnd() {
1143
+ if (this.session._cutStagedES(this.id)) {
1144
+ this._esStaged = false;
1145
+ this._waitForTrailers = true;
1146
+ }
1147
+ }
1148
+
886
1149
  // Writable-side corking, as a counting stub. node's Http2Stream inherits Writable.cork,
887
1150
  // which buffers write()/end() and defers the DATA to the wire until corked reaches 0;
888
1151
  // h2lean's write() sends straight through (the per-read socket batch already coalesces a
@@ -931,8 +1194,30 @@ class Http2Stream extends Stream {
931
1194
  throw errorOf('ERR_HTTP2_TRAILERS_NOT_READY',
932
1195
  'Trailing headers cannot be sent until after the wantTrailers event is emitted');
933
1196
  }
934
- const block = hdr.block(trailers, { trailer: true }, this.session);
935
- const bound = hdr.sent.bound;
1197
+ let block;
1198
+ let bound;
1199
+ // An empty trailer map is skipped, not run through block(): nothing in it can fail
1200
+ // validation (no name to check, no single-value rule to trip) and it encodes to zero
1201
+ // octets, while block() allocates the parse key list, the strict-singles scratch and
1202
+ // the parse result for every one of them -- and every compat response ends with an
1203
+ // empty trailer map, because the (req,res) layer always answers 'wantTrailers' with
1204
+ // what it recorded: nothing at all when the application added none (item 44).
1205
+ // hdr.sent must not be read for the skipped case: it still holds the previous
1206
+ // block's result.
1207
+ let empty = true;
1208
+ for (const key in trailers) {
1209
+ if (Object.prototype.hasOwnProperty.call(trailers, key)) {
1210
+ empty = false;
1211
+ break;
1212
+ }
1213
+ }
1214
+ if (empty) {
1215
+ block = EMPTY;
1216
+ bound = 0;
1217
+ } else {
1218
+ block = hdr.block(trailers, { trailer: true }, this.session);
1219
+ bound = hdr.sent.bound;
1220
+ }
936
1221
  // node records a null-prototype copy, not the caller's map (`ObjectAssign({
937
1222
  // __proto__: null }, headers)`, internal/http2/core.js sendTrailers -- the shared
938
1223
  // base method, so the client stream records the same shape).
@@ -940,6 +1225,15 @@ class Http2Stream extends Stream {
940
1225
  // the trailers are out: the flag that permitted this call must not keep asking for
941
1226
  // wantTrailers, whatever happens to the bytes below
942
1227
  this._waitForTrailers = false;
1228
+ if (this._esStaged) {
1229
+ // endWithStagedEnd() already put the END_STREAM octets into the batch that
1230
+ // produced this response (item 44); the wire half is done, only the
1231
+ // application-level half-close -- finish, wantTrailers were already fired, and
1232
+ // the close pair -- remains, exactly where it fires without the staging.
1233
+ this._esStaged = false;
1234
+ this._endLocalSide();
1235
+ return this;
1236
+ }
943
1237
  // An empty trailer block does not become a HEADERS frame. nghttp2 has nothing to
944
1238
  // put in a fieldless trailing header section, so node lets the END_STREAM the body
945
1239
  // withheld land on a zero-length DATA instead -- measured: HEADERS/EH, DATA len4
@@ -947,7 +1241,7 @@ class Http2Stream extends Stream {
947
1241
  // because node's (req,res) layer always asks for trailers (internal/http2/compat.js
948
1242
  // kBeginSend passes waitForTrailers: true) and answers with the empty trailer map
949
1243
  // when the application added none.
950
- const empty = block.length === 0;
1244
+ empty = block.length === 0;
951
1245
  if (this._queued !== null) {
952
1246
  // The body is still waiting for credit or for the socket, and this block has to
953
1247
  // follow it: END_STREAM rides on the trailers, so a HEADERS sent now would outrun
@@ -1144,168 +1438,1040 @@ class Http2Stream extends Stream {
1144
1438
  // so the sender is the one that waits, and whatever arrives in the meantime is
1145
1439
  // buffered and replayed on resume(). Returns this, like the Duplex does.
1146
1440
  pause() {
1441
+ this._flowing = false;
1147
1442
  this._pauseConsuming();
1148
1443
  return this;
1149
1444
  }
1150
1445
 
1151
1446
  resume() {
1152
- this._startConsuming();
1447
+ this._flowing = true;
1448
+ this._scheduleResume();
1153
1449
  return this;
1154
1450
  }
1155
1451
 
1156
- isPaused() {
1157
- return this._consumeState === 2;
1452
+ // node's resume() flips the flowing bit synchronously but the delivery itself
1453
+ // runs on the kResumeScheduled next tick, and an attaching 'data' listener only
1454
+ // calls resume when the stream is neither explicitly paused nor in pull mode --
1455
+ // the 'readable' attach has set kHasFlowing, and measured: a 'data' attach
1456
+ // inside a pull handler leaves the buffer for read() untouched.
1457
+ _scheduleResume() {
1458
+ if (this._resumeScheduled === true || this._flowing === false ||
1459
+ this._destroyed) {
1460
+ return;
1461
+ }
1462
+ this._resumeScheduled = true;
1463
+ process.nextTick(() => {
1464
+ this._resumeScheduled = false;
1465
+ if (this._destroyed || this._flowing === false) {
1466
+ return;
1467
+ }
1468
+ this._startConsuming();
1469
+ });
1158
1470
  }
1159
1471
 
1160
- // node maps a per-stream timeout onto the connection's idle timeout.
1161
- setTimeout(ms, cb) {
1162
- this.session.setTimeout(ms, cb);
1163
- return this;
1472
+ isPaused() {
1473
+ return this._consumeState === 2;
1164
1474
  }
1165
1475
 
1166
- // --- internals used by the session ------------------------------------------
1167
- // Both halves have to converge: a handler that answers synchronously inside
1168
- // the 'stream' emit closes the local side BEFORE the peer's END_STREAM is
1169
- // reported, and vice versa. Whichever call sees both halves closed is the one
1170
- // that removes the stream from the session -- without it every request leaks
1171
- // an Http2Stream (and _liveStreams never falls, so close() never finishes).
1172
- _remoteEnded() {
1173
- if (this._state.remoteClose === 1) {
1174
- return;
1476
+ // --- the readable pull surface: read() and push() -----------------------------
1477
+ //
1478
+ // A mini-Readable over the existing `_pending` queue, reproduced member by
1479
+ // member from internal/streams/readable.js (v26) and pinned against a live
1480
+ // node by tools/probe-duplex-surface.js: an arrival emits 'readable' and
1481
+ // nothing else until the application pulls; read() with no argument returns
1482
+ // the whole first chunk, read(n) merges across chunks and hands the
1483
+ // remainder back, an ask past the buffered end returns what the queue can
1484
+ // cover (nothing at all before the EOF is known), every data-returning read
1485
+ // flips dataRead and emits 'data', and a read past the end of an empty,
1486
+ // EOF-known queue schedules the end-of-stream. push() after the EOF errors
1487
+ // with ERR_STREAM_PUSH_AFTER_EOF through 'error', push() on a destroyed
1488
+ // stream is a silent false, push(null) always returns false. The queue holds
1489
+ // two entry kinds: a bare Buffer is octets off the socket (credit-owed), a
1490
+ // `{ data }` wrapper is octets the application pushed (never credited — they
1491
+ // never came off the wire, and crediting them would let a peer send bytes we
1492
+ // never advertised).
1493
+ //
1494
+ // The EOF becomes known to node when the END_STREAM is processed in the read
1495
+ // callback — measured by stack (stream_base_commons:236 -> Readable.push ->
1496
+ // onEofChunk): that push(null) emits 'readable' synchronously from
1497
+ // onEofChunk's non-sync branch, and onStreamClose pushes it again for the
1498
+ // paths that end without a final frame (reset, teardown). h2lean knows the
1499
+ // EOF at the same frame and parks it in `_endPending` when no reader is
1500
+ // watching, which matches the visible sequences (data, end, close, and the
1501
+ // measured-identical push-after-EOF matrix) with the parked EOF standing in
1502
+ // for the buffered one.
1503
+
1504
+ read(n) {
1505
+ // node's argument normalisation, kept exact: no argument is NaN and means
1506
+ // the whole first chunk; a non-integer goes through parseInt.
1507
+ if (n === undefined) {
1508
+ n = NaN;
1509
+ } else if (!Number.isInteger(n)) {
1510
+ n = Number.parseInt(n, 10);
1175
1511
  }
1176
- // The other half of the content-length promise: too many octets is caught as they arrive
1177
- // (session _onDataFrame, a connection error), too few can only be seen here, where the
1178
- // message ends. Measured on node (h2spec http2/8.1.2.6): RST_STREAM(PROTOCOL_ERROR) and the
1179
- // application is told ERR_HTTP2_STREAM_ERROR -- the short body is one request's failure, not
1180
- // the session's, which is the same split nghttp2 makes and the reason the two directions of
1181
- // the same lie get two different codes.
1182
- if (this._expLen >= 0 && this._bodyLen < this._expLen) {
1183
- this.session._streamError(this, PROTOCOL_ERROR, `content-length ${this._expLen} with only ` +
1184
- `${this._bodyLen} octets received`);
1185
- return;
1512
+ if (this._destroyed) {
1513
+ return null;
1186
1514
  }
1187
- this._state.remoteClose = 1;
1188
- this.endAfterHeaders = true;
1189
- // the readable side is done: 'end' after the last 'data', like a Readable.
1190
- // No auto-destroy: the application still has to answer. node keeps the
1191
- // writable side of an unanswered request open as well.
1192
- if (this._state.localClose === 1 && !this._waitForTrailers) {
1193
- // The local half is only *finished* once END_STREAM left on the wire. A stream that
1194
- // still owes a trailer block owes that END_STREAM too -- the body DATA was framed
1195
- // without it (sendTrailers() puts the close on the trailer block, or on an empty DATA
1196
- // when the block has no fields) -- so closing here would leave the response
1197
- // unanswered for the peer and drop the owed frame. node's rule is the same and lives
1198
- // in the writable shutdown, not in the read path: a stream with
1199
- // STREAM_FLAGS_HAS_TRAILERS set is not shut down early
1200
- // (internal/http2/core.js, `Trailers are pending, so the writable side cannot be
1201
- // shut down early`). Measured: a compat response that ends with no body against an
1202
- // unread request put HEADERS then a zero-length DATA/END_STREAM on node's wire, with
1203
- // the stream close after both; ending here sent the HEADERS only and the client
1204
- // waited for an answer that never came.
1205
- this._closeNow();
1206
- process.nextTick(emitEndCloseNT, this);
1207
- return;
1515
+ const pending = this._pending;
1516
+ let avail = 0;
1517
+ let firstLen = 0;
1518
+ if (pending !== null) {
1519
+ for (let i = 0; i < pending.length; i++) {
1520
+ const c = pending[i];
1521
+ const l = c.length === undefined ? c.data.length : c.length;
1522
+ avail += l;
1523
+ if (i === 0) {
1524
+ firstLen = l;
1525
+ }
1526
+ }
1208
1527
  }
1209
- if (this._state.state === ST_OPEN) {
1210
- this._state.state = ST_HALF_CLOSED_REMOTE;
1528
+ // howMuchToRead, byte mode (readable.js:678): the NaN fast path is the
1529
+ // first chunk's length; more-than-buffered is only satisfiable past the
1530
+ // EOF, where the whole remainder comes back instead.
1531
+ const eofKnown = this._eofSeen === true || this._endPending === true;
1532
+ let want;
1533
+ if (n <= 0 || (avail === 0 && eofKnown)) {
1534
+ want = 0;
1535
+ } else if (Number.isNaN(n)) {
1536
+ // node's decoder branch of howMuchToRead (readable.js:684): the
1537
+ // one-chunk-at-a-time fast path belongs to flowing mode -- in pull mode
1538
+ // an argumentless read returns the WHOLE buffered character count,
1539
+ // because the queue now holds strings, not buffers.
1540
+ want = this._decoder === undefined ? firstLen
1541
+ : (this._flowing === true && avail !== 0) ? firstLen : avail;
1542
+ } else if (n <= avail) {
1543
+ want = n;
1544
+ } else {
1545
+ want = eofKnown ? avail : 0;
1546
+ }
1547
+ let ret = null;
1548
+ if (want > 0) {
1549
+ ret = this._takeQueued(want);
1550
+ }
1551
+ if (this._pending === null || this._pending.length === 0) {
1552
+ // the tail of node's read(): asking past what the queue holds — node
1553
+ // compares the asked amount with what howMuchToRead allowed (nOrig !== n),
1554
+ // which the argumentless NaN form always is — with the EOF known and
1555
+ // nothing left is what schedules the end-of-stream: endReadable.
1556
+ if (n !== want && eofKnown) {
1557
+ this._scheduleEOF();
1558
+ } else if (!eofKnown && typeof this._read === 'function') {
1559
+ // node fires maybeReadMore after a consumption drops the buffer below
1560
+ // the mark, and that is where _read gets called -- the only thing in
1561
+ // h2lean that installs an _read is the legacy wrap(), whose paused
1562
+ // source needs exactly this nudge to continue; the empty-and-not-EOF
1563
+ // condition is where node's own call lands for a pull consumer.
1564
+ this._read();
1565
+ }
1211
1566
  }
1212
- if (!this._isConsuming()) {
1213
- // Nothing has read the buffered bytes yet, so 'end' must not overtake them:
1214
- // a reader that attaches later is owed the whole sequence, EOF included.
1215
- this._endPending = true;
1216
- return;
1567
+ if (ret !== null && this._errorEmitted !== true && this._closeDelivered !== true) {
1568
+ // node's read() hands the chunk to the consumer as a 'data' event too —
1569
+ // measured: three reads delivered three data events to a listener
1570
+ // attached for the second one. dataEmitted flips with the emission.
1571
+ this._dataRead = true;
1572
+ this.emit('data', ret);
1217
1573
  }
1218
- process.nextTick(emitNT, this, 'end');
1574
+ return ret;
1219
1575
  }
1220
1576
 
1221
- // The writable-side 'finish' -- node's Writable fires it once every write has been
1222
- // accepted by the stream machinery and the writable half has ended; a destroy in
1223
- // the same turn as the end() cancels it (upstream's test-http2-respond-with-fd-finish.js
1224
- // pins both shapes: finish, then close with writableFinished true on a clean send;
1225
- // close with writableFinished false and no 'finish' on an abort). The tick is also
1226
- // what keeps the event behind 'wantTrailers' -- measured on v26.12.1, 'finish'
1227
- // precedes 'wantTrailers' on the trailers shape. A body still queued on window
1228
- // credit re-runs _endLocalSide when the queue drains (session._release), which is
1229
- // where the second scheduling comes from.
1230
- _scheduleFinish() {
1231
- if (this._writableFinished || this._finishQueued) {
1232
- return;
1233
- }
1234
- this._finishQueued = true;
1235
- process.nextTick(() => {
1236
- this._finishQueued = false;
1237
- // not _destroyed here: a stream whose both halves close in the same turn the
1238
- // writable ends flips ST_CLOSED synchronously (_closeNow) while the close EVENTS
1239
- // are deferred -- and node's order for that shape is 'finish' before 'close',
1240
- // with writableFinished true at the close (measured). The only cancel is a
1241
- // writable that never drained: octets still parked on window credit.
1242
- if (this._writableFinished || this._queued !== null) {
1243
- return;
1577
+ // Pull `n` octets off the queue: the exact-first-chunk case returns the buffer
1578
+ // view itself (no copy, the AGENTS.md 5 rule that a chunk the app holds is
1579
+ // never recycled); a read that splits or merges allocates one buffer and
1580
+ // re-queues the remainder with the origin it had. Credit goes out for the
1581
+ // wire octets handed over, in one call, only for them.
1582
+ _takeQueued(n) {
1583
+ const pending = this._pending;
1584
+ const first = pending[0];
1585
+ const firstLen = first.length === undefined ? first.data.length : first.length;
1586
+ if (firstLen === n) {
1587
+ pending.shift();
1588
+ if (pending.length === 0) {
1589
+ this._pending = null;
1244
1590
  }
1245
- this._writableFinished = true;
1246
- this.emit('finish');
1247
- });
1591
+ if (first.length !== undefined) {
1592
+ this._release(n);
1593
+ return first;
1594
+ }
1595
+ if (first.bytes !== undefined) {
1596
+ this._release(first.bytes);
1597
+ }
1598
+ return first.data;
1599
+ }
1600
+ if (first.length === undefined && typeof first.data === 'string') {
1601
+ // node's fromList decoder branch (readable.js:2060): string entries
1602
+ // concatenate toward the asked length and a split lands on character
1603
+ // boundaries. The wire octets an entry stands for are credited per slice
1604
+ // by the slice's own length in the encoding -- the queue is homogeneous
1605
+ // once an encoding is set (setEncoding merged what stood there, every
1606
+ // later arrival is decoded at the door), so a string entry is the only
1607
+ // kind this loop sees.
1608
+ let ret = '';
1609
+ let need = n;
1610
+ let j = 0;
1611
+ while (need > 0) {
1612
+ const e = pending[j];
1613
+ const s = e.data;
1614
+ if (need > s.length) {
1615
+ ret += s;
1616
+ need -= s.length;
1617
+ if (e.bytes !== undefined) {
1618
+ this._release(e.bytes);
1619
+ }
1620
+ j++;
1621
+ } else {
1622
+ if (need === s.length) {
1623
+ ret += s;
1624
+ if (e.bytes !== undefined) {
1625
+ this._release(e.bytes);
1626
+ }
1627
+ j++;
1628
+ } else {
1629
+ const head = s.slice(0, need);
1630
+ ret += head;
1631
+ if (e.bytes !== undefined) {
1632
+ const owed = Math.min(Buffer.byteLength(head, this._encoding), e.bytes);
1633
+ this._release(owed);
1634
+ e.bytes -= owed;
1635
+ }
1636
+ e.data = s.slice(need);
1637
+ }
1638
+ need = 0;
1639
+ }
1640
+ }
1641
+ if (j > 0) {
1642
+ pending.splice(0, j);
1643
+ }
1644
+ if (pending.length === 0) {
1645
+ this._pending = null;
1646
+ }
1647
+ return ret;
1648
+ }
1649
+ const out = Buffer.allocUnsafe(n);
1650
+ let off = 0;
1651
+ let i = 0;
1652
+ let wire = 0;
1653
+ while (off < n) {
1654
+ const c = pending[i];
1655
+ const buf = c.length === undefined ? c.data : c;
1656
+ const take = buf.length <= n - off ? buf.length : n - off;
1657
+ buf.copy(out, off, 0, take);
1658
+ off += take;
1659
+ if (c.length !== undefined) {
1660
+ wire += take;
1661
+ }
1662
+ if (take === buf.length) {
1663
+ i++;
1664
+ } else {
1665
+ pending[i] = c.length === undefined ? { data: buf.subarray(take) } : buf.subarray(take);
1666
+ }
1667
+ }
1668
+ if (i > 0) {
1669
+ pending.splice(0, i);
1670
+ }
1671
+ if (pending.length === 0) {
1672
+ this._pending = null;
1673
+ }
1674
+ if (wire !== 0) {
1675
+ this._release(wire);
1676
+ }
1677
+ return out;
1248
1678
  }
1249
1679
 
1250
- _endLocalSide() {
1251
- const first = this._state.localClose !== 1;
1252
- this._state.localClose = 1;
1253
- this._endQueued = false;
1254
- if (this._blockRefused) {
1255
- // The half-close is the application's, and node records it whether or not the
1256
- // octets went out (`_writableState.ending` is what decides 'aborted'). The close
1257
- // machinery below must not run: it would finish the stream with NO_ERROR here,
1258
- // synchronously, ahead of the deferred FRAME_SIZE_ERROR close node's onFrameError
1259
- // schedules -- measured, node reports rstCode 6 for this shape and h2lean reported 0.
1260
- return;
1680
+ // node's Writable-side sibling call: push queued readable data with NO wire
1681
+ // accounting — the octets did not come off the socket, so _release must never
1682
+ // see them (a credit for them would advertise window the peer never spent).
1683
+ push(chunk, encoding) {
1684
+ if (chunk === null) {
1685
+ // push(null) is the EOF into the readable queue: it never returns true and
1686
+ // is silent when the EOF is already owed (node's onEofChunk early return).
1687
+ if (!this._eofSeen && !this._endPending && this._eofEmitted !== true) {
1688
+ this._eofSeen = true;
1689
+ this._endPending = true;
1690
+ this._flushDecoder();
1691
+ if (this._pending === null || this._pending.length === 0) {
1692
+ if (this._isConsuming()) {
1693
+ this._endPending = false;
1694
+ this._scheduleEOF();
1695
+ } else if (this.listenerCount('readable') > 0) {
1696
+ // node's onEofChunk sync branch, same mechanism as the wire EOF in
1697
+ // _remoteEnded: the pull consumer is woken synchronously, and the
1698
+ // 'end' waits for a read() (or a resume) that reaches the EOF.
1699
+ this.emit('readable');
1700
+ }
1701
+ }
1702
+ }
1703
+ return false;
1261
1704
  }
1262
- if (this._queued === null) {
1263
- // every octet handed over has been accepted by the session: node's condition
1264
- // for the writable 'finish'
1265
- this._scheduleFinish();
1705
+ if (chunk === undefined) {
1706
+ // node's byte-mode chain lets undefined fall past the type error into the
1707
+ // empty-chunk branch: no queueing, no event, the canPushMore return only.
1708
+ return this._canPushMore();
1709
+ }
1710
+ // node's readableAddChunkPushByteMode order is load-bearing: convert,
1711
+ // then the empty-chunk branch, and only after it the after-EOF error and
1712
+ // the destroyed silence -- an empty chunk after EOF returns canPushMore,
1713
+ // it does not error.
1714
+ let buf = chunk;
1715
+ let enc = encoding;
1716
+ if (typeof buf === 'string') {
1717
+ if (enc === undefined || enc === '') {
1718
+ enc = 'utf8'; // the readable side's defaultEncoding; setDefaultEncoding is the WRITABLE's
1719
+ }
1720
+ if (this._encoding !== enc) {
1721
+ buf = Buffer.from(buf, enc);
1722
+ enc = '';
1723
+ }
1724
+ } else if (buf instanceof Buffer) {
1725
+ enc = '';
1726
+ } else if (ArrayBuffer.isView(buf)) {
1727
+ buf = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
1728
+ enc = '';
1729
+ } else {
1730
+ this.destroy(errorOf('ERR_INVALID_ARG_TYPE',
1731
+ 'The "chunk" argument must be of type string or an instance of Buffer, ArrayBufferView, or DataView'));
1732
+ return false;
1266
1733
  }
1267
- if (this._state.state === ST_OPEN) {
1268
- this._state.state = ST_HALF_CLOSED_LOCAL;
1734
+ if (buf.length === 0) {
1735
+ return this._canPushMore();
1269
1736
  }
1270
- if (this._waitForTrailers) {
1271
- // one shot: a later end() must not ask for trailers a second time. The flag
1272
- // itself stays set, because sendTrailers() is only allowed while it is set.
1273
- if (first) {
1274
- process.nextTick(wantTrailersNT, this);
1737
+ if (this._eofSeen === true || this._eofEmitted === true) {
1738
+ const err = errorOf('ERR_STREAM_PUSH_AFTER_EOF', 'push() after EOF');
1739
+ if (!this._destroyed) {
1740
+ // node's errorOrDestroy destroys the stream through its autoDestroy, so
1741
+ // this arrives as 'error' then 'close' on the next ticks — the same
1742
+ // route the write-after-end shape takes in write() above.
1743
+ this.destroy(err);
1275
1744
  }
1276
- return;
1745
+ return false;
1277
1746
  }
1278
- if (this._state.remoteClose === 1) {
1279
- this._closeIfBothDone();
1280
- } else {
1281
- // the response is over and the peer's half is not: this is the shape node
1282
- // closes for the application (see _maybeAutoClose). A stream the peer has
1283
- // already ended takes the graceful close above, which is also what node's
1284
- // wire shows there -- no RST, because nghttp2 refuses to reset what both
1285
- // halves have closed (tools/probe-stream-teardown.js, 'request-ended').
1286
- this._maybeAutoClose();
1747
+ if (this._destroyed || this._errorEmitted === true) {
1748
+ return false; // node: kDestroyed|kErrored is the silent false
1749
+ }
1750
+ if (this._decoder !== undefined && !enc) {
1751
+ // decode at the door, node's kDecoder branch: the queue holds characters
1752
+ // from here on. A chunk the decoder swallowed whole (a split multi-byte
1753
+ // sequence) queues nothing and wakes nothing -- canPushMore only.
1754
+ const str = this._decoder.write(buf);
1755
+ if (str.length === 0) {
1756
+ return this._canPushMore();
1757
+ }
1758
+ buf = str;
1759
+ }
1760
+ if (this._pending === null) {
1761
+ this._pending = [];
1287
1762
  }
1763
+ this._pending.push({ data: buf });
1764
+ this._scheduleReadable();
1765
+ return this._canPushMore();
1288
1766
  }
1289
1767
 
1290
- // node's Http2Stream[kMaybeDestroy] (internal/http2/core.js): a response the
1291
- // server session has finished, with trailers neither requested nor sent
1292
- // (STREAM_FLAGS_HAS_TRAILERS) and a request side nobody ever started to consume
1293
- // (`!state.didRead && readableFlowing === null`), is closed by the session
1294
- // itself -- `setImmediate(callStreamClose)` off the writable side's 'finish',
1295
- // and closeStream submits RST_STREAM(NO_ERROR). Measured on v26.12.1
1296
- // (tools/probe-stream-teardown.js, 'answer-only'): HEADERS, DATA, then
1297
- // RST_STREAM(NO_ERROR) on the wire and the stream destroyed -- and the
1298
- // boundaries with it: 'resume-then-answer' shows that touching the readable
1299
- // side stops the auto-close, and 'request-ended' that a stream the peer already
1300
- // ended never gets one. Without it a peer that sends HEADERS without END_STREAM
1301
- // and no DATA holds a stream and a _liveStreams slot until the idle timeout,
1302
- // and a closing session waits for it forever (AGENTS.md 10, item 2).
1303
- // `_consumeState === 0` is this file's reading of `!didRead && flowing ===
1304
- // null`: no reader attached and no pause()/resume() called -- either has
1305
- // touched the request, and node stops there too.
1306
- _maybeAutoClose() {
1307
- if (this._destroyed || !this.headersSent || this._waitForTrailers ||
1308
- this._consumeState !== 0) {
1768
+ // node's canPushMore: below the watermark, or nothing buffered, and never
1769
+ // past the EOF the readable queue has received.
1770
+ _canPushMore() {
1771
+ if (this._eofSeen === true) {
1772
+ return false;
1773
+ }
1774
+ const n = this.readableLength;
1775
+ return n < READABLE_HWM || n === 0;
1776
+ }
1777
+
1778
+ // node's Readable.prototype.setEncoding (readable.js:631), member by member:
1779
+ // a FRESH StringDecoder replaces whatever was set before (an unknown name
1780
+ // throws ERR_UNKNOWN_ENCODING synchronously out of the StringDecoder
1781
+ // constructor; `null` and `undefined` decode as utf8, and the getter reports
1782
+ // what the decoder normalised, not what the caller passed), the octets
1783
+ // already queued are decoded through it and merged into ONE string entry, and
1784
+ // if the EOF is already known the decoder's flush rides along. From here the
1785
+ // queue holds strings and `readableLength` counts characters -- node's
1786
+ // state.length does the same once a decoder exists, which is why the
1787
+ // watermark arithmetic in _canPushMore needs no special case. The wire
1788
+ // octets the merged string stands for stay credited as a bundle on its
1789
+ // consumption (the `bytes` field), so a setEncoding between DATA frames
1790
+ // cannot leak or invent window.
1791
+ setEncoding(enc) {
1792
+ const decoder = new StringDecoder(enc);
1793
+ this._decoder = decoder;
1794
+ this._encoding = decoder.encoding;
1795
+ const pending = this._pending;
1796
+ if (pending !== null) {
1797
+ let content = '';
1798
+ // octets the old decoder still held: they were never delivered and were
1799
+ // never credited; the merged entry inherits the debt.
1800
+ let wire = this._decHeld === undefined ? 0 : this._decHeld;
1801
+ this._decHeld = undefined;
1802
+ for (let i = 0; i < pending.length; i++) {
1803
+ const c = pending[i];
1804
+ if (c.length !== undefined) {
1805
+ content += decoder.write(c);
1806
+ wire += c.length;
1807
+ } else {
1808
+ content += decoder.write(c.data);
1809
+ if (c.bytes !== undefined) {
1810
+ wire += c.bytes;
1811
+ }
1812
+ }
1813
+ }
1814
+ if (this._eofSeen === true || this._endPending === true) {
1815
+ content += decoder.end();
1816
+ }
1817
+ pending.length = 0;
1818
+ this._pending = null;
1819
+ if (content !== '') {
1820
+ this._pending = [{ data: content, bytes: wire }];
1821
+ }
1822
+ }
1823
+ return this;
1824
+ }
1825
+
1826
+ // node's Writable.prototype.setDefaultEncoding (writable.js:537): the name is
1827
+ // lower-cased first because node::ParseEncoding requires it, an unknown one
1828
+ // throws ERR_UNKNOWN_ENCODING synchronously, and the call returns the stream.
1829
+ // It is the WRITABLE half's default -- what an encoding-less write(string)
1830
+ // encodes with; the readable side keeps its own 'utf8'.
1831
+ setDefaultEncoding(encoding) {
1832
+ if (typeof encoding === 'string') {
1833
+ encoding = encoding.toLowerCase();
1834
+ }
1835
+ if (!Buffer.isEncoding(encoding)) {
1836
+ const err = new TypeError(`Unknown encoding: ${encoding}`);
1837
+ err.code = 'ERR_UNKNOWN_ENCODING';
1838
+ throw err;
1839
+ }
1840
+ this._defaultEnc = encoding;
1841
+ return this;
1842
+ }
1843
+
1844
+ // The EOF flush of the readable decoder -- node's onEofChunk head
1845
+ // (readable.js:849): the tail a split multi-byte sequence left in the decoder
1846
+ // becomes one last queue entry before the end machinery runs, carrying the
1847
+ // octets held there as its credit.
1848
+ _flushDecoder() {
1849
+ if (this._decoder === undefined) {
1850
+ return;
1851
+ }
1852
+ const tail = this._decoder.end();
1853
+ if (tail.length !== 0) {
1854
+ if (this._pending === null) {
1855
+ this._pending = [];
1856
+ }
1857
+ const bytes = this._decHeld === undefined ? 0 : this._decHeld;
1858
+ this._decHeld = undefined;
1859
+ this._pending.push({ data: tail, bytes });
1860
+ }
1861
+ }
1862
+
1863
+ // node's Readable.prototype.pipe (internal/streams/readable.js:978), not the
1864
+ // legacy Stream.prototype.pipe the bare base would supply: the tracked
1865
+ // destination list, the unpipe() surface, and the teardown that makes a
1866
+ // destroyed or finished source end and unpipe its destinations -- measured
1867
+ // on a live node the sink of a stream destroyed mid-pipe reports
1868
+ // pipe,finish,unpipe,close where the legacy base stops at pipe,close
1869
+ // (test/pipe-parity.test.js). The await-drain bookkeeping is node's
1870
+ // single-dest fast value promoted to a Set for the second destination.
1871
+ pipe(dest, options) {
1872
+ const src = this;
1873
+ if (src._pipes === null) {
1874
+ src._pipes = [];
1875
+ }
1876
+ src._pipes.push(dest);
1877
+
1878
+ const doEnd = (!options || options.end !== false) &&
1879
+ dest !== process.stdout && dest !== process.stderr;
1880
+ const endFn = doEnd ? onend : unpipe;
1881
+ if (src._eofEmitted === true) {
1882
+ process.nextTick(endFn);
1883
+ } else {
1884
+ src.once('end', endFn);
1885
+ }
1886
+
1887
+ dest.on('unpipe', onunpipe);
1888
+ function onunpipe(readable, unpipeInfo) {
1889
+ if (readable === src) {
1890
+ if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
1891
+ unpipeInfo.hasUnpiped = true;
1892
+ cleanup();
1893
+ }
1894
+ }
1895
+ }
1896
+
1897
+ function onend() {
1898
+ dest.end();
1899
+ }
1900
+
1901
+ let ondrain;
1902
+ let cleanedUp = false;
1903
+ function cleanup() {
1904
+ dest.removeListener('close', onclose);
1905
+ dest.removeListener('finish', onfinish);
1906
+ if (ondrain) {
1907
+ dest.removeListener('drain', ondrain);
1908
+ }
1909
+ dest.removeListener('error', onerror);
1910
+ dest.removeListener('unpipe', onunpipe);
1911
+ src.removeListener('end', onend);
1912
+ src.removeListener('end', unpipe);
1913
+ src.removeListener('data', ondata);
1914
+ cleanedUp = true;
1915
+ // a dest that errored or closed while the source waited on its drain
1916
+ // must not leave the flow parked for a writer that is gone
1917
+ if (ondrain && src._awaitDrain !== null) {
1918
+ ondrain();
1919
+ }
1920
+ }
1921
+
1922
+ function pause() {
1923
+ if (!cleanedUp) {
1924
+ if (src._pipes.length === 1 && src._pipes[0] === dest) {
1925
+ src._awaitDrain = dest;
1926
+ } else if (src._pipes.includes(dest)) {
1927
+ if (!(src._awaitDrain instanceof Set)) {
1928
+ src._awaitDrain = new Set(src._awaitDrain === null ? [] : [src._awaitDrain]);
1929
+ }
1930
+ src._awaitDrain.add(dest);
1931
+ }
1932
+ src.pause();
1933
+ }
1934
+ if (!ondrain) {
1935
+ ondrain = pipeOnDrain;
1936
+ dest.on('drain', ondrain);
1937
+ }
1938
+ }
1939
+
1940
+ function pipeOnDrain() {
1941
+ const a = src._awaitDrain;
1942
+ if (a === dest) {
1943
+ src._awaitDrain = null;
1944
+ } else if (a instanceof Set) {
1945
+ a.delete(dest);
1946
+ }
1947
+ const still = src._awaitDrain;
1948
+ if ((still === null || still.size === 0) && src.listenerCount('data') > 0) {
1949
+ src.resume();
1950
+ }
1951
+ }
1952
+
1953
+ src.on('data', ondata);
1954
+ function ondata(chunk) {
1955
+ try {
1956
+ if (dest.write(chunk) === false) {
1957
+ pause();
1958
+ }
1959
+ } catch (error) {
1960
+ dest.destroy(error);
1961
+ }
1962
+ }
1963
+
1964
+ // If the dest has an error, then stop piping into it. However, don't
1965
+ // suppress the throwing behavior for this (node's comment, verbatim rule).
1966
+ function onerror(er) {
1967
+ unpipe();
1968
+ dest.removeListener('error', onerror);
1969
+ if (dest.listenerCount('error') === 0) {
1970
+ const s = dest._writableState || dest._readableState;
1971
+ if (s && !s.errorEmitted) {
1972
+ dest.destroy(er);
1973
+ } else {
1974
+ dest.emit('error', er);
1975
+ }
1976
+ }
1977
+ }
1978
+ dest.prependListener('error', onerror);
1979
+
1980
+ // Both close and finish should trigger unpipe, but only once.
1981
+ function onclose() {
1982
+ dest.removeListener('finish', onfinish);
1983
+ unpipe();
1984
+ }
1985
+ dest.once('close', onclose);
1986
+ function onfinish() {
1987
+ dest.removeListener('close', onclose);
1988
+ unpipe();
1989
+ }
1990
+ dest.once('finish', onfinish);
1991
+
1992
+ function unpipe() {
1993
+ src.unpipe(dest);
1994
+ }
1995
+
1996
+ dest.emit('pipe', src);
1997
+
1998
+ if (dest.writableNeedDrain === true) {
1999
+ pause();
2000
+ } else if (src._flowing !== true) {
2001
+ src.resume();
2002
+ }
2003
+ return dest;
2004
+ }
2005
+
2006
+ // node's Readable.prototype.unpipe (readable.js:1180): no argument removes
2007
+ // every destination and stops the flow; one argument removes that
2008
+ // destination if it is piped to, and the call is its own 'unpipe' event
2009
+ // onto the dest with the hasUnpiped record the pipe closure cleans up on.
2010
+ unpipe(dest) {
2011
+ const pipes = this._pipes;
2012
+ if (pipes === null || pipes.length === 0) {
2013
+ return this;
2014
+ }
2015
+ if (!dest) {
2016
+ const dests = pipes;
2017
+ this._pipes = [];
2018
+ this.pause();
2019
+ for (let i = 0; i < dests.length; i++) {
2020
+ dests[i].emit('unpipe', this, { hasUnpiped: false });
2021
+ }
2022
+ return this;
2023
+ }
2024
+ const index = pipes.indexOf(dest);
2025
+ if (index === -1) {
2026
+ return this;
2027
+ }
2028
+ pipes.splice(index, 1);
2029
+ if (pipes.length === 0) {
2030
+ this.pause();
2031
+ }
2032
+ dest.emit('unpipe', this, { hasUnpiped: false });
2033
+ return this;
2034
+ }
2035
+
2036
+ // --- the async-iteration surface -------------------------------------------
2037
+ // node's readable-iteration protocol (internal/streams/readable.js:1552-1805)
2038
+ // and the fourteen helpers the public `stream` module bolts onto the same
2039
+ // prototype (stream.js:72-103, wrapping internal/streams/operators): the
2040
+ // transform family returns `Readable.from(generator)` -- measured on a live
2041
+ // node server stream: `map(fn)` yields an objectMode Readable -- and the
2042
+ // promise family returns the operation's promise. The iterator itself is a
2043
+ // pull machine over read(); break over for-await destroys through the
2044
+ // iterator's return() (AbortError into _destroy, RST CANCEL(8), events
2045
+ // aborted, error:ABORT_ERR, close), while a natural end leaves the stream
2046
+ // alive -- node reaches finalize() in both cases, but Http2Stream sets
2047
+ // autoDestroy false (core.js:2132), so only the still-active return()
2048
+ // branch satisfies finalize's second clause (measured: destroyed false,
2049
+ // readableEnded true after a clean loop; destroyed true, rstCode 8 after
2050
+ // break, both read inside the same handler turn).
2051
+ [Symbol.asyncIterator]() {
2052
+ return createStreamIterator(this, undefined);
2053
+ }
2054
+
2055
+ iterator(options) {
2056
+ if (options !== undefined) {
2057
+ validateObjectArg(options, 'options');
2058
+ }
2059
+ return createStreamIterator(this, options);
2060
+ }
2061
+
2062
+ map(fn, options) {
2063
+ return Readable.from(opMap(this, fn, options));
2064
+ }
2065
+
2066
+ filter(fn, options) {
2067
+ return Readable.from(opFilter(this, fn, options));
2068
+ }
2069
+
2070
+ flatMap(fn, options) {
2071
+ return Readable.from(opFlatMap(this, fn, options));
2072
+ }
2073
+
2074
+ drop(number, options) {
2075
+ return Readable.from(opDrop(this, number, options));
2076
+ }
2077
+
2078
+ take(number, options) {
2079
+ return Readable.from(opTake(this, number, options));
2080
+ }
2081
+
2082
+ reduce(reducer, initialValue, options) {
2083
+ // node's reduce tests `arguments.length > 1` inside the operator to tell
2084
+ // "no initial value" from "initial value undefined"; the arity has to be
2085
+ // read at the call, which is here.
2086
+ return opReduce(this, arguments.length > 1, reducer, initialValue, options);
2087
+ }
2088
+
2089
+ forEach(fn, options) {
2090
+ return opForEach(this, fn, options);
2091
+ }
2092
+
2093
+ toArray(options) {
2094
+ return opToArray(this, options);
2095
+ }
2096
+
2097
+ some(fn, options) {
2098
+ return opSome(this, fn, options);
2099
+ }
2100
+
2101
+ every(fn, options) {
2102
+ return opEvery(this, fn, options);
2103
+ }
2104
+
2105
+ find(fn, options) {
2106
+ return opFind(this, fn, options);
2107
+ }
2108
+
2109
+ // node's Readable.prototype.compose (readable.js:1810 plus
2110
+ // internal/streams/compose.js, the Node-stream branch): the composed Duplex
2111
+ // writes into this and reads out of the chain behind it. h2lean drives the
2112
+ // two-stream chain with its own pipe() -- the port of Readable.prototype.pipe
2113
+ // above -- where node uses internal/streams/pipeline; for the prototype
2114
+ // method's single argument those are the same chain (src 'end' -> dest.end(),
2115
+ // src error -> dest teardown), and the rest is node's wiring verbatim:
2116
+ // d._write into head with the drain callback, d._final = head.end(),
2117
+ // tail 'data'/'end' into d.push, teardown destroying the tail. Web streams
2118
+ // (TransformStream and friends) are refused here where node composes them --
2119
+ // KNOWN DIVERGENCE, stated in the header of this file's difference list.
2120
+ compose(stream, options) {
2121
+ if (options != null) {
2122
+ validateObjectArg(options, 'options');
2123
+ }
2124
+ validateSignalArg(options);
2125
+ const tail = typeof stream === 'function' ? Duplex.from(stream) : stream;
2126
+ if (tail === null || typeof tail !== 'object' ||
2127
+ typeof tail.pipe !== 'function' || typeof tail.write !== 'function') {
2128
+ // node's internal compose SKIPS non-streams in its own loop (the
2129
+ // "TODO: add checks for non streams" branch) and the refusal actually
2130
+ // comes from pipeline's `body` validation -- measured code:
2131
+ // ERR_INVALID_ARG_TYPE, not ERR_INVALID_ARG_VALUE.
2132
+ throw errorOf('ERR_INVALID_ARG_TYPE',
2133
+ 'The "body" argument must be of type function or an instance of Stream. ' +
2134
+ `Received type ${typeof stream} (${inspect(stream)}).`);
2135
+ }
2136
+ let ondrain = null;
2137
+ let onfinish = null;
2138
+ let onclose = undefined;
2139
+ const src = this;
2140
+ const d = new Duplex({
2141
+ writableObjectMode: !!src.writableObjectMode,
2142
+ readableObjectMode: !!tail.readableObjectMode,
2143
+ writable: true,
2144
+ readable: true
2145
+ });
2146
+
2147
+ function onfinished(err) {
2148
+ const cb = onclose;
2149
+ onclose = null;
2150
+ if (cb) {
2151
+ cb(err);
2152
+ } else if (err) {
2153
+ d.destroy(err);
2154
+ }
2155
+ }
2156
+
2157
+ // the writable half, node's d._write/d._final over head = this.
2158
+ d._write = function (chunk, encoding, callback) {
2159
+ if (src.write(chunk, encoding)) {
2160
+ callback();
2161
+ } else {
2162
+ ondrain = callback;
2163
+ }
2164
+ };
2165
+ d._final = function (callback) {
2166
+ src.end();
2167
+ onfinish = callback;
2168
+ };
2169
+ src.on('drain', () => {
2170
+ if (ondrain) {
2171
+ const cb = ondrain;
2172
+ ondrain = null;
2173
+ cb();
2174
+ }
2175
+ });
2176
+
2177
+ // node's pipeline([head, tail], onfinished): the chain is this pipe, and
2178
+ // any chain error reaches onfinished the way the pipeline callback takes
2179
+ // it (the pipe's own dest-side teardown is already node's behaviour).
2180
+ src.pipe(tail);
2181
+ src.on('error', onfinished);
2182
+ tail.on('error', onfinished);
2183
+
2184
+ // node's eos(toRead, cb) that releases d._final's callback.
2185
+ finished(tail, () => {
2186
+ if (onfinish) {
2187
+ const cb = onfinish;
2188
+ onfinish = null;
2189
+ cb();
2190
+ }
2191
+ });
2192
+
2193
+ // the readable half, node's tail 'data'/'end' push.
2194
+ d._read = function () {
2195
+ tail.resume();
2196
+ };
2197
+ tail.on('data', (chunk) => {
2198
+ if (!d.push(chunk)) {
2199
+ tail.pause();
2200
+ }
2201
+ });
2202
+ tail.on('end', () => {
2203
+ d.push(null);
2204
+ });
2205
+
2206
+ d._destroy = function (err, callback) {
2207
+ if (!err && onclose !== null) {
2208
+ err = abortError();
2209
+ }
2210
+ ondrain = null;
2211
+ onfinish = null;
2212
+ destroyStream(tail, err);
2213
+ if (onclose === null) {
2214
+ callback(err);
2215
+ } else {
2216
+ onclose = callback;
2217
+ }
2218
+ };
2219
+
2220
+ if (options && options.signal) {
2221
+ addAbortSignal(options.signal, d);
2222
+ }
2223
+ return d;
2224
+ }
2225
+
2226
+ // node's legacy Readable.prototype.wrap (readable.js:1503) -- the "ugly
2227
+ // unfortunate mess of history" that turns any event source into readable
2228
+ // data on this stream. It is honest machinery here because push() is node's
2229
+ // (task 39) and the pull-side resume hook fires where node's maybeReadMore
2230
+ // would call _read.
2231
+ wrap(stream) {
2232
+ let paused = false;
2233
+ stream.on('data', (chunk) => {
2234
+ if (!this.push(chunk) && stream.pause) {
2235
+ paused = true;
2236
+ stream.pause();
2237
+ }
2238
+ });
2239
+ stream.on('end', () => {
2240
+ this.push(null);
2241
+ });
2242
+ stream.on('error', (err) => {
2243
+ if (!this.destroyed) {
2244
+ this.destroy(err);
2245
+ }
2246
+ });
2247
+ stream.on('close', () => {
2248
+ if (!this.destroyed) {
2249
+ this.destroy();
2250
+ }
2251
+ });
2252
+ stream.on('destroy', () => {
2253
+ if (!this.destroyed) {
2254
+ this.destroy();
2255
+ }
2256
+ });
2257
+ this._read = () => {
2258
+ if (paused && stream.resume) {
2259
+ paused = false;
2260
+ stream.resume();
2261
+ }
2262
+ };
2263
+ const streamKeys = Object.keys(stream);
2264
+ for (let j = 0; j < streamKeys.length; j++) {
2265
+ const i = streamKeys[j];
2266
+ if (this[i] === undefined && typeof stream[i] === 'function') {
2267
+ this[i] = stream[i].bind(stream);
2268
+ }
2269
+ }
2270
+ return this;
2271
+ }
2272
+
2273
+ // The pull model's arrival event: node's readable-mode consumer is woken by
2274
+ // 'readable', never by the bytes themselves. Coalescing is node's
2275
+ // needReadable/emitReadable pair — one event per un-observed stretch, so two
2276
+ // DATA frames in one read batch produce one event (measured: readablePasses 2
2277
+ // for three reads over one arrival).
2278
+ _scheduleReadable() {
2279
+ if (this._readableScheduled === true || this.listenerCount('readable') === 0) {
2280
+ return;
2281
+ }
2282
+ this._readableScheduled = true;
2283
+ process.nextTick(() => {
2284
+ this._readableScheduled = false;
2285
+ if (this._destroyed || this._flowing === true ||
2286
+ this.listenerCount('readable') === 0) {
2287
+ return;
2288
+ }
2289
+ // nothing to report if the queue drained between the schedule and the tick
2290
+ // (node's read() clears needReadable the same way)
2291
+ if (this._pending === null && !this._endPending && this._eofSeen !== true) {
2292
+ return;
2293
+ }
2294
+ this.emit('readable');
2295
+ });
2296
+ }
2297
+
2298
+ // The end-of-stream schedule — node's endReadable: the 'end' never overtakes
2299
+ // buffered octets, and one schedule is enough (the kEndScheduled bit).
2300
+ _scheduleEOF() {
2301
+ if (this._eofEmitted === true || this._eofScheduled === true) {
2302
+ return;
2303
+ }
2304
+ this._eofScheduled = true;
2305
+ process.nextTick(() => {
2306
+ this._eofScheduled = false;
2307
+ if (this._destroyed || this._eofEmitted === true) {
2308
+ return;
2309
+ }
2310
+ if (this._pending !== null && this._pending.length > 0) {
2311
+ // a push landed between the trigger and the tick: the EOF is owed to the
2312
+ // drain again (node's endReadableNT re-checks state.length === 0 and
2313
+ // simply skips the emission here)
2314
+ this._endPending = true;
2315
+ return;
2316
+ }
2317
+ this._endPending = false;
2318
+ emitEndNT(this);
2319
+ });
2320
+ }
2321
+
2322
+ // node maps a per-stream timeout onto the connection's idle timeout.
2323
+ setTimeout(ms, cb) {
2324
+ this.session.setTimeout(ms, cb);
2325
+ return this;
2326
+ }
2327
+
2328
+ // --- internals used by the session ------------------------------------------
2329
+ // Both halves have to converge: a handler that answers synchronously inside
2330
+ // the 'stream' emit closes the local side BEFORE the peer's END_STREAM is
2331
+ // reported, and vice versa. Whichever call sees both halves closed is the one
2332
+ // that removes the stream from the session -- without it every request leaks
2333
+ // an Http2Stream (and _liveStreams never falls, so close() never finishes).
2334
+ _remoteEnded() {
2335
+ if (this._state.remoteClose === 1) {
2336
+ return;
2337
+ }
2338
+ // The other half of the content-length promise: too many octets is caught as they arrive
2339
+ // (session _onDataFrame, a connection error), too few can only be seen here, where the
2340
+ // message ends. Measured on node (h2spec http2/8.1.2.6): RST_STREAM(PROTOCOL_ERROR) and the
2341
+ // application is told ERR_HTTP2_STREAM_ERROR -- the short body is one request's failure, not
2342
+ // the session's, which is the same split nghttp2 makes and the reason the two directions of
2343
+ // the same lie get two different codes.
2344
+ if (this._expLen >= 0 && this._bodyLen < this._expLen) {
2345
+ this.session._streamError(this, PROTOCOL_ERROR, `content-length ${this._expLen} with only ` +
2346
+ `${this._bodyLen} octets received`);
2347
+ return;
2348
+ }
2349
+ this._state.remoteClose = 1;
2350
+ this.endAfterHeaders = true;
2351
+ // node's onEofChunk runs when the END_STREAM is processed, and with a
2352
+ // decoder set it flushes the split sequence held there into the queue
2353
+ // BEFORE any of the end machinery below -- the tail octets are owed to the
2354
+ // reader that arrives later, exactly like the bytes before them.
2355
+ this._flushDecoder();
2356
+ // the readable side is done: 'end' after the last 'data', like a Readable.
2357
+ // No auto-destroy: the application still has to answer. node keeps the
2358
+ // writable side of an unanswered request open as well.
2359
+ if (this._state.localClose === 1 && !this._waitForTrailers) {
2360
+ // The local half is only *finished* once END_STREAM left on the wire. A stream that
2361
+ // still owes a trailer block owes that END_STREAM too -- the body DATA was framed
2362
+ // without it (sendTrailers() puts the close on the trailer block, or on an empty DATA
2363
+ // when the block has no fields) -- so closing here would leave the response
2364
+ // unanswered for the peer and drop the owed frame. node's rule is the same and lives
2365
+ // in the writable shutdown, not in the read path: a stream with
2366
+ // STREAM_FLAGS_HAS_TRAILERS set is not shut down early
2367
+ // (internal/http2/core.js, `Trailers are pending, so the writable side cannot be
2368
+ // shut down early`). Measured: a compat response that ends with no body against an
2369
+ // unread request put HEADERS then a zero-length DATA/END_STREAM on node's wire, with
2370
+ // the stream close after both; ending here sent the HEADERS only and the client
2371
+ // waited for an answer that never came.
2372
+ this._closeNow();
2373
+ process.nextTick(emitEndCloseNT, this);
2374
+ return;
2375
+ }
2376
+ if (this._state.state === ST_OPEN) {
2377
+ this._state.state = ST_HALF_CLOSED_REMOTE;
2378
+ }
2379
+ if (!this._isConsuming()) {
2380
+ // Nothing has read the buffered bytes yet, so 'end' must not overtake them:
2381
+ // a reader that attaches later is owed the whole sequence, EOF included.
2382
+ this._endPending = true;
2383
+ // node's onEofChunk, measured stack (emitReadable_ <- onEofChunk <- the
2384
+ // stream_base read callback at END_STREAM): the EOF push emits 'readable'
2385
+ // SYNCHRONOUSLY inside the frame batch, not on a tick — the merge arm sees
2386
+ // the second 'readable' fire in the ES callback itself while the arrival
2387
+ // tick still runs its own. With no pull listener the sync emit is the
2388
+ // no-op node's listener-less emit performs, and the parked EOF waits for
2389
+ // the reader exactly as before.
2390
+ if (this.listenerCount('readable') > 0) {
2391
+ this.emit('readable');
2392
+ }
2393
+ return;
2394
+ }
2395
+ process.nextTick(emitEndNT, this);
2396
+ }
2397
+
2398
+ // The writable-side 'finish' -- node's Writable fires it once every write has been
2399
+ // accepted by the stream machinery and the writable half has ended; a destroy in
2400
+ // the same turn as the end() cancels it (upstream's test-http2-respond-with-fd-finish.js
2401
+ // pins both shapes: finish, then close with writableFinished true on a clean send;
2402
+ // close with writableFinished false and no 'finish' on an abort). The tick is also
2403
+ // what keeps the event behind 'wantTrailers' -- measured on v26.12.1, 'finish'
2404
+ // precedes 'wantTrailers' on the trailers shape. A body still queued on window
2405
+ // credit re-runs _endLocalSide when the queue drains (session._release), which is
2406
+ // where the second scheduling comes from.
2407
+ _scheduleFinish() {
2408
+ if (this._writableFinished || this._finishQueued) {
2409
+ return;
2410
+ }
2411
+ this._finishQueued = true;
2412
+ process.nextTick(finishNT, this);
2413
+ }
2414
+
2415
+ _endLocalSide() {
2416
+ const first = this._state.localClose !== 1;
2417
+ this._state.localClose = 1;
2418
+ this._endQueued = false;
2419
+ if (this._blockRefused) {
2420
+ // The half-close is the application's, and node records it whether or not the
2421
+ // octets went out (`_writableState.ending` is what decides 'aborted'). The close
2422
+ // machinery below must not run: it would finish the stream with NO_ERROR here,
2423
+ // synchronously, ahead of the deferred FRAME_SIZE_ERROR close node's onFrameError
2424
+ // schedules -- measured, node reports rstCode 6 for this shape and h2lean reported 0.
2425
+ return;
2426
+ }
2427
+ if (this._queued === null) {
2428
+ // every octet handed over has been accepted by the session: node's condition
2429
+ // for the writable 'finish'
2430
+ this._scheduleFinish();
2431
+ }
2432
+ if (this._state.state === ST_OPEN) {
2433
+ this._state.state = ST_HALF_CLOSED_LOCAL;
2434
+ }
2435
+ if (this._waitForTrailers) {
2436
+ // one shot: a later end() must not ask for trailers a second time. The flag
2437
+ // itself stays set, because sendTrailers() is only allowed while it is set.
2438
+ if (first) {
2439
+ process.nextTick(wantTrailersNT, this);
2440
+ }
2441
+ return;
2442
+ }
2443
+ if (this._state.remoteClose === 1) {
2444
+ this._closeIfBothDone();
2445
+ } else {
2446
+ // the response is over and the peer's half is not: this is the shape node
2447
+ // closes for the application (see _maybeAutoClose). A stream the peer has
2448
+ // already ended takes the graceful close above, which is also what node's
2449
+ // wire shows there -- no RST, because nghttp2 refuses to reset what both
2450
+ // halves have closed (tools/probe-stream-teardown.js, 'request-ended').
2451
+ this._maybeAutoClose();
2452
+ }
2453
+ }
2454
+
2455
+ // node's Http2Stream[kMaybeDestroy] (internal/http2/core.js): a response the
2456
+ // server session has finished, with trailers neither requested nor sent
2457
+ // (STREAM_FLAGS_HAS_TRAILERS) and a request side nobody ever started to consume
2458
+ // (`!state.didRead && readableFlowing === null`), is closed by the session
2459
+ // itself -- `setImmediate(callStreamClose)` off the writable side's 'finish',
2460
+ // and closeStream submits RST_STREAM(NO_ERROR). Measured on v26.12.1
2461
+ // (tools/probe-stream-teardown.js, 'answer-only'): HEADERS, DATA, then
2462
+ // RST_STREAM(NO_ERROR) on the wire and the stream destroyed -- and the
2463
+ // boundaries with it: 'resume-then-answer' shows that touching the readable
2464
+ // side stops the auto-close, and 'request-ended' that a stream the peer already
2465
+ // ended never gets one. Without it a peer that sends HEADERS without END_STREAM
2466
+ // and no DATA holds a stream and a _liveStreams slot until the idle timeout,
2467
+ // and a closing session waits for it forever (AGENTS.md 10, item 2).
2468
+ // `_consumeState === 0` is this file's reading of `!didRead && flowing ===
2469
+ // null`: no reader attached and no pause()/resume() called -- either has
2470
+ // touched the request, and node stops there too.
2471
+ _maybeAutoClose() {
2472
+ if (this._destroyed || !this.headersSent || this._waitForTrailers ||
2473
+ this._consumeState !== 0 || this._flowing === false ||
2474
+ this._dataRead === true) {
1309
2475
  return;
1310
2476
  }
1311
2477
  // node's own deferral: the RST goes out a turn after the response, and the
@@ -1326,7 +2492,7 @@ class Http2Stream extends Stream {
1326
2492
  // in _endPending for a reader that never appeared, and the local close below was the last
1327
2493
  // event the stream ever produced. Measured against node on exactly that shape: it emits
1328
2494
  // stream.end then stream.close (test/event-order.test.js, scenario eof).
1329
- if (this._endPending) {
2495
+ if (this._endPending || this._eofSeen === true) {
1330
2496
  this._endPending = false;
1331
2497
  process.nextTick(emitEndCloseNT, this);
1332
2498
  return;
@@ -1354,6 +2520,17 @@ class Http2Stream extends Stream {
1354
2520
  return;
1355
2521
  }
1356
2522
  this._destroyed = true;
2523
+ // node's destroy does not touch state.flowing — the readableFlowing getter keeps
2524
+ // reporting the last resume()/pause()/listener verdict even after the destroy
2525
+ // (measured: snapError inside the 'error' handler reads flowing true post-resume),
2526
+ // and every consumer here gates on _destroyed first.
2527
+ // node's destroy() runs checkError BEFORE the destroyed bit and before the
2528
+ // nextTick that emits: state.errored is already set in the same turn the
2529
+ // destroy happens (destroy.js checkError), so a getter read right after
2530
+ // destroy(err) sees it — the deferred emitErrorCloseNT only carries the event.
2531
+ if (err) {
2532
+ this._streamErrored = err;
2533
+ }
1357
2534
  this.rstCode = code;
1358
2535
  // node's rule for 'aborted' is about the WRITABLE side: "if the writable side of
1359
2536
  // the Http2Stream is still open, emit the 'aborted' event" -- closeStream's
@@ -1386,6 +2563,24 @@ class Http2Stream extends Stream {
1386
2563
  this.session = undefined;
1387
2564
  if (err) {
1388
2565
  process.nextTick(emitErrorCloseNT, this, err);
2566
+ } else if (this._isConsuming() &&
2567
+ (this._endPending || code === NO_ERROR || code === frames.CANCEL)) {
2568
+ // node's _destroy (internal/http2/core.js:2527) calls `this.push(null)`
2569
+ // unconditionally, but the EOF it pushes only reaches the readable when the
2570
+ // destroy was not an error: core.js:2541 turns every other code into
2571
+ // ERR_HTTP2_STREAM_ERROR first, and an errored destroy reports error+close
2572
+ // with no 'end' at all (measured on the over-long content-length refusal:
2573
+ // aborted, error, close). So the owed EOF goes out for exactly the codes
2574
+ // streamErrorOf does not name -- a plain destroy() and an abort (CANCEL) --
2575
+ // plus the parked-END_STREAM case this branch has always replayed. Measured
2576
+ // shapes: respond + close(8), request ended on its HEADERS -- aborted, end,
2577
+ // close; and a stream destroyed mid-pipe with no END_STREAM ever sent --
2578
+ // again aborted, end, close, which is what ends and unpipes the dest
2579
+ // (test/pipe-parity.test.js). Without it the deferred resume of an attached
2580
+ // reader is cancelled by the destroy bit and the owed 'end' never goes out
2581
+ // (test/event-order.test.js, scenario reset).
2582
+ this._endPending = false;
2583
+ process.nextTick(emitEndCloseNT, this);
1389
2584
  } else {
1390
2585
  process.nextTick(emitNT, this, 'close');
1391
2586
  }
@@ -1417,36 +2612,78 @@ class Http2Stream extends Stream {
1417
2612
  }
1418
2613
 
1419
2614
  // --- 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.
2615
+ // Attaching a reader is how the application says "send me the body": whatever
2616
+ // arrived before it did is replayed -- on the next tick, like node's
2617
+ // kResumeScheduled resume_, not inside the on() call (measured: a read() in the
2618
+ // same turn as the attach still sees the buffer). once()/addListener are
2619
+ // covered by the listenerCount() check at delivery time.
1424
2620
  on(name, fn) {
2621
+ const firstReader = (name === 'data' || name === 'readable') &&
2622
+ this.listenerCount(name) === 0;
1425
2623
  const r = super.on(name, fn);
1426
- if (name === 'data' || name === 'readable') {
1427
- this._startConsuming();
2624
+ if (name === 'data') {
2625
+ if (firstReader) {
2626
+ this._readerFlow(name);
2627
+ }
2628
+ this._scheduleResume();
2629
+ } else if (name === 'readable') {
2630
+ if (firstReader) {
2631
+ this._readerFlow(name);
2632
+ }
2633
+ this._scheduleReadable();
1428
2634
  }
1429
2635
  return r;
1430
2636
  }
1431
2637
 
1432
2638
  once(name, fn) {
2639
+ const firstReader = (name === 'data' || name === 'readable') &&
2640
+ this.listenerCount(name) === 0;
1433
2641
  const r = super.once(name, fn);
1434
- if (name === 'data' || name === 'readable') {
1435
- this._startConsuming();
2642
+ if (name === 'data') {
2643
+ if (firstReader) {
2644
+ this._readerFlow(name);
2645
+ }
2646
+ this._scheduleResume();
2647
+ } else if (name === 'readable') {
2648
+ if (firstReader) {
2649
+ this._readerFlow(name);
2650
+ }
2651
+ this._scheduleReadable();
1436
2652
  }
1437
2653
  return r;
1438
2654
  }
1439
2655
 
2656
+ // node's Readable.prototype.on: attaching 'data' resumes, unless the stream was
2657
+ // explicitly paused; attaching 'readable' takes the stream out of flowing mode
2658
+ // even after resume() (measured: resume() then on('readable') reads false).
2659
+ // Both rules show up on the readableFlowing getter only — the replay that
2660
+ // actually moves the bytes stayed where it was.
2661
+ _readerFlow(name) {
2662
+ if (name === 'data') {
2663
+ if (this._flowing !== false) {
2664
+ this._flowing = true;
2665
+ }
2666
+ } else if (this._eofEmitted !== true) {
2667
+ this._flowing = false;
2668
+ }
2669
+ }
2670
+
1440
2671
  // Credit goes back when the application takes the bytes, so a body nobody
1441
2672
  // reads closes the sender's window instead of growing our heap. The buffer of
1442
2673
  // unread chunks cannot exceed the window we advertised, because the peer is
1443
2674
  // not allowed to send more than that without a credit we never gave.
2675
+ // A 'readable' listener is NOT consuming: the pull model buffers and waits
2676
+ // for read(), which is where that credit comes back (node's readable mode
2677
+ // releases nothing until the app pulls). A 'data' listener is not consuming
2678
+ // either while the stream sits in pull or paused mode (_flowing === false) --
2679
+ // node's kHasFlowing rule measured in the merge arm: the chunks stay in the
2680
+ // buffer for read() and only read()'s own data emission delivers them.
1444
2681
  _isConsuming() {
1445
2682
  if (this._consumeState === 2) {
1446
2683
  return false;
1447
2684
  } // the reader asked us to stop
1448
- return this._consumeState === 1 || this.listenerCount('data') > 0 ||
1449
- this.listenerCount('readable') > 0;
2685
+ return this._consumeState === 1 ||
2686
+ (this._flowing !== false && this.listenerCount('data') > 0);
1450
2687
  }
1451
2688
 
1452
2689
  // Called when a reader shows up: replay what was buffered, in order, and let
@@ -1457,14 +2694,25 @@ class Http2Stream extends Stream {
1457
2694
  if (pending !== null) {
1458
2695
  this._pending = null;
1459
2696
  for (let i = 0; i < pending.length; i++) {
1460
- const chunk = pending[i];
1461
- this._release(chunk.length);
1462
- this.emit('data', chunk);
2697
+ const c = pending[i];
2698
+ this._dataRead = true;
2699
+ if (c.length === undefined) {
2700
+ // a pushed or decoded chunk: delivered, and it owes no credit for
2701
+ // itself -- but a string entry that stands for wire octets carries
2702
+ // their count and pays it here
2703
+ if (c.bytes !== undefined) {
2704
+ this._release(c.bytes);
2705
+ }
2706
+ this.emit('data', c.data);
2707
+ } else {
2708
+ this._release(c.length);
2709
+ this.emit('data', c);
2710
+ }
1463
2711
  }
1464
2712
  }
1465
- if (this._endPending && !this._destroyed) {
2713
+ if ((this._endPending || this._eofSeen === true) && !this._destroyed) {
1466
2714
  this._endPending = false;
1467
- process.nextTick(emitNT, this, 'end');
2715
+ this._scheduleEOF();
1468
2716
  }
1469
2717
  }
1470
2718
 
@@ -1486,17 +2734,53 @@ class Http2Stream extends Stream {
1486
2734
  return;
1487
2735
  } // an empty DATA frame carries no payload
1488
2736
  this._recvUsed += n;
1489
- if (this._isConsuming()) {
2737
+ if (this._decoder !== undefined) {
2738
+ // arrival decodes at the door, node's push path with a decoder set: the
2739
+ // queue holds characters from here on. A chunk the decoder swallowed
2740
+ // whole (split multi-byte sequence) produces no entry and no event --
2741
+ // node's `chunk.length === 0` return -- and its octets are held against
2742
+ // the credit of the entry that finally comes out.
2743
+ let held = 0;
2744
+ if (this._decHeld !== undefined) {
2745
+ held = this._decHeld;
2746
+ this._decHeld = undefined;
2747
+ }
2748
+ const str = this._decoder.write(buf);
2749
+ if (str.length === 0) {
2750
+ this._decHeld = n + held;
2751
+ return;
2752
+ }
2753
+ if (this._isConsuming() && this._pending === null) {
2754
+ this._dataRead = true;
2755
+ this._release(n + held);
2756
+ this.emit('data', str);
2757
+ return;
2758
+ }
2759
+ if (this._pending === null) {
2760
+ this._pending = [];
2761
+ }
2762
+ this._pending.push({ data: str, bytes: n + held });
2763
+ this._scheduleReadable();
2764
+ return;
2765
+ }
2766
+ if (this._isConsuming() && this._pending === null) {
2767
+ this._dataRead = true;
1490
2768
  this._release(n);
1491
2769
  this.emit('data', buf);
1492
2770
  return;
1493
2771
  }
1494
2772
  // 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
2773
+ // alone; both outlive the tick, so it can simply be queued. A consuming reader
2774
+ // with a queue still standing lands here too: resume()'s delivery is scheduled,
2775
+ // not synchronous (node's resume_ tick), and arriving bytes must not overtake
2776
+ // the buffered ones.
1496
2777
  if (this._pending === null) {
1497
2778
  this._pending = [];
1498
2779
  }
1499
2780
  this._pending.push(buf);
2781
+ // readable-mode arrival: the pull consumer learns about it through
2782
+ // 'readable', not through the bytes (node's needReadable/emitReadable).
2783
+ this._scheduleReadable();
1500
2784
  }
1501
2785
  }
1502
2786
 
@@ -1514,6 +2798,626 @@ function errorOf(code, msg) {
1514
2798
  return err;
1515
2799
  }
1516
2800
 
2801
+ // --- the async-iteration machinery ----------------------------------------------
2802
+ // Everything below reproduces node's internal/streams/readable.js:1552-1805
2803
+ // (streamToAsyncIterator/createAsyncIterator) and internal/streams/operators,
2804
+ // read from the binary in the same session as the measurements cited at the
2805
+ // methods. Two simplifications are honest, not inventions: (a) the iterator
2806
+ // never meets a thenable chunk -- push() validates its argument, so the queue
2807
+ // holds only Buffer/string/null and node's `chunk?.then` unwrapping and the
2808
+ // two-error AggregateError race it guards cannot occur (measured: an errored
2809
+ // iteration rejects with the bare error); (b) the FixedQueue node parks
2810
+ // queued requests in is an array here -- queue depth is a behaviour of the
2811
+ // consumer, not of the protocol.
2812
+
2813
+ const kEmpty = Symbol('kEmpty');
2814
+ const kEof = Symbol('kEof');
2815
+ // %AsyncIteratorPrototype% in V8: the function's .prototype is an INSTANCE of
2816
+ // the (shared) async-generator prototype, so the intrinsic with
2817
+ // [Symbol.asyncIterator]/[Symbol.asyncDispose] and no own methods sits TWO
2818
+ // levels up. Verified identity with the proto of a live node v26 iterator
2819
+ // object; the single getPrototypeOf lands on the generator prototype instead.
2820
+ // Node's own iterator is NOT this shape on every major: 22 and 24 hand back a
2821
+ // real async-generator instance, whose proto has no own keys at all. The
2822
+ // intrinsic is the only anchor stable across majors, and the behaviour that
2823
+ // depends on it ([Symbol.asyncIterator] resolving through the chain,
2824
+ // self-identical) is verified per major; exact proto identity is unportable.
2825
+ const ASYNC_ITERATOR_PROTO =
2826
+ Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}.prototype));
2827
+
2828
+ function noop() {}
2829
+
2830
+ // node's internal AbortError as the stream machinery constructs it (measured
2831
+ // on a live node break: name 'AbortError', code 'ABORT_ERR'). core.js:2516
2832
+ // maps it onto RST CANCEL(8) inside _destroy.
2833
+ function abortError(cause) {
2834
+ const err = new Error('The operation was aborted',
2835
+ cause === undefined ? undefined : { cause });
2836
+ err.name = 'AbortError';
2837
+ err.code = 'ABORT_ERR';
2838
+ return err;
2839
+ }
2840
+
2841
+ function validateObjectArg(value, name) {
2842
+ if (value === null || typeof value !== 'object') {
2843
+ throw errorOf('ERR_INVALID_ARG_TYPE',
2844
+ `The "${name}" argument must be of type object. Received ${inspect(value)}`);
2845
+ }
2846
+ }
2847
+
2848
+ function validateFunctionArg(value, name) {
2849
+ if (typeof value !== 'function') {
2850
+ throw errorOf('ERR_INVALID_ARG_TYPE',
2851
+ `The "${name}" argument must be of type function. Received ${inspect(value)}`);
2852
+ }
2853
+ }
2854
+
2855
+ // node's pair in every operator: validateObject(options) then
2856
+ // validateAbortSignal(options.signal).
2857
+ function validateSignalArg(options) {
2858
+ if (options != null && options.signal != null && !(options.signal instanceof AbortSignal)) {
2859
+ throw errorOf('ERR_INVALID_ARG_TYPE',
2860
+ 'The "options.signal" argument must be an instance of type AbortSignal.');
2861
+ }
2862
+ }
2863
+
2864
+ function validateOperatorOptions(options) {
2865
+ if (options != null) {
2866
+ validateObjectArg(options, 'options');
2867
+ }
2868
+ validateSignalArg(options);
2869
+ }
2870
+
2871
+ // node's toIntegerOrInfinity (operators:298): Number coercion per the
2872
+ // iterator-helpers proposal, then the range refusal.
2873
+ function toIntegerOrInfinity(number) {
2874
+ number = Number(number);
2875
+ if (Number.isNaN(number)) {
2876
+ return 0;
2877
+ }
2878
+ if (number < 0) {
2879
+ throw errorOf('ERR_OUT_OF_RANGE',
2880
+ `The value of "number" is out of range. It must be >= 0. Received ${number}`);
2881
+ }
2882
+ return number;
2883
+ }
2884
+
2885
+ // node's createAsyncIterator (readable.js:1576). The request protocol -- next
2886
+ // fast path, queue behind an inFlight request, return/throw draining through
2887
+ // the same pump -- is reproduced member by member; the wake is h2lean's
2888
+ // 'readable' event (node's emitReadable, same coalescing) and the end verdict
2889
+ // comes from the error/end/close trio standing in for
2890
+ // eos(stream, { writable: false }).
2891
+ function createStreamIterator(stream, options) {
2892
+ let callback = noop;
2893
+ let error; // undefined: active, null: ended cleanly, else: the Error
2894
+ let started = false;
2895
+ let completed = false;
2896
+ let inFlight = false; // an asynchronous request is outstanding
2897
+ let queue = null; // requests received while inFlight
2898
+ let draining = false;
2899
+ let detach = noop;
2900
+
2901
+ function fire() {
2902
+ const cb = callback;
2903
+ callback = noop;
2904
+ cb();
2905
+ }
2906
+
2907
+ function wait() {
2908
+ return new Promise((resolve) => {
2909
+ callback = resolve;
2910
+ });
2911
+ }
2912
+
2913
+ function start() {
2914
+ started = true;
2915
+ stream.on('readable', fire);
2916
+ let settled = false;
2917
+ const settle = (err) => {
2918
+ if (settled) {
2919
+ return;
2920
+ }
2921
+ settled = true;
2922
+ detach();
2923
+ error = err;
2924
+ fire();
2925
+ };
2926
+ const onEnd = () => {
2927
+ settle(null);
2928
+ };
2929
+ // a close with neither end nor error is node's eos verdict
2930
+ // ERR_STREAM_PREMATURE_CLOSE ('Premature close', read out of
2931
+ // internal/errors with --expose-internals).
2932
+ const onClose = () => {
2933
+ settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'));
2934
+ };
2935
+ stream.on('error', settle);
2936
+ stream.on('end', onEnd);
2937
+ stream.on('close', onClose);
2938
+ detach = () => {
2939
+ stream.removeListener('readable', fire);
2940
+ stream.removeListener('error', settle);
2941
+ stream.removeListener('end', onEnd);
2942
+ stream.removeListener('close', onClose);
2943
+ };
2944
+ // node's start() hooks eos, not raw 'end'/'close', and an eos on a
2945
+ // stream that has ALREADY settled calls back on the next tick: a second
2946
+ // iterator over an ended stream gets `{done:true}` (measured on live
2947
+ // node: every() after some() on the same stream answers true without
2948
+ // hanging), and over a destroyed one gets the premature-close error.
2949
+ // The one-shot trio below can never fire again, so this is where that
2950
+ // verdict is reproduced.
2951
+ if (stream.readableEnded === true) {
2952
+ process.nextTick(() => settle(null));
2953
+ } else if (stream.destroyed === true) {
2954
+ process.nextTick(() => settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close')));
2955
+ }
2956
+ }
2957
+
2958
+ function finalize() {
2959
+ completed = true;
2960
+ // node's finalize (readable.js:1609) reads autoDestroy off the state
2961
+ // object; Http2Stream fixes it false (core.js:2132), so the second
2962
+ // clause reduces to `error === undefined`: only a still-active
2963
+ // return()/break destroys -- node's destroyer(stream, null) on a
2964
+ // not-finished stream is destroy(new AbortError()), which core.js:2516
2965
+ // turns into RST CANCEL. h2lean's public destroy() derives
2966
+ // INTERNAL_ERROR from any Error object (its own documented rule, task
2967
+ // 17), so the iterator calls the engine with node's derived pair
2968
+ // directly. Measured: break -- destroyed true, rstCode 8, aborted,
2969
+ // error:ABORT_ERR, close; natural end -- destroyed stays false.
2970
+ if ((error || options?.destroyOnReturn !== false) && error === undefined) {
2971
+ if (!stream.destroyed) {
2972
+ stream._destroy(frames.CANCEL, undefined, true, abortError());
2973
+ }
2974
+ } else {
2975
+ stream.removeListener('readable', fire);
2976
+ detach();
2977
+ }
2978
+ }
2979
+
2980
+ function drain() {
2981
+ // node's guard: requests settled synchronously call back into drain(),
2982
+ // and one loop runs instead of one recursion per request.
2983
+ if (draining) {
2984
+ return;
2985
+ }
2986
+ draining = true;
2987
+ try {
2988
+ while (!inFlight && queue !== null && queue.length > 0) {
2989
+ const req = queue.shift();
2990
+ if (req.type === 'next') {
2991
+ processNext(req.resolve, req.reject);
2992
+ } else if (req.type === 'return') {
2993
+ processReturn(req.value, req.resolve);
2994
+ } else {
2995
+ processThrow(req.value, req.reject);
2996
+ }
2997
+ }
2998
+ } finally {
2999
+ draining = false;
3000
+ }
3001
+ }
3002
+
3003
+ function pump(resolve, reject) {
3004
+ const chunk = stream.destroyed ? null : stream.read();
3005
+ if (chunk !== null) {
3006
+ inFlight = false;
3007
+ resolve({ done: false, value: chunk });
3008
+ if (queue !== null) {
3009
+ drain();
3010
+ }
3011
+ } else if (error) {
3012
+ inFlight = false;
3013
+ finalize();
3014
+ reject(error);
3015
+ if (queue !== null) {
3016
+ drain();
3017
+ }
3018
+ } else if (error === null) {
3019
+ inFlight = false;
3020
+ finalize();
3021
+ resolve({ done: true, value: undefined });
3022
+ if (queue !== null) {
3023
+ drain();
3024
+ }
3025
+ } else {
3026
+ // nothing buffered yet: wait for the next 'readable' or end verdict
3027
+ // and retry, node's wakeup-promise tail.
3028
+ wait().then(() => pump(resolve, reject));
3029
+ }
3030
+ }
3031
+
3032
+ function processNext(resolve, reject) {
3033
+ if (completed) {
3034
+ resolve({ done: true, value: undefined });
3035
+ return;
3036
+ }
3037
+ if (!started) {
3038
+ start();
3039
+ }
3040
+ inFlight = true;
3041
+ pump(resolve, reject);
3042
+ }
3043
+
3044
+ function processReturn(value, resolve) {
3045
+ if (!completed) {
3046
+ if (started) {
3047
+ finalize();
3048
+ } else {
3049
+ // never started: complete without touching the stream.
3050
+ completed = true;
3051
+ }
3052
+ }
3053
+ resolve({ done: true, value });
3054
+ }
3055
+
3056
+ function processThrow(err, reject) {
3057
+ if (completed || !started) {
3058
+ completed = true;
3059
+ reject(err);
3060
+ return;
3061
+ }
3062
+ error = err;
3063
+ finalize();
3064
+ reject(err);
3065
+ }
3066
+
3067
+ const iter = {
3068
+ __proto__: ASYNC_ITERATOR_PROTO,
3069
+ next() {
3070
+ if (!inFlight && !completed) {
3071
+ if (!started) {
3072
+ start();
3073
+ }
3074
+ const chunk = stream.destroyed ? null : stream.read();
3075
+ if (chunk !== null) {
3076
+ return Promise.resolve({ done: false, value: chunk });
3077
+ }
3078
+ if (error) {
3079
+ finalize();
3080
+ return Promise.reject(error);
3081
+ }
3082
+ if (error === null) {
3083
+ finalize();
3084
+ return Promise.resolve({ done: true, value: undefined });
3085
+ }
3086
+ inFlight = true;
3087
+ return new Promise((resolve, reject) => {
3088
+ wait().then(() => pump(resolve, reject));
3089
+ });
3090
+ }
3091
+ return new Promise((resolve, reject) => {
3092
+ if (inFlight) {
3093
+ (queue ??= []).push({ __proto__: null, type: 'next', value: undefined, resolve, reject });
3094
+ } else {
3095
+ resolve({ done: true, value: undefined });
3096
+ }
3097
+ });
3098
+ },
3099
+ return(value) {
3100
+ return new Promise((resolve) => {
3101
+ if (inFlight) {
3102
+ (queue ??= []).push({ __proto__: null, type: 'return', value, resolve, reject: null });
3103
+ } else {
3104
+ processReturn(value, resolve);
3105
+ }
3106
+ });
3107
+ },
3108
+ throw(err) {
3109
+ return new Promise((resolve, reject) => {
3110
+ if (inFlight) {
3111
+ (queue ??= []).push({ __proto__: null, type: 'throw', value: err, resolve, reject });
3112
+ } else {
3113
+ processThrow(err, reject);
3114
+ }
3115
+ });
3116
+ }
3117
+ };
3118
+ // node's streamToAsyncIterator hangs the source on the iterator object
3119
+ // (readable.js:1563-1565); measured raw.stream === rd on a live node.
3120
+ iter.stream = stream;
3121
+ return iter;
3122
+ }
3123
+
3124
+ // node's operators (internal/streams/operators). Each is a plain function or
3125
+ // async function mirroring the original's argument shape, so the synchronous
3126
+ // validation the transform family performs (measured: map('nope') throws
3127
+ // ERR_INVALID_ARG_TYPE out of the call) and the rejection the promise family
3128
+ // produces land exactly where node puts them.
3129
+
3130
+ function opMap(stream, fn, options) {
3131
+ validateFunctionArg(fn, 'fn');
3132
+ validateOperatorOptions(options);
3133
+ let concurrency = 1;
3134
+ if (options?.concurrency != null) {
3135
+ concurrency = Math.floor(options.concurrency);
3136
+ }
3137
+ let highWaterMark = concurrency - 1;
3138
+ if (options?.highWaterMark != null) {
3139
+ highWaterMark = Math.floor(options.highWaterMark);
3140
+ }
3141
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
3142
+ throw errorOf('ERR_OUT_OF_RANGE',
3143
+ `The value of "options.concurrency" is out of range. It must be >= 1. Received ${concurrency}`);
3144
+ }
3145
+ if (!Number.isInteger(highWaterMark) || highWaterMark < 0) {
3146
+ throw errorOf('ERR_OUT_OF_RANGE',
3147
+ `The value of "options.highWaterMark" is out of range. It must be >= 0. Received ${highWaterMark}`);
3148
+ }
3149
+ highWaterMark += concurrency;
3150
+ // node builds its always-present signal with AbortSignal.any([...]) --
3151
+ // any([]) is a fresh never-aborted signal, which a never-aborted
3152
+ // controller's signal is byte-equivalent to for everything the operator
3153
+ // reads off it.
3154
+ const signal = options?.signal ?? new AbortController().signal;
3155
+
3156
+ return (async function* map() {
3157
+ const queue = [];
3158
+ const signalOpt = { signal };
3159
+ let next = null;
3160
+ let resume = null;
3161
+ let done = false;
3162
+ let cnt = 0;
3163
+
3164
+ function onCatch() {
3165
+ done = true;
3166
+ afterItemProcessed();
3167
+ }
3168
+
3169
+ function afterItemProcessed() {
3170
+ cnt -= 1;
3171
+ maybeResume();
3172
+ }
3173
+
3174
+ function maybeResume() {
3175
+ if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {
3176
+ const r = resume;
3177
+ resume = null;
3178
+ r();
3179
+ }
3180
+ }
3181
+
3182
+ async function pump() {
3183
+ try {
3184
+ for await (let val of stream) {
3185
+ if (done) {
3186
+ return;
3187
+ }
3188
+ if (signal.aborted) {
3189
+ throw abortError();
3190
+ }
3191
+ try {
3192
+ val = fn(val, signalOpt);
3193
+ if (val === kEmpty) {
3194
+ continue;
3195
+ }
3196
+ val = Promise.resolve(val);
3197
+ } catch (err) {
3198
+ val = Promise.reject(err);
3199
+ }
3200
+ cnt += 1;
3201
+ val.then(afterItemProcessed, onCatch);
3202
+ queue.push(val);
3203
+ if (next) {
3204
+ const n = next;
3205
+ next = null;
3206
+ n();
3207
+ }
3208
+ if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {
3209
+ await new Promise((resolve) => {
3210
+ resume = resolve;
3211
+ });
3212
+ }
3213
+ }
3214
+ queue.push(kEof);
3215
+ } catch (err) {
3216
+ const val = Promise.reject(err);
3217
+ val.then(afterItemProcessed, onCatch);
3218
+ queue.push(val);
3219
+ } finally {
3220
+ done = true;
3221
+ if (next) {
3222
+ const n = next;
3223
+ next = null;
3224
+ n();
3225
+ }
3226
+ }
3227
+ }
3228
+
3229
+ pump();
3230
+
3231
+ try {
3232
+ while (true) {
3233
+ while (queue.length > 0) {
3234
+ const val = await queue[0];
3235
+ if (val === kEof) {
3236
+ return;
3237
+ }
3238
+ if (signal.aborted) {
3239
+ throw abortError();
3240
+ }
3241
+ if (val !== kEmpty) {
3242
+ yield val;
3243
+ }
3244
+ queue.shift();
3245
+ maybeResume();
3246
+ }
3247
+ await new Promise((resolve) => {
3248
+ next = resolve;
3249
+ });
3250
+ }
3251
+ } finally {
3252
+ done = true;
3253
+ if (resume) {
3254
+ const r = resume;
3255
+ resume = null;
3256
+ r();
3257
+ }
3258
+ }
3259
+ })();
3260
+ }
3261
+
3262
+ function opFilter(stream, fn, options) {
3263
+ validateFunctionArg(fn, 'fn');
3264
+ async function filterFn(value, opt) {
3265
+ if (await fn(value, opt)) {
3266
+ return value;
3267
+ }
3268
+ return kEmpty;
3269
+ }
3270
+ return opMap(stream, filterFn, options);
3271
+ }
3272
+
3273
+ async function opForEach(stream, fn, options) {
3274
+ validateFunctionArg(fn, 'fn');
3275
+ async function forEachFn(value, opt) {
3276
+ await fn(value, opt);
3277
+ return kEmpty;
3278
+ }
3279
+ // node drains the mapped generator with an empty for-await body. The same
3280
+ // descent is spelled out here -- an fn error propagates out of the mapped
3281
+ // generator's own body, so its cleanup runs at the throw point and no
3282
+ // abrupt-close return() call from this loop would add anything.
3283
+ const it = opMap(stream, forEachFn, options)[Symbol.asyncIterator]();
3284
+ let res = await it.next();
3285
+ while (!res.done) {
3286
+ res = await it.next();
3287
+ }
3288
+ }
3289
+
3290
+ function opFlatMap(stream, fn, options) {
3291
+ const values = opMap(stream, fn, options);
3292
+ return (async function* flatMap() {
3293
+ for await (const val of values) {
3294
+ yield* val;
3295
+ }
3296
+ })();
3297
+ }
3298
+
3299
+ function opDrop(stream, number, options) {
3300
+ validateOperatorOptions(options);
3301
+ const limit = toIntegerOrInfinity(number);
3302
+ return (async function* drop() {
3303
+ if (options?.signal?.aborted) {
3304
+ throw abortError();
3305
+ }
3306
+ let numberLeft = limit;
3307
+ for await (const val of stream) {
3308
+ if (options?.signal?.aborted) {
3309
+ throw abortError();
3310
+ }
3311
+ if (numberLeft-- <= 0) {
3312
+ yield val;
3313
+ }
3314
+ }
3315
+ })();
3316
+ }
3317
+
3318
+ function opTake(stream, number, options) {
3319
+ validateOperatorOptions(options);
3320
+ const limit = toIntegerOrInfinity(number);
3321
+ return (async function* take() {
3322
+ if (options?.signal?.aborted) {
3323
+ throw abortError();
3324
+ }
3325
+ let numberLeft = limit;
3326
+ for await (const val of stream) {
3327
+ if (options?.signal?.aborted) {
3328
+ throw abortError();
3329
+ }
3330
+ if (numberLeft-- > 0) {
3331
+ yield val;
3332
+ }
3333
+ // Don't get another item from iterator in case we reached the end --
3334
+ // node's comment; the return() this early exit triggers on the source
3335
+ // iterator is what destroys a stream taken short of its EOF.
3336
+ if (numberLeft <= 0) {
3337
+ return;
3338
+ }
3339
+ }
3340
+ })();
3341
+ }
3342
+
3343
+ async function opSome(stream, fn, options) {
3344
+ for await (const unused of opFilter(stream, fn, options)) {
3345
+ return true;
3346
+ }
3347
+ return false;
3348
+ }
3349
+
3350
+ async function opEvery(stream, fn, options) {
3351
+ validateFunctionArg(fn, 'fn');
3352
+ // https://en.wikipedia.org/wiki/De_Morgan%27s_laws -- node's comment.
3353
+ return !(await opSome(stream, async (...args) => !(await fn(...args)), options));
3354
+ }
3355
+
3356
+ async function opFind(stream, fn, options) {
3357
+ for await (const result of opFilter(stream, fn, options)) {
3358
+ return result;
3359
+ }
3360
+ return undefined;
3361
+ }
3362
+
3363
+ async function opReduce(stream, hasInitial, reducer, initialValue, options) {
3364
+ validateFunctionArg(reducer, 'reducer');
3365
+ validateOperatorOptions(options);
3366
+ if (options?.signal?.aborted) {
3367
+ const err = abortError(options.signal.reason);
3368
+ stream.once('error', () => {}); // the error is already propagated
3369
+ // node awaits its internal eos, which RESOLVES on the errored teardown;
3370
+ // the callback form wrapped here is that promise, since the public
3371
+ // callback-less `finished` refuses instead.
3372
+ await new Promise((resolve) => {
3373
+ // h2lean's destroy() returns nothing, unlike node's, so the stream is
3374
+ // handed to eos on its own line.
3375
+ stream.destroy(err);
3376
+ finished(stream, resolve);
3377
+ });
3378
+ throw err;
3379
+ }
3380
+ const ac = new AbortController();
3381
+ const signal = ac.signal;
3382
+ if (options?.signal) {
3383
+ options.signal.addEventListener('abort', () => ac.abort(), { once: true });
3384
+ }
3385
+ let gotAnyItemFromStream = false;
3386
+ try {
3387
+ for await (const value of stream) {
3388
+ gotAnyItemFromStream = true;
3389
+ if (options?.signal?.aborted) {
3390
+ throw abortError();
3391
+ }
3392
+ if (!hasInitial) {
3393
+ initialValue = value;
3394
+ hasInitial = true;
3395
+ } else {
3396
+ initialValue = await reducer(initialValue, value, { signal });
3397
+ }
3398
+ }
3399
+ if (!gotAnyItemFromStream && !hasInitial) {
3400
+ // node's ReduceAwareErrMissingArgs: same code, same custom message.
3401
+ throw errorOf('ERR_MISSING_ARGS', 'Reduce of an empty stream requires an initial value');
3402
+ }
3403
+ } finally {
3404
+ ac.abort();
3405
+ }
3406
+ return initialValue;
3407
+ }
3408
+
3409
+ async function opToArray(stream, options) {
3410
+ validateOperatorOptions(options);
3411
+ const result = [];
3412
+ for await (const val of stream) {
3413
+ if (options?.signal?.aborted) {
3414
+ throw abortError(options.signal.reason);
3415
+ }
3416
+ result.push(val);
3417
+ }
3418
+ return result;
3419
+ }
3420
+
1517
3421
  // The error a stream reports when an RST_STREAM ends it, on either side. node's rule is
1518
3422
  // one line (internal/http2/core.js:2543): `if (err == null && code !== NGHTTP2_NO_ERROR &&
1519
3423
  // code !== NGHTTP2_CANCEL) err = new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code)`.