index.js 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190
  1. module.exports = (function() {
  2. var __MODS__ = {};
  3. var __DEFINE__ = function(modId, func, req) { var m = { exports: {}, _tempexports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; };
  4. var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = __MODS__[modId].m; m._exports = m._tempexports; var desp = Object.getOwnPropertyDescriptor(m, "exports"); if (desp && desp.configurable) Object.defineProperty(m, "exports", { set: function (val) { if(typeof val === "object" && val !== m._exports) { m._exports.__proto__ = val.__proto__; Object.keys(val).forEach(function (k) { m._exports[k] = val[k]; }); } m._tempexports = val }, get: function () { return m._tempexports; } }); __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); } return __MODS__[modId].m.exports; };
  5. var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } };
  6. var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; };
  7. __DEFINE__(1682324647566, function(require, module, exports) {
  8. var Stream = require('stream');
  9. if (process.env.READABLE_STREAM === 'disable' && Stream) {
  10. module.exports = Stream.Readable;
  11. Object.assign(module.exports, Stream);
  12. module.exports.Stream = Stream;
  13. } else {
  14. exports = module.exports = require('./lib/_stream_readable.js');
  15. exports.Stream = Stream || exports;
  16. exports.Readable = exports;
  17. exports.Writable = require('./lib/_stream_writable.js');
  18. exports.Duplex = require('./lib/_stream_duplex.js');
  19. exports.Transform = require('./lib/_stream_transform.js');
  20. exports.PassThrough = require('./lib/_stream_passthrough.js');
  21. exports.finished = require('./lib/internal/streams/end-of-stream.js');
  22. exports.pipeline = require('./lib/internal/streams/pipeline.js');
  23. }
  24. }, function(modId) {var map = {"./lib/_stream_readable.js":1682324647567,"./lib/_stream_writable.js":1682324647574,"./lib/_stream_duplex.js":1682324647573,"./lib/_stream_transform.js":1682324647578,"./lib/_stream_passthrough.js":1682324647579,"./lib/internal/streams/end-of-stream.js":1682324647576,"./lib/internal/streams/pipeline.js":1682324647580}; return __REQUIRE__(map[modId], modId); })
  25. __DEFINE__(1682324647567, function(require, module, exports) {
  26. // Copyright Joyent, Inc. and other Node contributors.
  27. //
  28. // Permission is hereby granted, free of charge, to any person obtaining a
  29. // copy of this software and associated documentation files (the
  30. // "Software"), to deal in the Software without restriction, including
  31. // without limitation the rights to use, copy, modify, merge, publish,
  32. // distribute, sublicense, and/or sell copies of the Software, and to permit
  33. // persons to whom the Software is furnished to do so, subject to the
  34. // following conditions:
  35. //
  36. // The above copyright notice and this permission notice shall be included
  37. // in all copies or substantial portions of the Software.
  38. //
  39. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  40. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  41. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  42. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  43. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  44. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  45. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  46. module.exports = Readable;
  47. /*<replacement>*/
  48. var Duplex;
  49. /*</replacement>*/
  50. Readable.ReadableState = ReadableState;
  51. /*<replacement>*/
  52. var EE = require('events').EventEmitter;
  53. var EElistenerCount = function EElistenerCount(emitter, type) {
  54. return emitter.listeners(type).length;
  55. };
  56. /*</replacement>*/
  57. /*<replacement>*/
  58. var Stream = require('./internal/streams/stream');
  59. /*</replacement>*/
  60. var Buffer = require('buffer').Buffer;
  61. var OurUint8Array = global.Uint8Array || function () {};
  62. function _uint8ArrayToBuffer(chunk) {
  63. return Buffer.from(chunk);
  64. }
  65. function _isUint8Array(obj) {
  66. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  67. }
  68. /*<replacement>*/
  69. var debugUtil = require('util');
  70. var debug;
  71. if (debugUtil && debugUtil.debuglog) {
  72. debug = debugUtil.debuglog('stream');
  73. } else {
  74. debug = function debug() {};
  75. }
  76. /*</replacement>*/
  77. var BufferList = require('./internal/streams/buffer_list');
  78. var destroyImpl = require('./internal/streams/destroy');
  79. var _require = require('./internal/streams/state'),
  80. getHighWaterMark = _require.getHighWaterMark;
  81. var _require$codes = require('../errors').codes,
  82. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  83. ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
  84. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  85. ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
  86. var StringDecoder;
  87. var createReadableStreamAsyncIterator;
  88. var from;
  89. require('inherits')(Readable, Stream);
  90. var errorOrDestroy = destroyImpl.errorOrDestroy;
  91. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  92. function prependListener(emitter, event, fn) {
  93. // Sadly this is not cacheable as some libraries bundle their own
  94. // event emitter implementation with them.
  95. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
  96. // userland ones. NEVER DO THIS. This is here only because this code needs
  97. // to continue to work with older versions of Node.js that do not include
  98. // the prependListener() method. The goal is to eventually remove this hack.
  99. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  100. }
  101. function ReadableState(options, stream, isDuplex) {
  102. Duplex = Duplex || require('./_stream_duplex');
  103. options = options || {}; // Duplex streams are both readable and writable, but share
  104. // the same options object.
  105. // However, some cases require setting options to different
  106. // values for the readable and the writable sides of the duplex stream.
  107. // These options can be provided separately as readableXXX and writableXXX.
  108. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
  109. // make all the buffer merging and length checks go away
  110. this.objectMode = !!options.objectMode;
  111. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
  112. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  113. this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
  114. // linked list can remove elements from the beginning faster than
  115. // array.shift()
  116. this.buffer = new BufferList();
  117. this.length = 0;
  118. this.pipes = null;
  119. this.pipesCount = 0;
  120. this.flowing = null;
  121. this.ended = false;
  122. this.endEmitted = false;
  123. this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
  124. // immediately, or on a later tick. We set this to true at first, because
  125. // any actions that shouldn't happen until "later" should generally also
  126. // not happen before the first read call.
  127. this.sync = true; // whenever we return null, then we set a flag to say
  128. // that we're awaiting a 'readable' event emission.
  129. this.needReadable = false;
  130. this.emittedReadable = false;
  131. this.readableListening = false;
  132. this.resumeScheduled = false;
  133. this.paused = true; // Should close be emitted on destroy. Defaults to true.
  134. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
  135. this.autoDestroy = !!options.autoDestroy; // has it been destroyed
  136. this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
  137. // encoding is 'binary' so we have to make this configurable.
  138. // Everything else in the universe uses 'utf8', though.
  139. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
  140. this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
  141. this.readingMore = false;
  142. this.decoder = null;
  143. this.encoding = null;
  144. if (options.encoding) {
  145. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  146. this.decoder = new StringDecoder(options.encoding);
  147. this.encoding = options.encoding;
  148. }
  149. }
  150. function Readable(options) {
  151. Duplex = Duplex || require('./_stream_duplex');
  152. if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
  153. // the ReadableState constructor, at least with V8 6.5
  154. var isDuplex = this instanceof Duplex;
  155. this._readableState = new ReadableState(options, this, isDuplex); // legacy
  156. this.readable = true;
  157. if (options) {
  158. if (typeof options.read === 'function') this._read = options.read;
  159. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  160. }
  161. Stream.call(this);
  162. }
  163. Object.defineProperty(Readable.prototype, 'destroyed', {
  164. // making it explicit this property is not enumerable
  165. // because otherwise some prototype manipulation in
  166. // userland will fail
  167. enumerable: false,
  168. get: function get() {
  169. if (this._readableState === undefined) {
  170. return false;
  171. }
  172. return this._readableState.destroyed;
  173. },
  174. set: function set(value) {
  175. // we ignore the value if the stream
  176. // has not been initialized yet
  177. if (!this._readableState) {
  178. return;
  179. } // backward compatibility, the user is explicitly
  180. // managing destroyed
  181. this._readableState.destroyed = value;
  182. }
  183. });
  184. Readable.prototype.destroy = destroyImpl.destroy;
  185. Readable.prototype._undestroy = destroyImpl.undestroy;
  186. Readable.prototype._destroy = function (err, cb) {
  187. cb(err);
  188. }; // Manually shove something into the read() buffer.
  189. // This returns true if the highWaterMark has not been hit yet,
  190. // similar to how Writable.write() returns true if you should
  191. // write() some more.
  192. Readable.prototype.push = function (chunk, encoding) {
  193. var state = this._readableState;
  194. var skipChunkCheck;
  195. if (!state.objectMode) {
  196. if (typeof chunk === 'string') {
  197. encoding = encoding || state.defaultEncoding;
  198. if (encoding !== state.encoding) {
  199. chunk = Buffer.from(chunk, encoding);
  200. encoding = '';
  201. }
  202. skipChunkCheck = true;
  203. }
  204. } else {
  205. skipChunkCheck = true;
  206. }
  207. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  208. }; // Unshift should *always* be something directly out of read()
  209. Readable.prototype.unshift = function (chunk) {
  210. return readableAddChunk(this, chunk, null, true, false);
  211. };
  212. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  213. debug('readableAddChunk', chunk);
  214. var state = stream._readableState;
  215. if (chunk === null) {
  216. state.reading = false;
  217. onEofChunk(stream, state);
  218. } else {
  219. var er;
  220. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  221. if (er) {
  222. errorOrDestroy(stream, er);
  223. } else if (state.objectMode || chunk && chunk.length > 0) {
  224. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  225. chunk = _uint8ArrayToBuffer(chunk);
  226. }
  227. if (addToFront) {
  228. if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
  229. } else if (state.ended) {
  230. errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
  231. } else if (state.destroyed) {
  232. return false;
  233. } else {
  234. state.reading = false;
  235. if (state.decoder && !encoding) {
  236. chunk = state.decoder.write(chunk);
  237. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  238. } else {
  239. addChunk(stream, state, chunk, false);
  240. }
  241. }
  242. } else if (!addToFront) {
  243. state.reading = false;
  244. maybeReadMore(stream, state);
  245. }
  246. } // We can push more data if we are below the highWaterMark.
  247. // Also, if we have no data yet, we can stand some more bytes.
  248. // This is to work around cases where hwm=0, such as the repl.
  249. return !state.ended && (state.length < state.highWaterMark || state.length === 0);
  250. }
  251. function addChunk(stream, state, chunk, addToFront) {
  252. if (state.flowing && state.length === 0 && !state.sync) {
  253. state.awaitDrain = 0;
  254. stream.emit('data', chunk);
  255. } else {
  256. // update the buffer info.
  257. state.length += state.objectMode ? 1 : chunk.length;
  258. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  259. if (state.needReadable) emitReadable(stream);
  260. }
  261. maybeReadMore(stream, state);
  262. }
  263. function chunkInvalid(state, chunk) {
  264. var er;
  265. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  266. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
  267. }
  268. return er;
  269. }
  270. Readable.prototype.isPaused = function () {
  271. return this._readableState.flowing === false;
  272. }; // backwards compatibility.
  273. Readable.prototype.setEncoding = function (enc) {
  274. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  275. var decoder = new StringDecoder(enc);
  276. this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
  277. this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
  278. var p = this._readableState.buffer.head;
  279. var content = '';
  280. while (p !== null) {
  281. content += decoder.write(p.data);
  282. p = p.next;
  283. }
  284. this._readableState.buffer.clear();
  285. if (content !== '') this._readableState.buffer.push(content);
  286. this._readableState.length = content.length;
  287. return this;
  288. }; // Don't raise the hwm > 1GB
  289. var MAX_HWM = 0x40000000;
  290. function computeNewHighWaterMark(n) {
  291. if (n >= MAX_HWM) {
  292. // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
  293. n = MAX_HWM;
  294. } else {
  295. // Get the next highest power of 2 to prevent increasing hwm excessively in
  296. // tiny amounts
  297. n--;
  298. n |= n >>> 1;
  299. n |= n >>> 2;
  300. n |= n >>> 4;
  301. n |= n >>> 8;
  302. n |= n >>> 16;
  303. n++;
  304. }
  305. return n;
  306. } // This function is designed to be inlinable, so please take care when making
  307. // changes to the function body.
  308. function howMuchToRead(n, state) {
  309. if (n <= 0 || state.length === 0 && state.ended) return 0;
  310. if (state.objectMode) return 1;
  311. if (n !== n) {
  312. // Only flow one buffer at a time
  313. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  314. } // If we're asking for more than the current hwm, then raise the hwm.
  315. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  316. if (n <= state.length) return n; // Don't have enough
  317. if (!state.ended) {
  318. state.needReadable = true;
  319. return 0;
  320. }
  321. return state.length;
  322. } // you can override either this method, or the async _read(n) below.
  323. Readable.prototype.read = function (n) {
  324. debug('read', n);
  325. n = parseInt(n, 10);
  326. var state = this._readableState;
  327. var nOrig = n;
  328. if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
  329. // already have a bunch of data in the buffer, then just trigger
  330. // the 'readable' event and move on.
  331. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
  332. debug('read: emitReadable', state.length, state.ended);
  333. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  334. return null;
  335. }
  336. n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
  337. if (n === 0 && state.ended) {
  338. if (state.length === 0) endReadable(this);
  339. return null;
  340. } // All the actual chunk generation logic needs to be
  341. // *below* the call to _read. The reason is that in certain
  342. // synthetic stream cases, such as passthrough streams, _read
  343. // may be a completely synchronous operation which may change
  344. // the state of the read buffer, providing enough data when
  345. // before there was *not* enough.
  346. //
  347. // So, the steps are:
  348. // 1. Figure out what the state of things will be after we do
  349. // a read from the buffer.
  350. //
  351. // 2. If that resulting state will trigger a _read, then call _read.
  352. // Note that this may be asynchronous, or synchronous. Yes, it is
  353. // deeply ugly to write APIs this way, but that still doesn't mean
  354. // that the Readable class should behave improperly, as streams are
  355. // designed to be sync/async agnostic.
  356. // Take note if the _read call is sync or async (ie, if the read call
  357. // has returned yet), so that we know whether or not it's safe to emit
  358. // 'readable' etc.
  359. //
  360. // 3. Actually pull the requested chunks out of the buffer and return.
  361. // if we need a readable event, then we need to do some reading.
  362. var doRead = state.needReadable;
  363. debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
  364. if (state.length === 0 || state.length - n < state.highWaterMark) {
  365. doRead = true;
  366. debug('length less than watermark', doRead);
  367. } // however, if we've ended, then there's no point, and if we're already
  368. // reading, then it's unnecessary.
  369. if (state.ended || state.reading) {
  370. doRead = false;
  371. debug('reading or ended', doRead);
  372. } else if (doRead) {
  373. debug('do read');
  374. state.reading = true;
  375. state.sync = true; // if the length is currently zero, then we *need* a readable event.
  376. if (state.length === 0) state.needReadable = true; // call internal read method
  377. this._read(state.highWaterMark);
  378. state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
  379. // and we need to re-evaluate how much data we can return to the user.
  380. if (!state.reading) n = howMuchToRead(nOrig, state);
  381. }
  382. var ret;
  383. if (n > 0) ret = fromList(n, state);else ret = null;
  384. if (ret === null) {
  385. state.needReadable = state.length <= state.highWaterMark;
  386. n = 0;
  387. } else {
  388. state.length -= n;
  389. state.awaitDrain = 0;
  390. }
  391. if (state.length === 0) {
  392. // If we have nothing in the buffer, then we want to know
  393. // as soon as we *do* get something into the buffer.
  394. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
  395. if (nOrig !== n && state.ended) endReadable(this);
  396. }
  397. if (ret !== null) this.emit('data', ret);
  398. return ret;
  399. };
  400. function onEofChunk(stream, state) {
  401. debug('onEofChunk');
  402. if (state.ended) return;
  403. if (state.decoder) {
  404. var chunk = state.decoder.end();
  405. if (chunk && chunk.length) {
  406. state.buffer.push(chunk);
  407. state.length += state.objectMode ? 1 : chunk.length;
  408. }
  409. }
  410. state.ended = true;
  411. if (state.sync) {
  412. // if we are sync, wait until next tick to emit the data.
  413. // Otherwise we risk emitting data in the flow()
  414. // the readable code triggers during a read() call
  415. emitReadable(stream);
  416. } else {
  417. // emit 'readable' now to make sure it gets picked up.
  418. state.needReadable = false;
  419. if (!state.emittedReadable) {
  420. state.emittedReadable = true;
  421. emitReadable_(stream);
  422. }
  423. }
  424. } // Don't emit readable right away in sync mode, because this can trigger
  425. // another read() call => stack overflow. This way, it might trigger
  426. // a nextTick recursion warning, but that's not so bad.
  427. function emitReadable(stream) {
  428. var state = stream._readableState;
  429. debug('emitReadable', state.needReadable, state.emittedReadable);
  430. state.needReadable = false;
  431. if (!state.emittedReadable) {
  432. debug('emitReadable', state.flowing);
  433. state.emittedReadable = true;
  434. process.nextTick(emitReadable_, stream);
  435. }
  436. }
  437. function emitReadable_(stream) {
  438. var state = stream._readableState;
  439. debug('emitReadable_', state.destroyed, state.length, state.ended);
  440. if (!state.destroyed && (state.length || state.ended)) {
  441. stream.emit('readable');
  442. state.emittedReadable = false;
  443. } // The stream needs another readable event if
  444. // 1. It is not flowing, as the flow mechanism will take
  445. // care of it.
  446. // 2. It is not ended.
  447. // 3. It is below the highWaterMark, so we can schedule
  448. // another readable later.
  449. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
  450. flow(stream);
  451. } // at this point, the user has presumably seen the 'readable' event,
  452. // and called read() to consume some data. that may have triggered
  453. // in turn another _read(n) call, in which case reading = true if
  454. // it's in progress.
  455. // However, if we're not ended, or reading, and the length < hwm,
  456. // then go ahead and try to read some more preemptively.
  457. function maybeReadMore(stream, state) {
  458. if (!state.readingMore) {
  459. state.readingMore = true;
  460. process.nextTick(maybeReadMore_, stream, state);
  461. }
  462. }
  463. function maybeReadMore_(stream, state) {
  464. // Attempt to read more data if we should.
  465. //
  466. // The conditions for reading more data are (one of):
  467. // - Not enough data buffered (state.length < state.highWaterMark). The loop
  468. // is responsible for filling the buffer with enough data if such data
  469. // is available. If highWaterMark is 0 and we are not in the flowing mode
  470. // we should _not_ attempt to buffer any extra data. We'll get more data
  471. // when the stream consumer calls read() instead.
  472. // - No data in the buffer, and the stream is in flowing mode. In this mode
  473. // the loop below is responsible for ensuring read() is called. Failing to
  474. // call read here would abort the flow and there's no other mechanism for
  475. // continuing the flow if the stream consumer has just subscribed to the
  476. // 'data' event.
  477. //
  478. // In addition to the above conditions to keep reading data, the following
  479. // conditions prevent the data from being read:
  480. // - The stream has ended (state.ended).
  481. // - There is already a pending 'read' operation (state.reading). This is a
  482. // case where the the stream has called the implementation defined _read()
  483. // method, but they are processing the call asynchronously and have _not_
  484. // called push() with new data. In this case we skip performing more
  485. // read()s. The execution ends in this method again after the _read() ends
  486. // up calling push() with more data.
  487. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
  488. var len = state.length;
  489. debug('maybeReadMore read 0');
  490. stream.read(0);
  491. if (len === state.length) // didn't get any data, stop spinning.
  492. break;
  493. }
  494. state.readingMore = false;
  495. } // abstract method. to be overridden in specific implementation classes.
  496. // call cb(er, data) where data is <= n in length.
  497. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  498. // arbitrary, and perhaps not very meaningful.
  499. Readable.prototype._read = function (n) {
  500. errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
  501. };
  502. Readable.prototype.pipe = function (dest, pipeOpts) {
  503. var src = this;
  504. var state = this._readableState;
  505. switch (state.pipesCount) {
  506. case 0:
  507. state.pipes = dest;
  508. break;
  509. case 1:
  510. state.pipes = [state.pipes, dest];
  511. break;
  512. default:
  513. state.pipes.push(dest);
  514. break;
  515. }
  516. state.pipesCount += 1;
  517. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  518. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  519. var endFn = doEnd ? onend : unpipe;
  520. if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
  521. dest.on('unpipe', onunpipe);
  522. function onunpipe(readable, unpipeInfo) {
  523. debug('onunpipe');
  524. if (readable === src) {
  525. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  526. unpipeInfo.hasUnpiped = true;
  527. cleanup();
  528. }
  529. }
  530. }
  531. function onend() {
  532. debug('onend');
  533. dest.end();
  534. } // when the dest drains, it reduces the awaitDrain counter
  535. // on the source. This would be more elegant with a .once()
  536. // handler in flow(), but adding and removing repeatedly is
  537. // too slow.
  538. var ondrain = pipeOnDrain(src);
  539. dest.on('drain', ondrain);
  540. var cleanedUp = false;
  541. function cleanup() {
  542. debug('cleanup'); // cleanup event handlers once the pipe is broken
  543. dest.removeListener('close', onclose);
  544. dest.removeListener('finish', onfinish);
  545. dest.removeListener('drain', ondrain);
  546. dest.removeListener('error', onerror);
  547. dest.removeListener('unpipe', onunpipe);
  548. src.removeListener('end', onend);
  549. src.removeListener('end', unpipe);
  550. src.removeListener('data', ondata);
  551. cleanedUp = true; // if the reader is waiting for a drain event from this
  552. // specific writer, then it would cause it to never start
  553. // flowing again.
  554. // So, if this is awaiting a drain, then we just call it now.
  555. // If we don't know, then assume that we are waiting for one.
  556. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  557. }
  558. src.on('data', ondata);
  559. function ondata(chunk) {
  560. debug('ondata');
  561. var ret = dest.write(chunk);
  562. debug('dest.write', ret);
  563. if (ret === false) {
  564. // If the user unpiped during `dest.write()`, it is possible
  565. // to get stuck in a permanently paused state if that write
  566. // also returned false.
  567. // => Check whether `dest` is still a piping destination.
  568. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  569. debug('false write response, pause', state.awaitDrain);
  570. state.awaitDrain++;
  571. }
  572. src.pause();
  573. }
  574. } // if the dest has an error, then stop piping into it.
  575. // however, don't suppress the throwing behavior for this.
  576. function onerror(er) {
  577. debug('onerror', er);
  578. unpipe();
  579. dest.removeListener('error', onerror);
  580. if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
  581. } // Make sure our error handler is attached before userland ones.
  582. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
  583. function onclose() {
  584. dest.removeListener('finish', onfinish);
  585. unpipe();
  586. }
  587. dest.once('close', onclose);
  588. function onfinish() {
  589. debug('onfinish');
  590. dest.removeListener('close', onclose);
  591. unpipe();
  592. }
  593. dest.once('finish', onfinish);
  594. function unpipe() {
  595. debug('unpipe');
  596. src.unpipe(dest);
  597. } // tell the dest that it's being piped to
  598. dest.emit('pipe', src); // start the flow if it hasn't been started already.
  599. if (!state.flowing) {
  600. debug('pipe resume');
  601. src.resume();
  602. }
  603. return dest;
  604. };
  605. function pipeOnDrain(src) {
  606. return function pipeOnDrainFunctionResult() {
  607. var state = src._readableState;
  608. debug('pipeOnDrain', state.awaitDrain);
  609. if (state.awaitDrain) state.awaitDrain--;
  610. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  611. state.flowing = true;
  612. flow(src);
  613. }
  614. };
  615. }
  616. Readable.prototype.unpipe = function (dest) {
  617. var state = this._readableState;
  618. var unpipeInfo = {
  619. hasUnpiped: false
  620. }; // if we're not piping anywhere, then do nothing.
  621. if (state.pipesCount === 0) return this; // just one destination. most common case.
  622. if (state.pipesCount === 1) {
  623. // passed in one, but it's not the right one.
  624. if (dest && dest !== state.pipes) return this;
  625. if (!dest) dest = state.pipes; // got a match.
  626. state.pipes = null;
  627. state.pipesCount = 0;
  628. state.flowing = false;
  629. if (dest) dest.emit('unpipe', this, unpipeInfo);
  630. return this;
  631. } // slow case. multiple pipe destinations.
  632. if (!dest) {
  633. // remove all.
  634. var dests = state.pipes;
  635. var len = state.pipesCount;
  636. state.pipes = null;
  637. state.pipesCount = 0;
  638. state.flowing = false;
  639. for (var i = 0; i < len; i++) {
  640. dests[i].emit('unpipe', this, {
  641. hasUnpiped: false
  642. });
  643. }
  644. return this;
  645. } // try to find the right one.
  646. var index = indexOf(state.pipes, dest);
  647. if (index === -1) return this;
  648. state.pipes.splice(index, 1);
  649. state.pipesCount -= 1;
  650. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  651. dest.emit('unpipe', this, unpipeInfo);
  652. return this;
  653. }; // set up data events if they are asked for
  654. // Ensure readable listeners eventually get something
  655. Readable.prototype.on = function (ev, fn) {
  656. var res = Stream.prototype.on.call(this, ev, fn);
  657. var state = this._readableState;
  658. if (ev === 'data') {
  659. // update readableListening so that resume() may be a no-op
  660. // a few lines down. This is needed to support once('readable').
  661. state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
  662. if (state.flowing !== false) this.resume();
  663. } else if (ev === 'readable') {
  664. if (!state.endEmitted && !state.readableListening) {
  665. state.readableListening = state.needReadable = true;
  666. state.flowing = false;
  667. state.emittedReadable = false;
  668. debug('on readable', state.length, state.reading);
  669. if (state.length) {
  670. emitReadable(this);
  671. } else if (!state.reading) {
  672. process.nextTick(nReadingNextTick, this);
  673. }
  674. }
  675. }
  676. return res;
  677. };
  678. Readable.prototype.addListener = Readable.prototype.on;
  679. Readable.prototype.removeListener = function (ev, fn) {
  680. var res = Stream.prototype.removeListener.call(this, ev, fn);
  681. if (ev === 'readable') {
  682. // We need to check if there is someone still listening to
  683. // readable and reset the state. However this needs to happen
  684. // after readable has been emitted but before I/O (nextTick) to
  685. // support once('readable', fn) cycles. This means that calling
  686. // resume within the same tick will have no
  687. // effect.
  688. process.nextTick(updateReadableListening, this);
  689. }
  690. return res;
  691. };
  692. Readable.prototype.removeAllListeners = function (ev) {
  693. var res = Stream.prototype.removeAllListeners.apply(this, arguments);
  694. if (ev === 'readable' || ev === undefined) {
  695. // We need to check if there is someone still listening to
  696. // readable and reset the state. However this needs to happen
  697. // after readable has been emitted but before I/O (nextTick) to
  698. // support once('readable', fn) cycles. This means that calling
  699. // resume within the same tick will have no
  700. // effect.
  701. process.nextTick(updateReadableListening, this);
  702. }
  703. return res;
  704. };
  705. function updateReadableListening(self) {
  706. var state = self._readableState;
  707. state.readableListening = self.listenerCount('readable') > 0;
  708. if (state.resumeScheduled && !state.paused) {
  709. // flowing needs to be set to true now, otherwise
  710. // the upcoming resume will not flow.
  711. state.flowing = true; // crude way to check if we should resume
  712. } else if (self.listenerCount('data') > 0) {
  713. self.resume();
  714. }
  715. }
  716. function nReadingNextTick(self) {
  717. debug('readable nexttick read 0');
  718. self.read(0);
  719. } // pause() and resume() are remnants of the legacy readable stream API
  720. // If the user uses them, then switch into old mode.
  721. Readable.prototype.resume = function () {
  722. var state = this._readableState;
  723. if (!state.flowing) {
  724. debug('resume'); // we flow only if there is no one listening
  725. // for readable, but we still have to call
  726. // resume()
  727. state.flowing = !state.readableListening;
  728. resume(this, state);
  729. }
  730. state.paused = false;
  731. return this;
  732. };
  733. function resume(stream, state) {
  734. if (!state.resumeScheduled) {
  735. state.resumeScheduled = true;
  736. process.nextTick(resume_, stream, state);
  737. }
  738. }
  739. function resume_(stream, state) {
  740. debug('resume', state.reading);
  741. if (!state.reading) {
  742. stream.read(0);
  743. }
  744. state.resumeScheduled = false;
  745. stream.emit('resume');
  746. flow(stream);
  747. if (state.flowing && !state.reading) stream.read(0);
  748. }
  749. Readable.prototype.pause = function () {
  750. debug('call pause flowing=%j', this._readableState.flowing);
  751. if (this._readableState.flowing !== false) {
  752. debug('pause');
  753. this._readableState.flowing = false;
  754. this.emit('pause');
  755. }
  756. this._readableState.paused = true;
  757. return this;
  758. };
  759. function flow(stream) {
  760. var state = stream._readableState;
  761. debug('flow', state.flowing);
  762. while (state.flowing && stream.read() !== null) {
  763. ;
  764. }
  765. } // wrap an old-style stream as the async data source.
  766. // This is *not* part of the readable stream interface.
  767. // It is an ugly unfortunate mess of history.
  768. Readable.prototype.wrap = function (stream) {
  769. var _this = this;
  770. var state = this._readableState;
  771. var paused = false;
  772. stream.on('end', function () {
  773. debug('wrapped end');
  774. if (state.decoder && !state.ended) {
  775. var chunk = state.decoder.end();
  776. if (chunk && chunk.length) _this.push(chunk);
  777. }
  778. _this.push(null);
  779. });
  780. stream.on('data', function (chunk) {
  781. debug('wrapped data');
  782. if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
  783. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  784. var ret = _this.push(chunk);
  785. if (!ret) {
  786. paused = true;
  787. stream.pause();
  788. }
  789. }); // proxy all the other methods.
  790. // important when wrapping filters and duplexes.
  791. for (var i in stream) {
  792. if (this[i] === undefined && typeof stream[i] === 'function') {
  793. this[i] = function methodWrap(method) {
  794. return function methodWrapReturnFunction() {
  795. return stream[method].apply(stream, arguments);
  796. };
  797. }(i);
  798. }
  799. } // proxy certain important events.
  800. for (var n = 0; n < kProxyEvents.length; n++) {
  801. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  802. } // when we try to consume some more bytes, simply unpause the
  803. // underlying stream.
  804. this._read = function (n) {
  805. debug('wrapped _read', n);
  806. if (paused) {
  807. paused = false;
  808. stream.resume();
  809. }
  810. };
  811. return this;
  812. };
  813. if (typeof Symbol === 'function') {
  814. Readable.prototype[Symbol.asyncIterator] = function () {
  815. if (createReadableStreamAsyncIterator === undefined) {
  816. createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
  817. }
  818. return createReadableStreamAsyncIterator(this);
  819. };
  820. }
  821. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  822. // making it explicit this property is not enumerable
  823. // because otherwise some prototype manipulation in
  824. // userland will fail
  825. enumerable: false,
  826. get: function get() {
  827. return this._readableState.highWaterMark;
  828. }
  829. });
  830. Object.defineProperty(Readable.prototype, 'readableBuffer', {
  831. // making it explicit this property is not enumerable
  832. // because otherwise some prototype manipulation in
  833. // userland will fail
  834. enumerable: false,
  835. get: function get() {
  836. return this._readableState && this._readableState.buffer;
  837. }
  838. });
  839. Object.defineProperty(Readable.prototype, 'readableFlowing', {
  840. // making it explicit this property is not enumerable
  841. // because otherwise some prototype manipulation in
  842. // userland will fail
  843. enumerable: false,
  844. get: function get() {
  845. return this._readableState.flowing;
  846. },
  847. set: function set(state) {
  848. if (this._readableState) {
  849. this._readableState.flowing = state;
  850. }
  851. }
  852. }); // exposed for testing purposes only.
  853. Readable._fromList = fromList;
  854. Object.defineProperty(Readable.prototype, 'readableLength', {
  855. // making it explicit this property is not enumerable
  856. // because otherwise some prototype manipulation in
  857. // userland will fail
  858. enumerable: false,
  859. get: function get() {
  860. return this._readableState.length;
  861. }
  862. }); // Pluck off n bytes from an array of buffers.
  863. // Length is the combined lengths of all the buffers in the list.
  864. // This function is designed to be inlinable, so please take care when making
  865. // changes to the function body.
  866. function fromList(n, state) {
  867. // nothing buffered
  868. if (state.length === 0) return null;
  869. var ret;
  870. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  871. // read it all, truncate the list
  872. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
  873. state.buffer.clear();
  874. } else {
  875. // read part of list
  876. ret = state.buffer.consume(n, state.decoder);
  877. }
  878. return ret;
  879. }
  880. function endReadable(stream) {
  881. var state = stream._readableState;
  882. debug('endReadable', state.endEmitted);
  883. if (!state.endEmitted) {
  884. state.ended = true;
  885. process.nextTick(endReadableNT, state, stream);
  886. }
  887. }
  888. function endReadableNT(state, stream) {
  889. debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
  890. if (!state.endEmitted && state.length === 0) {
  891. state.endEmitted = true;
  892. stream.readable = false;
  893. stream.emit('end');
  894. if (state.autoDestroy) {
  895. // In case of duplex streams we need a way to detect
  896. // if the writable side is ready for autoDestroy as well
  897. var wState = stream._writableState;
  898. if (!wState || wState.autoDestroy && wState.finished) {
  899. stream.destroy();
  900. }
  901. }
  902. }
  903. }
  904. if (typeof Symbol === 'function') {
  905. Readable.from = function (iterable, opts) {
  906. if (from === undefined) {
  907. from = require('./internal/streams/from');
  908. }
  909. return from(Readable, iterable, opts);
  910. };
  911. }
  912. function indexOf(xs, x) {
  913. for (var i = 0, l = xs.length; i < l; i++) {
  914. if (xs[i] === x) return i;
  915. }
  916. return -1;
  917. }
  918. }, function(modId) { var map = {"./internal/streams/stream":1682324647568,"./internal/streams/buffer_list":1682324647569,"./internal/streams/destroy":1682324647570,"./internal/streams/state":1682324647571,"../errors":1682324647572,"./_stream_duplex":1682324647573,"./internal/streams/async_iterator":1682324647575,"./internal/streams/from":1682324647577}; return __REQUIRE__(map[modId], modId); })
  919. __DEFINE__(1682324647568, function(require, module, exports) {
  920. module.exports = require('stream');
  921. }, function(modId) { var map = {"stream":1682324647568}; return __REQUIRE__(map[modId], modId); })
  922. __DEFINE__(1682324647569, function(require, module, exports) {
  923. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  924. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  925. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  926. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  927. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  928. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  929. var _require = require('buffer'),
  930. Buffer = _require.Buffer;
  931. var _require2 = require('util'),
  932. inspect = _require2.inspect;
  933. var custom = inspect && inspect.custom || 'inspect';
  934. function copyBuffer(src, target, offset) {
  935. Buffer.prototype.copy.call(src, target, offset);
  936. }
  937. module.exports =
  938. /*#__PURE__*/
  939. function () {
  940. function BufferList() {
  941. _classCallCheck(this, BufferList);
  942. this.head = null;
  943. this.tail = null;
  944. this.length = 0;
  945. }
  946. _createClass(BufferList, [{
  947. key: "push",
  948. value: function push(v) {
  949. var entry = {
  950. data: v,
  951. next: null
  952. };
  953. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  954. this.tail = entry;
  955. ++this.length;
  956. }
  957. }, {
  958. key: "unshift",
  959. value: function unshift(v) {
  960. var entry = {
  961. data: v,
  962. next: this.head
  963. };
  964. if (this.length === 0) this.tail = entry;
  965. this.head = entry;
  966. ++this.length;
  967. }
  968. }, {
  969. key: "shift",
  970. value: function shift() {
  971. if (this.length === 0) return;
  972. var ret = this.head.data;
  973. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  974. --this.length;
  975. return ret;
  976. }
  977. }, {
  978. key: "clear",
  979. value: function clear() {
  980. this.head = this.tail = null;
  981. this.length = 0;
  982. }
  983. }, {
  984. key: "join",
  985. value: function join(s) {
  986. if (this.length === 0) return '';
  987. var p = this.head;
  988. var ret = '' + p.data;
  989. while (p = p.next) {
  990. ret += s + p.data;
  991. }
  992. return ret;
  993. }
  994. }, {
  995. key: "concat",
  996. value: function concat(n) {
  997. if (this.length === 0) return Buffer.alloc(0);
  998. var ret = Buffer.allocUnsafe(n >>> 0);
  999. var p = this.head;
  1000. var i = 0;
  1001. while (p) {
  1002. copyBuffer(p.data, ret, i);
  1003. i += p.data.length;
  1004. p = p.next;
  1005. }
  1006. return ret;
  1007. } // Consumes a specified amount of bytes or characters from the buffered data.
  1008. }, {
  1009. key: "consume",
  1010. value: function consume(n, hasStrings) {
  1011. var ret;
  1012. if (n < this.head.data.length) {
  1013. // `slice` is the same for buffers and strings.
  1014. ret = this.head.data.slice(0, n);
  1015. this.head.data = this.head.data.slice(n);
  1016. } else if (n === this.head.data.length) {
  1017. // First chunk is a perfect match.
  1018. ret = this.shift();
  1019. } else {
  1020. // Result spans more than one buffer.
  1021. ret = hasStrings ? this._getString(n) : this._getBuffer(n);
  1022. }
  1023. return ret;
  1024. }
  1025. }, {
  1026. key: "first",
  1027. value: function first() {
  1028. return this.head.data;
  1029. } // Consumes a specified amount of characters from the buffered data.
  1030. }, {
  1031. key: "_getString",
  1032. value: function _getString(n) {
  1033. var p = this.head;
  1034. var c = 1;
  1035. var ret = p.data;
  1036. n -= ret.length;
  1037. while (p = p.next) {
  1038. var str = p.data;
  1039. var nb = n > str.length ? str.length : n;
  1040. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  1041. n -= nb;
  1042. if (n === 0) {
  1043. if (nb === str.length) {
  1044. ++c;
  1045. if (p.next) this.head = p.next;else this.head = this.tail = null;
  1046. } else {
  1047. this.head = p;
  1048. p.data = str.slice(nb);
  1049. }
  1050. break;
  1051. }
  1052. ++c;
  1053. }
  1054. this.length -= c;
  1055. return ret;
  1056. } // Consumes a specified amount of bytes from the buffered data.
  1057. }, {
  1058. key: "_getBuffer",
  1059. value: function _getBuffer(n) {
  1060. var ret = Buffer.allocUnsafe(n);
  1061. var p = this.head;
  1062. var c = 1;
  1063. p.data.copy(ret);
  1064. n -= p.data.length;
  1065. while (p = p.next) {
  1066. var buf = p.data;
  1067. var nb = n > buf.length ? buf.length : n;
  1068. buf.copy(ret, ret.length - n, 0, nb);
  1069. n -= nb;
  1070. if (n === 0) {
  1071. if (nb === buf.length) {
  1072. ++c;
  1073. if (p.next) this.head = p.next;else this.head = this.tail = null;
  1074. } else {
  1075. this.head = p;
  1076. p.data = buf.slice(nb);
  1077. }
  1078. break;
  1079. }
  1080. ++c;
  1081. }
  1082. this.length -= c;
  1083. return ret;
  1084. } // Make sure the linked list only shows the minimal necessary information.
  1085. }, {
  1086. key: custom,
  1087. value: function value(_, options) {
  1088. return inspect(this, _objectSpread({}, options, {
  1089. // Only inspect one level.
  1090. depth: 0,
  1091. // It should not recurse.
  1092. customInspect: false
  1093. }));
  1094. }
  1095. }]);
  1096. return BufferList;
  1097. }();
  1098. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  1099. __DEFINE__(1682324647570, function(require, module, exports) {
  1100. // undocumented cb() API, needed for core, not for public API
  1101. function destroy(err, cb) {
  1102. var _this = this;
  1103. var readableDestroyed = this._readableState && this._readableState.destroyed;
  1104. var writableDestroyed = this._writableState && this._writableState.destroyed;
  1105. if (readableDestroyed || writableDestroyed) {
  1106. if (cb) {
  1107. cb(err);
  1108. } else if (err) {
  1109. if (!this._writableState) {
  1110. process.nextTick(emitErrorNT, this, err);
  1111. } else if (!this._writableState.errorEmitted) {
  1112. this._writableState.errorEmitted = true;
  1113. process.nextTick(emitErrorNT, this, err);
  1114. }
  1115. }
  1116. return this;
  1117. } // we set destroyed to true before firing error callbacks in order
  1118. // to make it re-entrance safe in case destroy() is called within callbacks
  1119. if (this._readableState) {
  1120. this._readableState.destroyed = true;
  1121. } // if this is a duplex stream mark the writable part as destroyed as well
  1122. if (this._writableState) {
  1123. this._writableState.destroyed = true;
  1124. }
  1125. this._destroy(err || null, function (err) {
  1126. if (!cb && err) {
  1127. if (!_this._writableState) {
  1128. process.nextTick(emitErrorAndCloseNT, _this, err);
  1129. } else if (!_this._writableState.errorEmitted) {
  1130. _this._writableState.errorEmitted = true;
  1131. process.nextTick(emitErrorAndCloseNT, _this, err);
  1132. } else {
  1133. process.nextTick(emitCloseNT, _this);
  1134. }
  1135. } else if (cb) {
  1136. process.nextTick(emitCloseNT, _this);
  1137. cb(err);
  1138. } else {
  1139. process.nextTick(emitCloseNT, _this);
  1140. }
  1141. });
  1142. return this;
  1143. }
  1144. function emitErrorAndCloseNT(self, err) {
  1145. emitErrorNT(self, err);
  1146. emitCloseNT(self);
  1147. }
  1148. function emitCloseNT(self) {
  1149. if (self._writableState && !self._writableState.emitClose) return;
  1150. if (self._readableState && !self._readableState.emitClose) return;
  1151. self.emit('close');
  1152. }
  1153. function undestroy() {
  1154. if (this._readableState) {
  1155. this._readableState.destroyed = false;
  1156. this._readableState.reading = false;
  1157. this._readableState.ended = false;
  1158. this._readableState.endEmitted = false;
  1159. }
  1160. if (this._writableState) {
  1161. this._writableState.destroyed = false;
  1162. this._writableState.ended = false;
  1163. this._writableState.ending = false;
  1164. this._writableState.finalCalled = false;
  1165. this._writableState.prefinished = false;
  1166. this._writableState.finished = false;
  1167. this._writableState.errorEmitted = false;
  1168. }
  1169. }
  1170. function emitErrorNT(self, err) {
  1171. self.emit('error', err);
  1172. }
  1173. function errorOrDestroy(stream, err) {
  1174. // We have tests that rely on errors being emitted
  1175. // in the same tick, so changing this is semver major.
  1176. // For now when you opt-in to autoDestroy we allow
  1177. // the error to be emitted nextTick. In a future
  1178. // semver major update we should change the default to this.
  1179. var rState = stream._readableState;
  1180. var wState = stream._writableState;
  1181. if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
  1182. }
  1183. module.exports = {
  1184. destroy: destroy,
  1185. undestroy: undestroy,
  1186. errorOrDestroy: errorOrDestroy
  1187. };
  1188. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  1189. __DEFINE__(1682324647571, function(require, module, exports) {
  1190. var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
  1191. function highWaterMarkFrom(options, isDuplex, duplexKey) {
  1192. return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
  1193. }
  1194. function getHighWaterMark(state, options, duplexKey, isDuplex) {
  1195. var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
  1196. if (hwm != null) {
  1197. if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
  1198. var name = isDuplex ? duplexKey : 'highWaterMark';
  1199. throw new ERR_INVALID_OPT_VALUE(name, hwm);
  1200. }
  1201. return Math.floor(hwm);
  1202. } // Default value
  1203. return state.objectMode ? 16 : 16 * 1024;
  1204. }
  1205. module.exports = {
  1206. getHighWaterMark: getHighWaterMark
  1207. };
  1208. }, function(modId) { var map = {"../../../errors":1682324647572}; return __REQUIRE__(map[modId], modId); })
  1209. __DEFINE__(1682324647572, function(require, module, exports) {
  1210. const codes = {};
  1211. function createErrorType(code, message, Base) {
  1212. if (!Base) {
  1213. Base = Error
  1214. }
  1215. function getMessage (arg1, arg2, arg3) {
  1216. if (typeof message === 'string') {
  1217. return message
  1218. } else {
  1219. return message(arg1, arg2, arg3)
  1220. }
  1221. }
  1222. class NodeError extends Base {
  1223. constructor (arg1, arg2, arg3) {
  1224. super(getMessage(arg1, arg2, arg3));
  1225. }
  1226. }
  1227. NodeError.prototype.name = Base.name;
  1228. NodeError.prototype.code = code;
  1229. codes[code] = NodeError;
  1230. }
  1231. // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
  1232. function oneOf(expected, thing) {
  1233. if (Array.isArray(expected)) {
  1234. const len = expected.length;
  1235. expected = expected.map((i) => String(i));
  1236. if (len > 2) {
  1237. return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +
  1238. expected[len - 1];
  1239. } else if (len === 2) {
  1240. return `one of ${thing} ${expected[0]} or ${expected[1]}`;
  1241. } else {
  1242. return `of ${thing} ${expected[0]}`;
  1243. }
  1244. } else {
  1245. return `of ${thing} ${String(expected)}`;
  1246. }
  1247. }
  1248. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
  1249. function startsWith(str, search, pos) {
  1250. return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
  1251. }
  1252. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
  1253. function endsWith(str, search, this_len) {
  1254. if (this_len === undefined || this_len > str.length) {
  1255. this_len = str.length;
  1256. }
  1257. return str.substring(this_len - search.length, this_len) === search;
  1258. }
  1259. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
  1260. function includes(str, search, start) {
  1261. if (typeof start !== 'number') {
  1262. start = 0;
  1263. }
  1264. if (start + search.length > str.length) {
  1265. return false;
  1266. } else {
  1267. return str.indexOf(search, start) !== -1;
  1268. }
  1269. }
  1270. createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
  1271. return 'The value "' + value + '" is invalid for option "' + name + '"'
  1272. }, TypeError);
  1273. createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
  1274. // determiner: 'must be' or 'must not be'
  1275. let determiner;
  1276. if (typeof expected === 'string' && startsWith(expected, 'not ')) {
  1277. determiner = 'must not be';
  1278. expected = expected.replace(/^not /, '');
  1279. } else {
  1280. determiner = 'must be';
  1281. }
  1282. let msg;
  1283. if (endsWith(name, ' argument')) {
  1284. // For cases like 'first argument'
  1285. msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;
  1286. } else {
  1287. const type = includes(name, '.') ? 'property' : 'argument';
  1288. msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`;
  1289. }
  1290. msg += `. Received type ${typeof actual}`;
  1291. return msg;
  1292. }, TypeError);
  1293. createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
  1294. createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
  1295. return 'The ' + name + ' method is not implemented'
  1296. });
  1297. createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
  1298. createErrorType('ERR_STREAM_DESTROYED', function (name) {
  1299. return 'Cannot call ' + name + ' after a stream was destroyed';
  1300. });
  1301. createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
  1302. createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
  1303. createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
  1304. createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
  1305. createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
  1306. return 'Unknown encoding: ' + arg
  1307. }, TypeError);
  1308. createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
  1309. module.exports.codes = codes;
  1310. }, function(modId) { var map = {}; return __REQUIRE__(map[modId], modId); })
  1311. __DEFINE__(1682324647573, function(require, module, exports) {
  1312. // Copyright Joyent, Inc. and other Node contributors.
  1313. //
  1314. // Permission is hereby granted, free of charge, to any person obtaining a
  1315. // copy of this software and associated documentation files (the
  1316. // "Software"), to deal in the Software without restriction, including
  1317. // without limitation the rights to use, copy, modify, merge, publish,
  1318. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1319. // persons to whom the Software is furnished to do so, subject to the
  1320. // following conditions:
  1321. //
  1322. // The above copyright notice and this permission notice shall be included
  1323. // in all copies or substantial portions of the Software.
  1324. //
  1325. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1326. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1327. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1328. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1329. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1330. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1331. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1332. // a duplex stream is just a stream that is both readable and writable.
  1333. // Since JS doesn't have multiple prototypal inheritance, this class
  1334. // prototypally inherits from Readable, and then parasitically from
  1335. // Writable.
  1336. /*<replacement>*/
  1337. var objectKeys = Object.keys || function (obj) {
  1338. var keys = [];
  1339. for (var key in obj) {
  1340. keys.push(key);
  1341. }
  1342. return keys;
  1343. };
  1344. /*</replacement>*/
  1345. module.exports = Duplex;
  1346. var Readable = require('./_stream_readable');
  1347. var Writable = require('./_stream_writable');
  1348. require('inherits')(Duplex, Readable);
  1349. {
  1350. // Allow the keys array to be GC'ed.
  1351. var keys = objectKeys(Writable.prototype);
  1352. for (var v = 0; v < keys.length; v++) {
  1353. var method = keys[v];
  1354. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  1355. }
  1356. }
  1357. function Duplex(options) {
  1358. if (!(this instanceof Duplex)) return new Duplex(options);
  1359. Readable.call(this, options);
  1360. Writable.call(this, options);
  1361. this.allowHalfOpen = true;
  1362. if (options) {
  1363. if (options.readable === false) this.readable = false;
  1364. if (options.writable === false) this.writable = false;
  1365. if (options.allowHalfOpen === false) {
  1366. this.allowHalfOpen = false;
  1367. this.once('end', onend);
  1368. }
  1369. }
  1370. }
  1371. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  1372. // making it explicit this property is not enumerable
  1373. // because otherwise some prototype manipulation in
  1374. // userland will fail
  1375. enumerable: false,
  1376. get: function get() {
  1377. return this._writableState.highWaterMark;
  1378. }
  1379. });
  1380. Object.defineProperty(Duplex.prototype, 'writableBuffer', {
  1381. // making it explicit this property is not enumerable
  1382. // because otherwise some prototype manipulation in
  1383. // userland will fail
  1384. enumerable: false,
  1385. get: function get() {
  1386. return this._writableState && this._writableState.getBuffer();
  1387. }
  1388. });
  1389. Object.defineProperty(Duplex.prototype, 'writableLength', {
  1390. // making it explicit this property is not enumerable
  1391. // because otherwise some prototype manipulation in
  1392. // userland will fail
  1393. enumerable: false,
  1394. get: function get() {
  1395. return this._writableState.length;
  1396. }
  1397. }); // the no-half-open enforcer
  1398. function onend() {
  1399. // If the writable side ended, then we're ok.
  1400. if (this._writableState.ended) return; // no more data can be written.
  1401. // But allow more writes to happen in this tick.
  1402. process.nextTick(onEndNT, this);
  1403. }
  1404. function onEndNT(self) {
  1405. self.end();
  1406. }
  1407. Object.defineProperty(Duplex.prototype, 'destroyed', {
  1408. // making it explicit this property is not enumerable
  1409. // because otherwise some prototype manipulation in
  1410. // userland will fail
  1411. enumerable: false,
  1412. get: function get() {
  1413. if (this._readableState === undefined || this._writableState === undefined) {
  1414. return false;
  1415. }
  1416. return this._readableState.destroyed && this._writableState.destroyed;
  1417. },
  1418. set: function set(value) {
  1419. // we ignore the value if the stream
  1420. // has not been initialized yet
  1421. if (this._readableState === undefined || this._writableState === undefined) {
  1422. return;
  1423. } // backward compatibility, the user is explicitly
  1424. // managing destroyed
  1425. this._readableState.destroyed = value;
  1426. this._writableState.destroyed = value;
  1427. }
  1428. });
  1429. }, function(modId) { var map = {"./_stream_readable":1682324647567,"./_stream_writable":1682324647574}; return __REQUIRE__(map[modId], modId); })
  1430. __DEFINE__(1682324647574, function(require, module, exports) {
  1431. // Copyright Joyent, Inc. and other Node contributors.
  1432. //
  1433. // Permission is hereby granted, free of charge, to any person obtaining a
  1434. // copy of this software and associated documentation files (the
  1435. // "Software"), to deal in the Software without restriction, including
  1436. // without limitation the rights to use, copy, modify, merge, publish,
  1437. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1438. // persons to whom the Software is furnished to do so, subject to the
  1439. // following conditions:
  1440. //
  1441. // The above copyright notice and this permission notice shall be included
  1442. // in all copies or substantial portions of the Software.
  1443. //
  1444. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1445. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1446. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1447. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1448. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1449. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1450. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1451. // A bit simpler than readable streams.
  1452. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  1453. // the drain event emission and buffering.
  1454. module.exports = Writable;
  1455. /* <replacement> */
  1456. function WriteReq(chunk, encoding, cb) {
  1457. this.chunk = chunk;
  1458. this.encoding = encoding;
  1459. this.callback = cb;
  1460. this.next = null;
  1461. } // It seems a linked list but it is not
  1462. // there will be only 2 of these for each stream
  1463. function CorkedRequest(state) {
  1464. var _this = this;
  1465. this.next = null;
  1466. this.entry = null;
  1467. this.finish = function () {
  1468. onCorkedFinish(_this, state);
  1469. };
  1470. }
  1471. /* </replacement> */
  1472. /*<replacement>*/
  1473. var Duplex;
  1474. /*</replacement>*/
  1475. Writable.WritableState = WritableState;
  1476. /*<replacement>*/
  1477. var internalUtil = {
  1478. deprecate: require('util-deprecate')
  1479. };
  1480. /*</replacement>*/
  1481. /*<replacement>*/
  1482. var Stream = require('./internal/streams/stream');
  1483. /*</replacement>*/
  1484. var Buffer = require('buffer').Buffer;
  1485. var OurUint8Array = global.Uint8Array || function () {};
  1486. function _uint8ArrayToBuffer(chunk) {
  1487. return Buffer.from(chunk);
  1488. }
  1489. function _isUint8Array(obj) {
  1490. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  1491. }
  1492. var destroyImpl = require('./internal/streams/destroy');
  1493. var _require = require('./internal/streams/state'),
  1494. getHighWaterMark = _require.getHighWaterMark;
  1495. var _require$codes = require('../errors').codes,
  1496. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  1497. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  1498. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  1499. ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
  1500. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
  1501. ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
  1502. ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
  1503. ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
  1504. var errorOrDestroy = destroyImpl.errorOrDestroy;
  1505. require('inherits')(Writable, Stream);
  1506. function nop() {}
  1507. function WritableState(options, stream, isDuplex) {
  1508. Duplex = Duplex || require('./_stream_duplex');
  1509. options = options || {}; // Duplex streams are both readable and writable, but share
  1510. // the same options object.
  1511. // However, some cases require setting options to different
  1512. // values for the readable and the writable sides of the duplex stream,
  1513. // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
  1514. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
  1515. // contains buffers or objects.
  1516. this.objectMode = !!options.objectMode;
  1517. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
  1518. // Note: 0 is a valid value, means that we always return false if
  1519. // the entire buffer is not flushed immediately on write()
  1520. this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
  1521. this.finalCalled = false; // drain event flag.
  1522. this.needDrain = false; // at the start of calling end()
  1523. this.ending = false; // when end() has been called, and returned
  1524. this.ended = false; // when 'finish' is emitted
  1525. this.finished = false; // has it been destroyed
  1526. this.destroyed = false; // should we decode strings into buffers before passing to _write?
  1527. // this is here so that some node-core streams can optimize string
  1528. // handling at a lower level.
  1529. var noDecode = options.decodeStrings === false;
  1530. this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
  1531. // encoding is 'binary' so we have to make this configurable.
  1532. // Everything else in the universe uses 'utf8', though.
  1533. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
  1534. // of how much we're waiting to get pushed to some underlying
  1535. // socket or file.
  1536. this.length = 0; // a flag to see when we're in the middle of a write.
  1537. this.writing = false; // when true all writes will be buffered until .uncork() call
  1538. this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
  1539. // or on a later tick. We set this to true at first, because any
  1540. // actions that shouldn't happen until "later" should generally also
  1541. // not happen before the first write call.
  1542. this.sync = true; // a flag to know if we're processing previously buffered items, which
  1543. // may call the _write() callback in the same tick, so that we don't
  1544. // end up in an overlapped onwrite situation.
  1545. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
  1546. this.onwrite = function (er) {
  1547. onwrite(stream, er);
  1548. }; // the callback that the user supplies to write(chunk,encoding,cb)
  1549. this.writecb = null; // the amount that is being written when _write is called.
  1550. this.writelen = 0;
  1551. this.bufferedRequest = null;
  1552. this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
  1553. // this must be 0 before 'finish' can be emitted
  1554. this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
  1555. // This is relevant for synchronous Transform streams
  1556. this.prefinished = false; // True if the error was already emitted and should not be thrown again
  1557. this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
  1558. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
  1559. this.autoDestroy = !!options.autoDestroy; // count buffered requests
  1560. this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
  1561. // one allocated and free to use, and we maintain at most two
  1562. this.corkedRequestsFree = new CorkedRequest(this);
  1563. }
  1564. WritableState.prototype.getBuffer = function getBuffer() {
  1565. var current = this.bufferedRequest;
  1566. var out = [];
  1567. while (current) {
  1568. out.push(current);
  1569. current = current.next;
  1570. }
  1571. return out;
  1572. };
  1573. (function () {
  1574. try {
  1575. Object.defineProperty(WritableState.prototype, 'buffer', {
  1576. get: internalUtil.deprecate(function writableStateBufferGetter() {
  1577. return this.getBuffer();
  1578. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  1579. });
  1580. } catch (_) {}
  1581. })(); // Test _writableState for inheritance to account for Duplex streams,
  1582. // whose prototype chain only points to Readable.
  1583. var realHasInstance;
  1584. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  1585. realHasInstance = Function.prototype[Symbol.hasInstance];
  1586. Object.defineProperty(Writable, Symbol.hasInstance, {
  1587. value: function value(object) {
  1588. if (realHasInstance.call(this, object)) return true;
  1589. if (this !== Writable) return false;
  1590. return object && object._writableState instanceof WritableState;
  1591. }
  1592. });
  1593. } else {
  1594. realHasInstance = function realHasInstance(object) {
  1595. return object instanceof this;
  1596. };
  1597. }
  1598. function Writable(options) {
  1599. Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
  1600. // `realHasInstance` is necessary because using plain `instanceof`
  1601. // would return false, as no `_writableState` property is attached.
  1602. // Trying to use the custom `instanceof` for Writable here will also break the
  1603. // Node.js LazyTransform implementation, which has a non-trivial getter for
  1604. // `_writableState` that would lead to infinite recursion.
  1605. // Checking for a Stream.Duplex instance is faster here instead of inside
  1606. // the WritableState constructor, at least with V8 6.5
  1607. var isDuplex = this instanceof Duplex;
  1608. if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
  1609. this._writableState = new WritableState(options, this, isDuplex); // legacy.
  1610. this.writable = true;
  1611. if (options) {
  1612. if (typeof options.write === 'function') this._write = options.write;
  1613. if (typeof options.writev === 'function') this._writev = options.writev;
  1614. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  1615. if (typeof options.final === 'function') this._final = options.final;
  1616. }
  1617. Stream.call(this);
  1618. } // Otherwise people can pipe Writable streams, which is just wrong.
  1619. Writable.prototype.pipe = function () {
  1620. errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
  1621. };
  1622. function writeAfterEnd(stream, cb) {
  1623. var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
  1624. errorOrDestroy(stream, er);
  1625. process.nextTick(cb, er);
  1626. } // Checks that a user-supplied chunk is valid, especially for the particular
  1627. // mode the stream is in. Currently this means that `null` is never accepted
  1628. // and undefined/non-string values are only allowed in object mode.
  1629. function validChunk(stream, state, chunk, cb) {
  1630. var er;
  1631. if (chunk === null) {
  1632. er = new ERR_STREAM_NULL_VALUES();
  1633. } else if (typeof chunk !== 'string' && !state.objectMode) {
  1634. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
  1635. }
  1636. if (er) {
  1637. errorOrDestroy(stream, er);
  1638. process.nextTick(cb, er);
  1639. return false;
  1640. }
  1641. return true;
  1642. }
  1643. Writable.prototype.write = function (chunk, encoding, cb) {
  1644. var state = this._writableState;
  1645. var ret = false;
  1646. var isBuf = !state.objectMode && _isUint8Array(chunk);
  1647. if (isBuf && !Buffer.isBuffer(chunk)) {
  1648. chunk = _uint8ArrayToBuffer(chunk);
  1649. }
  1650. if (typeof encoding === 'function') {
  1651. cb = encoding;
  1652. encoding = null;
  1653. }
  1654. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  1655. if (typeof cb !== 'function') cb = nop;
  1656. if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  1657. state.pendingcb++;
  1658. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  1659. }
  1660. return ret;
  1661. };
  1662. Writable.prototype.cork = function () {
  1663. this._writableState.corked++;
  1664. };
  1665. Writable.prototype.uncork = function () {
  1666. var state = this._writableState;
  1667. if (state.corked) {
  1668. state.corked--;
  1669. if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  1670. }
  1671. };
  1672. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  1673. // node::ParseEncoding() requires lower case.
  1674. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  1675. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
  1676. this._writableState.defaultEncoding = encoding;
  1677. return this;
  1678. };
  1679. Object.defineProperty(Writable.prototype, 'writableBuffer', {
  1680. // making it explicit this property is not enumerable
  1681. // because otherwise some prototype manipulation in
  1682. // userland will fail
  1683. enumerable: false,
  1684. get: function get() {
  1685. return this._writableState && this._writableState.getBuffer();
  1686. }
  1687. });
  1688. function decodeChunk(state, chunk, encoding) {
  1689. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  1690. chunk = Buffer.from(chunk, encoding);
  1691. }
  1692. return chunk;
  1693. }
  1694. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  1695. // making it explicit this property is not enumerable
  1696. // because otherwise some prototype manipulation in
  1697. // userland will fail
  1698. enumerable: false,
  1699. get: function get() {
  1700. return this._writableState.highWaterMark;
  1701. }
  1702. }); // if we're already writing something, then just put this
  1703. // in the queue, and wait our turn. Otherwise, call _write
  1704. // If we return false, then we need a drain event, so set that flag.
  1705. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  1706. if (!isBuf) {
  1707. var newChunk = decodeChunk(state, chunk, encoding);
  1708. if (chunk !== newChunk) {
  1709. isBuf = true;
  1710. encoding = 'buffer';
  1711. chunk = newChunk;
  1712. }
  1713. }
  1714. var len = state.objectMode ? 1 : chunk.length;
  1715. state.length += len;
  1716. var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
  1717. if (!ret) state.needDrain = true;
  1718. if (state.writing || state.corked) {
  1719. var last = state.lastBufferedRequest;
  1720. state.lastBufferedRequest = {
  1721. chunk: chunk,
  1722. encoding: encoding,
  1723. isBuf: isBuf,
  1724. callback: cb,
  1725. next: null
  1726. };
  1727. if (last) {
  1728. last.next = state.lastBufferedRequest;
  1729. } else {
  1730. state.bufferedRequest = state.lastBufferedRequest;
  1731. }
  1732. state.bufferedRequestCount += 1;
  1733. } else {
  1734. doWrite(stream, state, false, len, chunk, encoding, cb);
  1735. }
  1736. return ret;
  1737. }
  1738. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  1739. state.writelen = len;
  1740. state.writecb = cb;
  1741. state.writing = true;
  1742. state.sync = true;
  1743. if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  1744. state.sync = false;
  1745. }
  1746. function onwriteError(stream, state, sync, er, cb) {
  1747. --state.pendingcb;
  1748. if (sync) {
  1749. // defer the callback if we are being called synchronously
  1750. // to avoid piling up things on the stack
  1751. process.nextTick(cb, er); // this can emit finish, and it will always happen
  1752. // after error
  1753. process.nextTick(finishMaybe, stream, state);
  1754. stream._writableState.errorEmitted = true;
  1755. errorOrDestroy(stream, er);
  1756. } else {
  1757. // the caller expect this to happen before if
  1758. // it is async
  1759. cb(er);
  1760. stream._writableState.errorEmitted = true;
  1761. errorOrDestroy(stream, er); // this can emit finish, but finish must
  1762. // always follow error
  1763. finishMaybe(stream, state);
  1764. }
  1765. }
  1766. function onwriteStateUpdate(state) {
  1767. state.writing = false;
  1768. state.writecb = null;
  1769. state.length -= state.writelen;
  1770. state.writelen = 0;
  1771. }
  1772. function onwrite(stream, er) {
  1773. var state = stream._writableState;
  1774. var sync = state.sync;
  1775. var cb = state.writecb;
  1776. if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
  1777. onwriteStateUpdate(state);
  1778. if (er) onwriteError(stream, state, sync, er, cb);else {
  1779. // Check if we're actually ready to finish, but don't emit yet
  1780. var finished = needFinish(state) || stream.destroyed;
  1781. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  1782. clearBuffer(stream, state);
  1783. }
  1784. if (sync) {
  1785. process.nextTick(afterWrite, stream, state, finished, cb);
  1786. } else {
  1787. afterWrite(stream, state, finished, cb);
  1788. }
  1789. }
  1790. }
  1791. function afterWrite(stream, state, finished, cb) {
  1792. if (!finished) onwriteDrain(stream, state);
  1793. state.pendingcb--;
  1794. cb();
  1795. finishMaybe(stream, state);
  1796. } // Must force callback to be called on nextTick, so that we don't
  1797. // emit 'drain' before the write() consumer gets the 'false' return
  1798. // value, and has a chance to attach a 'drain' listener.
  1799. function onwriteDrain(stream, state) {
  1800. if (state.length === 0 && state.needDrain) {
  1801. state.needDrain = false;
  1802. stream.emit('drain');
  1803. }
  1804. } // if there's something in the buffer waiting, then process it
  1805. function clearBuffer(stream, state) {
  1806. state.bufferProcessing = true;
  1807. var entry = state.bufferedRequest;
  1808. if (stream._writev && entry && entry.next) {
  1809. // Fast case, write everything using _writev()
  1810. var l = state.bufferedRequestCount;
  1811. var buffer = new Array(l);
  1812. var holder = state.corkedRequestsFree;
  1813. holder.entry = entry;
  1814. var count = 0;
  1815. var allBuffers = true;
  1816. while (entry) {
  1817. buffer[count] = entry;
  1818. if (!entry.isBuf) allBuffers = false;
  1819. entry = entry.next;
  1820. count += 1;
  1821. }
  1822. buffer.allBuffers = allBuffers;
  1823. doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
  1824. // as the hot path ends with doWrite
  1825. state.pendingcb++;
  1826. state.lastBufferedRequest = null;
  1827. if (holder.next) {
  1828. state.corkedRequestsFree = holder.next;
  1829. holder.next = null;
  1830. } else {
  1831. state.corkedRequestsFree = new CorkedRequest(state);
  1832. }
  1833. state.bufferedRequestCount = 0;
  1834. } else {
  1835. // Slow case, write chunks one-by-one
  1836. while (entry) {
  1837. var chunk = entry.chunk;
  1838. var encoding = entry.encoding;
  1839. var cb = entry.callback;
  1840. var len = state.objectMode ? 1 : chunk.length;
  1841. doWrite(stream, state, false, len, chunk, encoding, cb);
  1842. entry = entry.next;
  1843. state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
  1844. // it means that we need to wait until it does.
  1845. // also, that means that the chunk and cb are currently
  1846. // being processed, so move the buffer counter past them.
  1847. if (state.writing) {
  1848. break;
  1849. }
  1850. }
  1851. if (entry === null) state.lastBufferedRequest = null;
  1852. }
  1853. state.bufferedRequest = entry;
  1854. state.bufferProcessing = false;
  1855. }
  1856. Writable.prototype._write = function (chunk, encoding, cb) {
  1857. cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
  1858. };
  1859. Writable.prototype._writev = null;
  1860. Writable.prototype.end = function (chunk, encoding, cb) {
  1861. var state = this._writableState;
  1862. if (typeof chunk === 'function') {
  1863. cb = chunk;
  1864. chunk = null;
  1865. encoding = null;
  1866. } else if (typeof encoding === 'function') {
  1867. cb = encoding;
  1868. encoding = null;
  1869. }
  1870. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
  1871. if (state.corked) {
  1872. state.corked = 1;
  1873. this.uncork();
  1874. } // ignore unnecessary end() calls.
  1875. if (!state.ending) endWritable(this, state, cb);
  1876. return this;
  1877. };
  1878. Object.defineProperty(Writable.prototype, 'writableLength', {
  1879. // making it explicit this property is not enumerable
  1880. // because otherwise some prototype manipulation in
  1881. // userland will fail
  1882. enumerable: false,
  1883. get: function get() {
  1884. return this._writableState.length;
  1885. }
  1886. });
  1887. function needFinish(state) {
  1888. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  1889. }
  1890. function callFinal(stream, state) {
  1891. stream._final(function (err) {
  1892. state.pendingcb--;
  1893. if (err) {
  1894. errorOrDestroy(stream, err);
  1895. }
  1896. state.prefinished = true;
  1897. stream.emit('prefinish');
  1898. finishMaybe(stream, state);
  1899. });
  1900. }
  1901. function prefinish(stream, state) {
  1902. if (!state.prefinished && !state.finalCalled) {
  1903. if (typeof stream._final === 'function' && !state.destroyed) {
  1904. state.pendingcb++;
  1905. state.finalCalled = true;
  1906. process.nextTick(callFinal, stream, state);
  1907. } else {
  1908. state.prefinished = true;
  1909. stream.emit('prefinish');
  1910. }
  1911. }
  1912. }
  1913. function finishMaybe(stream, state) {
  1914. var need = needFinish(state);
  1915. if (need) {
  1916. prefinish(stream, state);
  1917. if (state.pendingcb === 0) {
  1918. state.finished = true;
  1919. stream.emit('finish');
  1920. if (state.autoDestroy) {
  1921. // In case of duplex streams we need a way to detect
  1922. // if the readable side is ready for autoDestroy as well
  1923. var rState = stream._readableState;
  1924. if (!rState || rState.autoDestroy && rState.endEmitted) {
  1925. stream.destroy();
  1926. }
  1927. }
  1928. }
  1929. }
  1930. return need;
  1931. }
  1932. function endWritable(stream, state, cb) {
  1933. state.ending = true;
  1934. finishMaybe(stream, state);
  1935. if (cb) {
  1936. if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
  1937. }
  1938. state.ended = true;
  1939. stream.writable = false;
  1940. }
  1941. function onCorkedFinish(corkReq, state, err) {
  1942. var entry = corkReq.entry;
  1943. corkReq.entry = null;
  1944. while (entry) {
  1945. var cb = entry.callback;
  1946. state.pendingcb--;
  1947. cb(err);
  1948. entry = entry.next;
  1949. } // reuse the free corkReq.
  1950. state.corkedRequestsFree.next = corkReq;
  1951. }
  1952. Object.defineProperty(Writable.prototype, 'destroyed', {
  1953. // making it explicit this property is not enumerable
  1954. // because otherwise some prototype manipulation in
  1955. // userland will fail
  1956. enumerable: false,
  1957. get: function get() {
  1958. if (this._writableState === undefined) {
  1959. return false;
  1960. }
  1961. return this._writableState.destroyed;
  1962. },
  1963. set: function set(value) {
  1964. // we ignore the value if the stream
  1965. // has not been initialized yet
  1966. if (!this._writableState) {
  1967. return;
  1968. } // backward compatibility, the user is explicitly
  1969. // managing destroyed
  1970. this._writableState.destroyed = value;
  1971. }
  1972. });
  1973. Writable.prototype.destroy = destroyImpl.destroy;
  1974. Writable.prototype._undestroy = destroyImpl.undestroy;
  1975. Writable.prototype._destroy = function (err, cb) {
  1976. cb(err);
  1977. };
  1978. }, function(modId) { var map = {"./internal/streams/stream":1682324647568,"./internal/streams/destroy":1682324647570,"./internal/streams/state":1682324647571,"../errors":1682324647572,"./_stream_duplex":1682324647573}; return __REQUIRE__(map[modId], modId); })
  1979. __DEFINE__(1682324647575, function(require, module, exports) {
  1980. var _Object$setPrototypeO;
  1981. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  1982. var finished = require('./end-of-stream');
  1983. var kLastResolve = Symbol('lastResolve');
  1984. var kLastReject = Symbol('lastReject');
  1985. var kError = Symbol('error');
  1986. var kEnded = Symbol('ended');
  1987. var kLastPromise = Symbol('lastPromise');
  1988. var kHandlePromise = Symbol('handlePromise');
  1989. var kStream = Symbol('stream');
  1990. function createIterResult(value, done) {
  1991. return {
  1992. value: value,
  1993. done: done
  1994. };
  1995. }
  1996. function readAndResolve(iter) {
  1997. var resolve = iter[kLastResolve];
  1998. if (resolve !== null) {
  1999. var data = iter[kStream].read(); // we defer if data is null
  2000. // we can be expecting either 'end' or
  2001. // 'error'
  2002. if (data !== null) {
  2003. iter[kLastPromise] = null;
  2004. iter[kLastResolve] = null;
  2005. iter[kLastReject] = null;
  2006. resolve(createIterResult(data, false));
  2007. }
  2008. }
  2009. }
  2010. function onReadable(iter) {
  2011. // we wait for the next tick, because it might
  2012. // emit an error with process.nextTick
  2013. process.nextTick(readAndResolve, iter);
  2014. }
  2015. function wrapForNext(lastPromise, iter) {
  2016. return function (resolve, reject) {
  2017. lastPromise.then(function () {
  2018. if (iter[kEnded]) {
  2019. resolve(createIterResult(undefined, true));
  2020. return;
  2021. }
  2022. iter[kHandlePromise](resolve, reject);
  2023. }, reject);
  2024. };
  2025. }
  2026. var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
  2027. var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
  2028. get stream() {
  2029. return this[kStream];
  2030. },
  2031. next: function next() {
  2032. var _this = this;
  2033. // if we have detected an error in the meanwhile
  2034. // reject straight away
  2035. var error = this[kError];
  2036. if (error !== null) {
  2037. return Promise.reject(error);
  2038. }
  2039. if (this[kEnded]) {
  2040. return Promise.resolve(createIterResult(undefined, true));
  2041. }
  2042. if (this[kStream].destroyed) {
  2043. // We need to defer via nextTick because if .destroy(err) is
  2044. // called, the error will be emitted via nextTick, and
  2045. // we cannot guarantee that there is no error lingering around
  2046. // waiting to be emitted.
  2047. return new Promise(function (resolve, reject) {
  2048. process.nextTick(function () {
  2049. if (_this[kError]) {
  2050. reject(_this[kError]);
  2051. } else {
  2052. resolve(createIterResult(undefined, true));
  2053. }
  2054. });
  2055. });
  2056. } // if we have multiple next() calls
  2057. // we will wait for the previous Promise to finish
  2058. // this logic is optimized to support for await loops,
  2059. // where next() is only called once at a time
  2060. var lastPromise = this[kLastPromise];
  2061. var promise;
  2062. if (lastPromise) {
  2063. promise = new Promise(wrapForNext(lastPromise, this));
  2064. } else {
  2065. // fast path needed to support multiple this.push()
  2066. // without triggering the next() queue
  2067. var data = this[kStream].read();
  2068. if (data !== null) {
  2069. return Promise.resolve(createIterResult(data, false));
  2070. }
  2071. promise = new Promise(this[kHandlePromise]);
  2072. }
  2073. this[kLastPromise] = promise;
  2074. return promise;
  2075. }
  2076. }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
  2077. return this;
  2078. }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
  2079. var _this2 = this;
  2080. // destroy(err, cb) is a private API
  2081. // we can guarantee we have that here, because we control the
  2082. // Readable class this is attached to
  2083. return new Promise(function (resolve, reject) {
  2084. _this2[kStream].destroy(null, function (err) {
  2085. if (err) {
  2086. reject(err);
  2087. return;
  2088. }
  2089. resolve(createIterResult(undefined, true));
  2090. });
  2091. });
  2092. }), _Object$setPrototypeO), AsyncIteratorPrototype);
  2093. var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
  2094. var _Object$create;
  2095. var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
  2096. value: stream,
  2097. writable: true
  2098. }), _defineProperty(_Object$create, kLastResolve, {
  2099. value: null,
  2100. writable: true
  2101. }), _defineProperty(_Object$create, kLastReject, {
  2102. value: null,
  2103. writable: true
  2104. }), _defineProperty(_Object$create, kError, {
  2105. value: null,
  2106. writable: true
  2107. }), _defineProperty(_Object$create, kEnded, {
  2108. value: stream._readableState.endEmitted,
  2109. writable: true
  2110. }), _defineProperty(_Object$create, kHandlePromise, {
  2111. value: function value(resolve, reject) {
  2112. var data = iterator[kStream].read();
  2113. if (data) {
  2114. iterator[kLastPromise] = null;
  2115. iterator[kLastResolve] = null;
  2116. iterator[kLastReject] = null;
  2117. resolve(createIterResult(data, false));
  2118. } else {
  2119. iterator[kLastResolve] = resolve;
  2120. iterator[kLastReject] = reject;
  2121. }
  2122. },
  2123. writable: true
  2124. }), _Object$create));
  2125. iterator[kLastPromise] = null;
  2126. finished(stream, function (err) {
  2127. if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
  2128. var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
  2129. // returned by next() and store the error
  2130. if (reject !== null) {
  2131. iterator[kLastPromise] = null;
  2132. iterator[kLastResolve] = null;
  2133. iterator[kLastReject] = null;
  2134. reject(err);
  2135. }
  2136. iterator[kError] = err;
  2137. return;
  2138. }
  2139. var resolve = iterator[kLastResolve];
  2140. if (resolve !== null) {
  2141. iterator[kLastPromise] = null;
  2142. iterator[kLastResolve] = null;
  2143. iterator[kLastReject] = null;
  2144. resolve(createIterResult(undefined, true));
  2145. }
  2146. iterator[kEnded] = true;
  2147. });
  2148. stream.on('readable', onReadable.bind(null, iterator));
  2149. return iterator;
  2150. };
  2151. module.exports = createReadableStreamAsyncIterator;
  2152. }, function(modId) { var map = {"./end-of-stream":1682324647576}; return __REQUIRE__(map[modId], modId); })
  2153. __DEFINE__(1682324647576, function(require, module, exports) {
  2154. // Ported from https://github.com/mafintosh/end-of-stream with
  2155. // permission from the author, Mathias Buus (@mafintosh).
  2156. var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
  2157. function once(callback) {
  2158. var called = false;
  2159. return function () {
  2160. if (called) return;
  2161. called = true;
  2162. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2163. args[_key] = arguments[_key];
  2164. }
  2165. callback.apply(this, args);
  2166. };
  2167. }
  2168. function noop() {}
  2169. function isRequest(stream) {
  2170. return stream.setHeader && typeof stream.abort === 'function';
  2171. }
  2172. function eos(stream, opts, callback) {
  2173. if (typeof opts === 'function') return eos(stream, null, opts);
  2174. if (!opts) opts = {};
  2175. callback = once(callback || noop);
  2176. var readable = opts.readable || opts.readable !== false && stream.readable;
  2177. var writable = opts.writable || opts.writable !== false && stream.writable;
  2178. var onlegacyfinish = function onlegacyfinish() {
  2179. if (!stream.writable) onfinish();
  2180. };
  2181. var writableEnded = stream._writableState && stream._writableState.finished;
  2182. var onfinish = function onfinish() {
  2183. writable = false;
  2184. writableEnded = true;
  2185. if (!readable) callback.call(stream);
  2186. };
  2187. var readableEnded = stream._readableState && stream._readableState.endEmitted;
  2188. var onend = function onend() {
  2189. readable = false;
  2190. readableEnded = true;
  2191. if (!writable) callback.call(stream);
  2192. };
  2193. var onerror = function onerror(err) {
  2194. callback.call(stream, err);
  2195. };
  2196. var onclose = function onclose() {
  2197. var err;
  2198. if (readable && !readableEnded) {
  2199. if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  2200. return callback.call(stream, err);
  2201. }
  2202. if (writable && !writableEnded) {
  2203. if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  2204. return callback.call(stream, err);
  2205. }
  2206. };
  2207. var onrequest = function onrequest() {
  2208. stream.req.on('finish', onfinish);
  2209. };
  2210. if (isRequest(stream)) {
  2211. stream.on('complete', onfinish);
  2212. stream.on('abort', onclose);
  2213. if (stream.req) onrequest();else stream.on('request', onrequest);
  2214. } else if (writable && !stream._writableState) {
  2215. // legacy streams
  2216. stream.on('end', onlegacyfinish);
  2217. stream.on('close', onlegacyfinish);
  2218. }
  2219. stream.on('end', onend);
  2220. stream.on('finish', onfinish);
  2221. if (opts.error !== false) stream.on('error', onerror);
  2222. stream.on('close', onclose);
  2223. return function () {
  2224. stream.removeListener('complete', onfinish);
  2225. stream.removeListener('abort', onclose);
  2226. stream.removeListener('request', onrequest);
  2227. if (stream.req) stream.req.removeListener('finish', onfinish);
  2228. stream.removeListener('end', onlegacyfinish);
  2229. stream.removeListener('close', onlegacyfinish);
  2230. stream.removeListener('finish', onfinish);
  2231. stream.removeListener('end', onend);
  2232. stream.removeListener('error', onerror);
  2233. stream.removeListener('close', onclose);
  2234. };
  2235. }
  2236. module.exports = eos;
  2237. }, function(modId) { var map = {"../../../errors":1682324647572}; return __REQUIRE__(map[modId], modId); })
  2238. __DEFINE__(1682324647577, function(require, module, exports) {
  2239. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  2240. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  2241. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  2242. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  2243. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  2244. var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;
  2245. function from(Readable, iterable, opts) {
  2246. var iterator;
  2247. if (iterable && typeof iterable.next === 'function') {
  2248. iterator = iterable;
  2249. } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);
  2250. var readable = new Readable(_objectSpread({
  2251. objectMode: true
  2252. }, opts)); // Reading boolean to protect against _read
  2253. // being called before last iteration completion.
  2254. var reading = false;
  2255. readable._read = function () {
  2256. if (!reading) {
  2257. reading = true;
  2258. next();
  2259. }
  2260. };
  2261. function next() {
  2262. return _next2.apply(this, arguments);
  2263. }
  2264. function _next2() {
  2265. _next2 = _asyncToGenerator(function* () {
  2266. try {
  2267. var _ref = yield iterator.next(),
  2268. value = _ref.value,
  2269. done = _ref.done;
  2270. if (done) {
  2271. readable.push(null);
  2272. } else if (readable.push((yield value))) {
  2273. next();
  2274. } else {
  2275. reading = false;
  2276. }
  2277. } catch (err) {
  2278. readable.destroy(err);
  2279. }
  2280. });
  2281. return _next2.apply(this, arguments);
  2282. }
  2283. return readable;
  2284. }
  2285. module.exports = from;
  2286. }, function(modId) { var map = {"../../../errors":1682324647572}; return __REQUIRE__(map[modId], modId); })
  2287. __DEFINE__(1682324647578, function(require, module, exports) {
  2288. // Copyright Joyent, Inc. and other Node contributors.
  2289. //
  2290. // Permission is hereby granted, free of charge, to any person obtaining a
  2291. // copy of this software and associated documentation files (the
  2292. // "Software"), to deal in the Software without restriction, including
  2293. // without limitation the rights to use, copy, modify, merge, publish,
  2294. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2295. // persons to whom the Software is furnished to do so, subject to the
  2296. // following conditions:
  2297. //
  2298. // The above copyright notice and this permission notice shall be included
  2299. // in all copies or substantial portions of the Software.
  2300. //
  2301. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2302. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2303. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2304. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2305. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2306. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2307. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2308. // a transform stream is a readable/writable stream where you do
  2309. // something with the data. Sometimes it's called a "filter",
  2310. // but that's not a great name for it, since that implies a thing where
  2311. // some bits pass through, and others are simply ignored. (That would
  2312. // be a valid example of a transform, of course.)
  2313. //
  2314. // While the output is causally related to the input, it's not a
  2315. // necessarily symmetric or synchronous transformation. For example,
  2316. // a zlib stream might take multiple plain-text writes(), and then
  2317. // emit a single compressed chunk some time in the future.
  2318. //
  2319. // Here's how this works:
  2320. //
  2321. // The Transform stream has all the aspects of the readable and writable
  2322. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  2323. // internally, and returns false if there's a lot of pending writes
  2324. // buffered up. When you call read(), that calls _read(n) until
  2325. // there's enough pending readable data buffered up.
  2326. //
  2327. // In a transform stream, the written data is placed in a buffer. When
  2328. // _read(n) is called, it transforms the queued up data, calling the
  2329. // buffered _write cb's as it consumes chunks. If consuming a single
  2330. // written chunk would result in multiple output chunks, then the first
  2331. // outputted bit calls the readcb, and subsequent chunks just go into
  2332. // the read buffer, and will cause it to emit 'readable' if necessary.
  2333. //
  2334. // This way, back-pressure is actually determined by the reading side,
  2335. // since _read has to be called to start processing a new chunk. However,
  2336. // a pathological inflate type of transform can cause excessive buffering
  2337. // here. For example, imagine a stream where every byte of input is
  2338. // interpreted as an integer from 0-255, and then results in that many
  2339. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  2340. // 1kb of data being output. In this case, you could write a very small
  2341. // amount of input, and end up with a very large amount of output. In
  2342. // such a pathological inflating mechanism, there'd be no way to tell
  2343. // the system to stop doing the transform. A single 4MB write could
  2344. // cause the system to run out of memory.
  2345. //
  2346. // However, even in such a pathological case, only a single written chunk
  2347. // would be consumed, and then the rest would wait (un-transformed) until
  2348. // the results of the previous transformed chunk were consumed.
  2349. module.exports = Transform;
  2350. var _require$codes = require('../errors').codes,
  2351. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  2352. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  2353. ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
  2354. ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
  2355. var Duplex = require('./_stream_duplex');
  2356. require('inherits')(Transform, Duplex);
  2357. function afterTransform(er, data) {
  2358. var ts = this._transformState;
  2359. ts.transforming = false;
  2360. var cb = ts.writecb;
  2361. if (cb === null) {
  2362. return this.emit('error', new ERR_MULTIPLE_CALLBACK());
  2363. }
  2364. ts.writechunk = null;
  2365. ts.writecb = null;
  2366. if (data != null) // single equals check for both `null` and `undefined`
  2367. this.push(data);
  2368. cb(er);
  2369. var rs = this._readableState;
  2370. rs.reading = false;
  2371. if (rs.needReadable || rs.length < rs.highWaterMark) {
  2372. this._read(rs.highWaterMark);
  2373. }
  2374. }
  2375. function Transform(options) {
  2376. if (!(this instanceof Transform)) return new Transform(options);
  2377. Duplex.call(this, options);
  2378. this._transformState = {
  2379. afterTransform: afterTransform.bind(this),
  2380. needTransform: false,
  2381. transforming: false,
  2382. writecb: null,
  2383. writechunk: null,
  2384. writeencoding: null
  2385. }; // start out asking for a readable event once data is transformed.
  2386. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
  2387. // that Readable wants before the first _read call, so unset the
  2388. // sync guard flag.
  2389. this._readableState.sync = false;
  2390. if (options) {
  2391. if (typeof options.transform === 'function') this._transform = options.transform;
  2392. if (typeof options.flush === 'function') this._flush = options.flush;
  2393. } // When the writable side finishes, then flush out anything remaining.
  2394. this.on('prefinish', prefinish);
  2395. }
  2396. function prefinish() {
  2397. var _this = this;
  2398. if (typeof this._flush === 'function' && !this._readableState.destroyed) {
  2399. this._flush(function (er, data) {
  2400. done(_this, er, data);
  2401. });
  2402. } else {
  2403. done(this, null, null);
  2404. }
  2405. }
  2406. Transform.prototype.push = function (chunk, encoding) {
  2407. this._transformState.needTransform = false;
  2408. return Duplex.prototype.push.call(this, chunk, encoding);
  2409. }; // This is the part where you do stuff!
  2410. // override this function in implementation classes.
  2411. // 'chunk' is an input chunk.
  2412. //
  2413. // Call `push(newChunk)` to pass along transformed output
  2414. // to the readable side. You may call 'push' zero or more times.
  2415. //
  2416. // Call `cb(err)` when you are done with this chunk. If you pass
  2417. // an error, then that'll put the hurt on the whole operation. If you
  2418. // never call cb(), then you'll never get another chunk.
  2419. Transform.prototype._transform = function (chunk, encoding, cb) {
  2420. cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
  2421. };
  2422. Transform.prototype._write = function (chunk, encoding, cb) {
  2423. var ts = this._transformState;
  2424. ts.writecb = cb;
  2425. ts.writechunk = chunk;
  2426. ts.writeencoding = encoding;
  2427. if (!ts.transforming) {
  2428. var rs = this._readableState;
  2429. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  2430. }
  2431. }; // Doesn't matter what the args are here.
  2432. // _transform does all the work.
  2433. // That we got here means that the readable side wants more data.
  2434. Transform.prototype._read = function (n) {
  2435. var ts = this._transformState;
  2436. if (ts.writechunk !== null && !ts.transforming) {
  2437. ts.transforming = true;
  2438. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  2439. } else {
  2440. // mark that we need a transform, so that any data that comes in
  2441. // will get processed, now that we've asked for it.
  2442. ts.needTransform = true;
  2443. }
  2444. };
  2445. Transform.prototype._destroy = function (err, cb) {
  2446. Duplex.prototype._destroy.call(this, err, function (err2) {
  2447. cb(err2);
  2448. });
  2449. };
  2450. function done(stream, er, data) {
  2451. if (er) return stream.emit('error', er);
  2452. if (data != null) // single equals check for both `null` and `undefined`
  2453. stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
  2454. // if there's nothing in the write buffer, then that means
  2455. // that nothing more will ever be provided
  2456. if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
  2457. if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
  2458. return stream.push(null);
  2459. }
  2460. }, function(modId) { var map = {"../errors":1682324647572,"./_stream_duplex":1682324647573}; return __REQUIRE__(map[modId], modId); })
  2461. __DEFINE__(1682324647579, function(require, module, exports) {
  2462. // Copyright Joyent, Inc. and other Node contributors.
  2463. //
  2464. // Permission is hereby granted, free of charge, to any person obtaining a
  2465. // copy of this software and associated documentation files (the
  2466. // "Software"), to deal in the Software without restriction, including
  2467. // without limitation the rights to use, copy, modify, merge, publish,
  2468. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2469. // persons to whom the Software is furnished to do so, subject to the
  2470. // following conditions:
  2471. //
  2472. // The above copyright notice and this permission notice shall be included
  2473. // in all copies or substantial portions of the Software.
  2474. //
  2475. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2476. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2477. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2478. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2479. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2480. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2481. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2482. // a passthrough stream.
  2483. // basically just the most minimal sort of Transform stream.
  2484. // Every written chunk gets output as-is.
  2485. module.exports = PassThrough;
  2486. var Transform = require('./_stream_transform');
  2487. require('inherits')(PassThrough, Transform);
  2488. function PassThrough(options) {
  2489. if (!(this instanceof PassThrough)) return new PassThrough(options);
  2490. Transform.call(this, options);
  2491. }
  2492. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  2493. cb(null, chunk);
  2494. };
  2495. }, function(modId) { var map = {"./_stream_transform":1682324647578}; return __REQUIRE__(map[modId], modId); })
  2496. __DEFINE__(1682324647580, function(require, module, exports) {
  2497. // Ported from https://github.com/mafintosh/pump with
  2498. // permission from the author, Mathias Buus (@mafintosh).
  2499. var eos;
  2500. function once(callback) {
  2501. var called = false;
  2502. return function () {
  2503. if (called) return;
  2504. called = true;
  2505. callback.apply(void 0, arguments);
  2506. };
  2507. }
  2508. var _require$codes = require('../../../errors').codes,
  2509. ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
  2510. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
  2511. function noop(err) {
  2512. // Rethrow the error if it exists to avoid swallowing it
  2513. if (err) throw err;
  2514. }
  2515. function isRequest(stream) {
  2516. return stream.setHeader && typeof stream.abort === 'function';
  2517. }
  2518. function destroyer(stream, reading, writing, callback) {
  2519. callback = once(callback);
  2520. var closed = false;
  2521. stream.on('close', function () {
  2522. closed = true;
  2523. });
  2524. if (eos === undefined) eos = require('./end-of-stream');
  2525. eos(stream, {
  2526. readable: reading,
  2527. writable: writing
  2528. }, function (err) {
  2529. if (err) return callback(err);
  2530. closed = true;
  2531. callback();
  2532. });
  2533. var destroyed = false;
  2534. return function (err) {
  2535. if (closed) return;
  2536. if (destroyed) return;
  2537. destroyed = true; // request.destroy just do .end - .abort is what we want
  2538. if (isRequest(stream)) return stream.abort();
  2539. if (typeof stream.destroy === 'function') return stream.destroy();
  2540. callback(err || new ERR_STREAM_DESTROYED('pipe'));
  2541. };
  2542. }
  2543. function call(fn) {
  2544. fn();
  2545. }
  2546. function pipe(from, to) {
  2547. return from.pipe(to);
  2548. }
  2549. function popCallback(streams) {
  2550. if (!streams.length) return noop;
  2551. if (typeof streams[streams.length - 1] !== 'function') return noop;
  2552. return streams.pop();
  2553. }
  2554. function pipeline() {
  2555. for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
  2556. streams[_key] = arguments[_key];
  2557. }
  2558. var callback = popCallback(streams);
  2559. if (Array.isArray(streams[0])) streams = streams[0];
  2560. if (streams.length < 2) {
  2561. throw new ERR_MISSING_ARGS('streams');
  2562. }
  2563. var error;
  2564. var destroys = streams.map(function (stream, i) {
  2565. var reading = i < streams.length - 1;
  2566. var writing = i > 0;
  2567. return destroyer(stream, reading, writing, function (err) {
  2568. if (!error) error = err;
  2569. if (err) destroys.forEach(call);
  2570. if (reading) return;
  2571. destroys.forEach(call);
  2572. callback(error);
  2573. });
  2574. });
  2575. return streams.reduce(pipe);
  2576. }
  2577. module.exports = pipeline;
  2578. }, function(modId) { var map = {"../../../errors":1682324647572,"./end-of-stream":1682324647576}; return __REQUIRE__(map[modId], modId); })
  2579. return __REQUIRE__(1682324647566);
  2580. })()
  2581. //miniprogram-npm-outsideDeps=["stream","events","buffer","util","inherits","string_decoder/","util-deprecate"]
  2582. //# sourceMappingURL=index.js.map