import { addAbortSignalNoValidate } from "./add-abort-signal.mjs";import { Buffer } from "../../buffer.ts";import { debuglog } from "../util/debuglog.ts";import { getDefaultHighWaterMark, getHighWaterMark } from "./state.mjs";import { prependListener, Stream } from "./legacy.mjs";import { StringDecoder } from "../../string_decoder.ts";import { validateObject } from "../validators.mjs";import { ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED, ERR_STREAM_PUSH_AFTER_EOF, ERR_STREAM_UNSHIFT_AFTER_END_EVENT,} from "../errors.ts";import { nextTick } from "../../_next_tick.ts";import { stdio } from "../../_process/stdio.mjs";import _from from "./from.mjs";import BufferList from "./buffer_list.mjs";import destroyImpl from "./destroy.mjs";import EE from "../../events.ts";
let debug = debuglog("stream", (fn) => { debug = fn;});
const kPaused = Symbol("kPaused");
Object.setPrototypeOf(Readable.prototype, Stream.prototype);Object.setPrototypeOf(Readable, Stream);const nop = () => {};
const { errorOrDestroy } = destroyImpl;
function ReadableState(options, stream, isDuplex) { if (typeof isDuplex !== "boolean") { isDuplex = stream instanceof Stream.Duplex; }
this.objectMode = !!(options && options.objectMode);
if (isDuplex) { this.objectMode = this.objectMode || !!(options && options.readableObjectMode); }
this.highWaterMark = options ? getHighWaterMark(this, options, "readableHighWaterMark", isDuplex) : getDefaultHighWaterMark(false);
this.buffer = new BufferList(); this.length = 0; this.pipes = []; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false;
this.constructed = true;
this.sync = true;
this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; this[kPaused] = null;
this.errorEmitted = false;
this.emitClose = !options || options.emitClose !== false;
this.autoDestroy = !options || options.autoDestroy !== false;
this.destroyed = false;
this.errored = null;
this.closed = false;
this.closeEmitted = false;
this.defaultEncoding = (options && options.defaultEncoding) || "utf8";
this.awaitDrainWriters = null; this.multiAwaitDrain = false;
this.readingMore = false;
this.dataEmitted = false;
this.decoder = null; this.encoding = null; if (options && options.encoding) { this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; }}
function Readable(options) { if (!(this instanceof Readable)) { return new Readable(options); }
const isDuplex = this instanceof Stream.Duplex;
this._readableState = new ReadableState(options, this, isDuplex);
if (options) { if (typeof options.read === "function") { this._read = options.read; }
if (typeof options.destroy === "function") { this._destroy = options.destroy; }
if (typeof options.construct === "function") { this._construct = options.construct; } if (options.signal && !isDuplex) { addAbortSignalNoValidate(options.signal, this); } }
Stream.call(this, options);
destroyImpl.construct(this, () => { if (this._readableState.needReadable) { maybeReadMore(this, this._readableState); } });}
Readable.prototype.destroy = destroyImpl.destroy;Readable.prototype._undestroy = destroyImpl.undestroy;Readable.prototype._destroy = function (err, cb) { cb(err);};
Readable.prototype[EE.captureRejectionSymbol] = function (err) { this.destroy(err);};
Readable.prototype.push = function (chunk, encoding) { return readableAddChunk(this, chunk, encoding, false);};
Readable.prototype.unshift = function (chunk, encoding) { return readableAddChunk(this, chunk, encoding, true);};
function readableAddChunk(stream, chunk, encoding, addToFront) { debug("readableAddChunk", chunk); const state = stream._readableState;
let err; if (!state.objectMode) { if (typeof chunk === "string") { encoding = encoding || state.defaultEncoding; if (state.encoding !== encoding) { if (addToFront && state.encoding) { chunk = Buffer.from(chunk, encoding).toString(state.encoding); } else { chunk = Buffer.from(chunk, encoding); encoding = ""; } } } else if (chunk instanceof Buffer) { encoding = ""; } else if (Stream._isUint8Array(chunk)) { chunk = Stream._uint8ArrayToBuffer(chunk); encoding = ""; } else if (chunk != null) { err = new ERR_INVALID_ARG_TYPE( "chunk", ["string", "Buffer", "Uint8Array"], chunk, ); } }
if (err) { errorOrDestroy(stream, err); } else if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else if (state.objectMode || (chunk && chunk.length > 0)) { if (addToFront) { if (state.endEmitted) { errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); } else { addChunk(stream, state, chunk, true); } } else if (state.ended) { errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); } else if (state.destroyed || state.errored) { return false; } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) { addChunk(stream, state, chunk, false); } else { maybeReadMore(stream, state); } } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; maybeReadMore(stream, state); }
return !state.ended && (state.length < state.highWaterMark || state.length === 0);}
function addChunk(stream, state, chunk, addToFront) { if ( state.flowing && state.length === 0 && !state.sync && stream.listenerCount("data") > 0 ) { if (state.multiAwaitDrain) { state.awaitDrainWriters.clear(); } else { state.awaitDrainWriters = null; } state.dataEmitted = true; stream.emit("data", chunk); } else { state.length += state.objectMode ? 1 : chunk.length; if (addToFront) { state.buffer.unshift(chunk); } else { state.buffer.push(chunk); }
if (state.needReadable) { emitReadable(stream); } } maybeReadMore(stream, state);}
Readable.prototype.isPaused = function () { const state = this._readableState; return state[kPaused] === true || state.flowing === false;};
Readable.prototype.setEncoding = function (enc) { const decoder = new StringDecoder(enc); this._readableState.decoder = decoder; this._readableState.encoding = this._readableState.decoder.encoding;
const buffer = this._readableState.buffer; let content = ""; for (const data of buffer) { content += decoder.write(data); } buffer.clear(); if (content !== "") { buffer.push(content); } this._readableState.length = content.length; return this;};
const MAX_HWM = 0x40000000;function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n;}
function howMuchToRead(n, state) { if (n <= 0 || (state.length === 0 && state.ended)) { return 0; } if (state.objectMode) { return 1; } if (Number.isNaN(n)) { if (state.flowing && state.length) { return state.buffer.first().length; } return state.length; } if (n <= state.length) { return n; } return state.ended ? state.length : 0;}
Readable.prototype.read = function (n) { debug("read", n); if (n === undefined) { n = NaN; } else if (!Number.isInteger(n)) { n = Number.parseInt(n, 10); } const state = this._readableState; const nOrig = n;
if (n > state.highWaterMark) { state.highWaterMark = computeNewHighWaterMark(n); }
if (n !== 0) { state.emittedReadable = false; }
if ( n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended) ) { debug("read: emitReadable", state.length, state.ended); if (state.length === 0 && state.ended) { endReadable(this); } else { emitReadable(this); } return null; }
n = howMuchToRead(n, state);
if (n === 0 && state.ended) { if (state.length === 0) { endReadable(this); } return null; }
let doRead = state.needReadable; debug("need readable", doRead);
if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug("length less than watermark", doRead); }
if ( state.ended || state.reading || state.destroyed || state.errored || !state.constructed ) { doRead = false; debug("reading, ended or constructing", doRead); } else if (doRead) { debug("do read"); state.reading = true; state.sync = true; if (state.length === 0) { state.needReadable = true; }
this._read(state.highWaterMark);
state.sync = false; if (!state.reading) { n = howMuchToRead(nOrig, state); } }
let ret; if (n > 0) { ret = fromList(n, state); } else { ret = null; }
if (ret === null) { state.needReadable = state.length <= state.highWaterMark; n = 0; } else { state.length -= n; if (state.multiAwaitDrain) { state.awaitDrainWriters.clear(); } else { state.awaitDrainWriters = null; } }
if (state.length === 0) { if (!state.ended) { state.needReadable = true; }
if (nOrig !== n && state.ended) { endReadable(this); } }
if (ret !== null) { state.dataEmitted = true; this.emit("data", ret); }
return ret;};
function onEofChunk(stream, state) { debug("onEofChunk"); if (state.ended) return; if (state.decoder) { const chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true;
if (state.sync) { emitReadable(stream); } else { state.needReadable = false; state.emittedReadable = true; emitReadable_(stream); }}
function emitReadable(stream) { const state = stream._readableState; debug("emitReadable", state.needReadable, state.emittedReadable); state.needReadable = false; if (!state.emittedReadable) { debug("emitReadable", state.flowing); state.emittedReadable = true; nextTick(emitReadable_, stream); }}
function emitReadable_(stream) { const state = stream._readableState; debug("emitReadable_", state.destroyed, state.length, state.ended); if (!state.destroyed && !state.errored && (state.length || state.ended)) { stream.emit("readable"); state.emittedReadable = false; }
state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; flow(stream);}
function maybeReadMore(stream, state) { if (!state.readingMore && state.constructed) { state.readingMore = true; nextTick(maybeReadMore_, stream, state); }}
function maybeReadMore_(stream, state) { while ( !state.reading && !state.ended && (state.length < state.highWaterMark || (state.flowing && state.length === 0)) ) { const len = state.length; debug("maybeReadMore read 0"); stream.read(0); if (len === state.length) { break; } } state.readingMore = false;}
Readable.prototype._read = function (n) { throw new ERR_METHOD_NOT_IMPLEMENTED("_read()");};
Readable.prototype.pipe = function (dest, pipeOpts) { const src = this; const state = this._readableState;
if (state.pipes.length === 1) { if (!state.multiAwaitDrain) { state.multiAwaitDrain = true; state.awaitDrainWriters = new Set( state.awaitDrainWriters ? [state.awaitDrainWriters] : [], ); } }
state.pipes.push(dest); debug("pipe count=%d opts=%j", state.pipes.length, pipeOpts);
const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== stdio.stdout && dest !== stdio.stderr;
const endFn = doEnd ? onend : unpipe; if (state.endEmitted) { nextTick(endFn); } else { src.once("end", endFn); }
dest.on("unpipe", onunpipe); function onunpipe(readable, unpipeInfo) { debug("onunpipe"); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } }
function onend() { debug("onend"); dest.end(); }
let ondrain;
let cleanedUp = false; function cleanup() { debug("cleanup"); dest.removeListener("close", onclose); dest.removeListener("finish", onfinish); if (ondrain) { dest.removeListener("drain", ondrain); } dest.removeListener("error", onerror); dest.removeListener("unpipe", onunpipe); src.removeListener("end", onend); src.removeListener("end", unpipe); src.removeListener("data", ondata);
cleanedUp = true;
if ( ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain) ) { ondrain(); } }
function pause() { if (!cleanedUp) { if (state.pipes.length === 1 && state.pipes[0] === dest) { debug("false write response, pause", 0); state.awaitDrainWriters = dest; state.multiAwaitDrain = false; } else if (state.pipes.length > 1 && state.pipes.includes(dest)) { debug("false write response, pause", state.awaitDrainWriters.size); state.awaitDrainWriters.add(dest); } src.pause(); } if (!ondrain) { ondrain = pipeOnDrain(src, dest); dest.on("drain", ondrain); } }
src.on("data", ondata); function ondata(chunk) { debug("ondata"); const ret = dest.write(chunk); debug("dest.write", ret); if (ret === false) { pause(); } }
function onerror(er) { debug("onerror", er); unpipe(); dest.removeListener("error", onerror); if (EE.listenerCount(dest, "error") === 0) { const s = dest._writableState || dest._readableState; if (s && !s.errorEmitted) { errorOrDestroy(dest, er); } else { dest.emit("error", er); } } }
prependListener(dest, "error", onerror);
function onclose() { dest.removeListener("finish", onfinish); unpipe(); } dest.once("close", onclose); function onfinish() { debug("onfinish"); dest.removeListener("close", onclose); unpipe(); } dest.once("finish", onfinish);
function unpipe() { debug("unpipe"); src.unpipe(dest); }
dest.emit("pipe", src);
if (dest.writableNeedDrain === true) { if (state.flowing) { pause(); } } else if (!state.flowing) { debug("pipe resume"); src.resume(); }
return dest;};
function pipeOnDrain(src, dest) { return function pipeOnDrainFunctionResult() { const state = src._readableState;
if (state.awaitDrainWriters === dest) { debug("pipeOnDrain", 1); state.awaitDrainWriters = null; } else if (state.multiAwaitDrain) { debug("pipeOnDrain", state.awaitDrainWriters.size); state.awaitDrainWriters.delete(dest); }
if ( (!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && EE.listenerCount(src, "data") ) { state.flowing = true; flow(src); } };}
Readable.prototype.unpipe = function (dest) { const state = this._readableState; const unpipeInfo = { hasUnpiped: false };
if (state.pipes.length === 0) { return this; }
if (!dest) { const dests = state.pipes; state.pipes = []; this.pause();
for (let i = 0; i < dests.length; i++) { dests[i].emit("unpipe", this, { hasUnpiped: false }); } return this; }
const index = state.pipes.indexOf(dest); if (index === -1) { return this; }
state.pipes.splice(index, 1); if (state.pipes.length === 0) { this.pause(); }
dest.emit("unpipe", this, unpipeInfo);
return this;};
Readable.prototype.on = function (ev, fn) { const res = Stream.prototype.on.call(this, ev, fn); const state = this._readableState;
if (ev === "data") { state.readableListening = this.listenerCount("readable") > 0;
if (state.flowing !== false) { this.resume(); } } else if (ev === "readable") { if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.flowing = false; state.emittedReadable = false; debug("on readable", state.length, state.reading); if (state.length) { emitReadable(this); } else if (!state.reading) { nextTick(nReadingNextTick, this); } } }
return res;};Readable.prototype.addListener = Readable.prototype.on;
Readable.prototype.removeListener = function (ev, fn) { const res = Stream.prototype.removeListener.call(this, ev, fn);
if (ev === "readable") { nextTick(updateReadableListening, this); }
return res;};Readable.prototype.off = Readable.prototype.removeListener;
Readable.prototype.removeAllListeners = function (ev) { const res = Stream.prototype.removeAllListeners.apply(this, arguments);
if (ev === "readable" || ev === undefined) { nextTick(updateReadableListening, this); }
return res;};
function updateReadableListening(self) { const state = self._readableState; state.readableListening = self.listenerCount("readable") > 0;
if (state.resumeScheduled && state[kPaused] === false) { state.flowing = true;
} else if (self.listenerCount("data") > 0) { self.resume(); } else if (!state.readableListening) { state.flowing = null; }}
function nReadingNextTick(self) { debug("readable nexttick read 0"); self.read(0);}
Readable.prototype.resume = function () { const state = this._readableState; if (!state.flowing) { debug("resume"); state.flowing = !state.readableListening; resume(this, state); } state[kPaused] = false; return this;};
function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; nextTick(resume_, stream, state); }}
function resume_(stream, state) { debug("resume", state.reading); if (!state.reading) { stream.read(0); }
state.resumeScheduled = false; stream.emit("resume"); flow(stream); if (state.flowing && !state.reading) { stream.read(0); }}
Readable.prototype.pause = function () { debug("call pause flowing=%j", this._readableState.flowing); if (this._readableState.flowing !== false) { debug("pause"); this._readableState.flowing = false; this.emit("pause"); } this._readableState[kPaused] = true; return this;};
function flow(stream) { const state = stream._readableState; debug("flow", state.flowing); while (state.flowing && stream.read() !== null);}
Readable.prototype.wrap = function (stream) { let paused = false;
stream.on("data", (chunk) => { if (!this.push(chunk) && stream.pause) { paused = true; stream.pause(); } });
stream.on("end", () => { this.push(null); });
stream.on("error", (err) => { errorOrDestroy(this, err); });
stream.on("close", () => { this.destroy(); });
stream.on("destroy", () => { this.destroy(); });
this._read = () => { if (paused && stream.resume) { paused = false; stream.resume(); } };
const streamKeys = Object.keys(stream); for (let j = 1; j < streamKeys.length; j++) { const i = streamKeys[j]; if (this[i] === undefined && typeof stream[i] === "function") { this[i] = stream[i].bind(stream); } }
return this;};
Readable.prototype[Symbol.asyncIterator] = function () { return streamToAsyncIterator(this);};
Readable.prototype.iterator = function (options) { if (options !== undefined) { validateObject(options, "options"); } return streamToAsyncIterator(this, options);};
function streamToAsyncIterator(stream, options) { if (typeof stream.read !== "function") { stream = Readable.wrap(stream, { objectMode: true }); }
const iter = createAsyncIterator(stream, options); iter.stream = stream; return iter;}
async function* createAsyncIterator(stream, options) { let callback = nop;
const opts = { destroyOnReturn: true, destroyOnError: true, ...options, };
function next(resolve) { if (this === stream) { callback(); callback = nop; } else { callback = resolve; } }
const state = stream._readableState;
let error = state.errored; let errorEmitted = state.errorEmitted; let endEmitted = state.endEmitted; let closeEmitted = state.closeEmitted;
stream .on("readable", next) .on("error", function (err) { error = err; errorEmitted = true; next.call(this); }) .on("end", function () { endEmitted = true; next.call(this); }) .on("close", function () { closeEmitted = true; next.call(this); });
let errorThrown = false; try { while (true) { const chunk = stream.destroyed ? null : stream.read(); if (chunk !== null) { yield chunk; } else if (errorEmitted) { throw error; } else if (endEmitted) { break; } else if (closeEmitted) { break; } else { await new Promise(next); } } } catch (err) { if (opts.destroyOnError) { destroyImpl.destroyer(stream, err); } errorThrown = true; throw err; } finally { if (!errorThrown && opts.destroyOnReturn) { if (state.autoDestroy || !endEmitted) { destroyImpl.destroyer(stream, null); } } }}
Object.defineProperties(Readable.prototype, { readable: { get() { const r = this._readableState; return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted; }, set(val) { if (this._readableState) { this._readableState.readable = !!val; } }, },
readableDidRead: { enumerable: false, get: function () { return this._readableState.dataEmitted; }, },
readableAborted: { enumerable: false, get: function () { return !!(this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted; }, },
readableHighWaterMark: { enumerable: false, get: function () { return this._readableState.highWaterMark; }, },
readableBuffer: { enumerable: false, get: function () { return this._readableState && this._readableState.buffer; }, },
readableFlowing: { enumerable: false, get: function () { return this._readableState.flowing; }, set: function (state) { if (this._readableState) { this._readableState.flowing = state; } }, },
readableLength: { enumerable: false, get() { return this._readableState.length; }, },
readableObjectMode: { enumerable: false, get() { return this._readableState ? this._readableState.objectMode : false; }, },
readableEncoding: { enumerable: false, get() { return this._readableState ? this._readableState.encoding : null; }, },
destroyed: { enumerable: false, get() { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set(value) { if (!this._readableState) { return; }
this._readableState.destroyed = value; }, },
readableEnded: { enumerable: false, get() { return this._readableState ? this._readableState.endEmitted : false; }, },});
Object.defineProperties(ReadableState.prototype, { pipesCount: { get() { return this.pipes.length; }, },
paused: { get() { return this[kPaused] !== false; }, set(value) { this[kPaused] = !!value; }, },});
function fromList(n, state) { if (state.length === 0) { return null; }
let ret; if (state.objectMode) { ret = state.buffer.shift(); } else if (!n || n >= state.length) { if (state.decoder) { ret = state.buffer.join(""); } else if (state.buffer.length === 1) { ret = state.buffer.first(); } else { ret = state.buffer.concat(state.length); } state.buffer.clear(); } else { ret = state.buffer.consume(n, state.decoder); }
return ret;}
function endReadable(stream) { const state = stream._readableState;
debug("endReadable", state.endEmitted); if (!state.endEmitted) { state.ended = true; nextTick(endReadableNT, state, stream); }}
function endReadableNT(state, stream) { debug("endReadableNT", state.endEmitted, state.length);
if ( !state.errorEmitted && !state.closeEmitted && !state.endEmitted && state.length === 0 ) { state.endEmitted = true; stream.emit("end");
if (stream.writable && stream.allowHalfOpen === false) { nextTick(endWritableNT, stream); } else if (state.autoDestroy) { const wState = stream._writableState; const autoDestroy = !wState || ( wState.autoDestroy && (wState.finished || wState.writable === false) );
if (autoDestroy) { stream.destroy(); } } }}
function endWritableNT(stream) { const writable = stream.writable && !stream.writableEnded && !stream.destroyed; if (writable) { stream.end(); }}
function readableFrom(iterable, opts) { return _from(Readable, iterable, opts);}
function wrap(src, options) { return new Readable({ objectMode: src.readableObjectMode ?? src.objectMode ?? true, ...options, destroy(err, callback) { destroyImpl.destroyer(src, err); callback(err); }, }).wrap(src);}
Readable._fromList = fromList;Readable.ReadableState = ReadableState;Readable.from = readableFrom;Readable.wrap = wrap;
export default Readable;export { fromList as _fromList, readableFrom as from, ReadableState, wrap };