index.js 197 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542
  1. var global$1 = (typeof global !== "undefined" ? global :
  2. typeof self !== "undefined" ? self :
  3. typeof window !== "undefined" ? window : {});
  4. var lookup = [];
  5. var revLookup = [];
  6. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  7. var inited = false;
  8. function init () {
  9. inited = true;
  10. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  11. for (var i = 0, len = code.length; i < len; ++i) {
  12. lookup[i] = code[i];
  13. revLookup[code.charCodeAt(i)] = i;
  14. }
  15. revLookup['-'.charCodeAt(0)] = 62;
  16. revLookup['_'.charCodeAt(0)] = 63;
  17. }
  18. function toByteArray (b64) {
  19. if (!inited) {
  20. init();
  21. }
  22. var i, j, l, tmp, placeHolders, arr;
  23. var len = b64.length;
  24. if (len % 4 > 0) {
  25. throw new Error('Invalid string. Length must be a multiple of 4')
  26. }
  27. // the number of equal signs (place holders)
  28. // if there are two placeholders, than the two characters before it
  29. // represent one byte
  30. // if there is only one, then the three characters before it represent 2 bytes
  31. // this is just a cheap hack to not do indexOf twice
  32. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  33. // base64 is 4/3 + up to two characters of the original data
  34. arr = new Arr(len * 3 / 4 - placeHolders);
  35. // if there are placeholders, only get up to the last complete 4 chars
  36. l = placeHolders > 0 ? len - 4 : len;
  37. var L = 0;
  38. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  39. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  40. arr[L++] = (tmp >> 16) & 0xFF;
  41. arr[L++] = (tmp >> 8) & 0xFF;
  42. arr[L++] = tmp & 0xFF;
  43. }
  44. if (placeHolders === 2) {
  45. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  46. arr[L++] = tmp & 0xFF;
  47. } else if (placeHolders === 1) {
  48. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  49. arr[L++] = (tmp >> 8) & 0xFF;
  50. arr[L++] = tmp & 0xFF;
  51. }
  52. return arr
  53. }
  54. function tripletToBase64 (num) {
  55. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  56. }
  57. function encodeChunk (uint8, start, end) {
  58. var tmp;
  59. var output = [];
  60. for (var i = start; i < end; i += 3) {
  61. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
  62. output.push(tripletToBase64(tmp));
  63. }
  64. return output.join('')
  65. }
  66. function fromByteArray (uint8) {
  67. if (!inited) {
  68. init();
  69. }
  70. var tmp;
  71. var len = uint8.length;
  72. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  73. var output = '';
  74. var parts = [];
  75. var maxChunkLength = 16383; // must be multiple of 3
  76. // go through the array every three bytes, we'll deal with trailing stuff later
  77. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  78. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
  79. }
  80. // pad the end with zeros, but make sure to not forget the extra bytes
  81. if (extraBytes === 1) {
  82. tmp = uint8[len - 1];
  83. output += lookup[tmp >> 2];
  84. output += lookup[(tmp << 4) & 0x3F];
  85. output += '==';
  86. } else if (extraBytes === 2) {
  87. tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
  88. output += lookup[tmp >> 10];
  89. output += lookup[(tmp >> 4) & 0x3F];
  90. output += lookup[(tmp << 2) & 0x3F];
  91. output += '=';
  92. }
  93. parts.push(output);
  94. return parts.join('')
  95. }
  96. function read (buffer, offset, isLE, mLen, nBytes) {
  97. var e, m;
  98. var eLen = nBytes * 8 - mLen - 1;
  99. var eMax = (1 << eLen) - 1;
  100. var eBias = eMax >> 1;
  101. var nBits = -7;
  102. var i = isLE ? (nBytes - 1) : 0;
  103. var d = isLE ? -1 : 1;
  104. var s = buffer[offset + i];
  105. i += d;
  106. e = s & ((1 << (-nBits)) - 1);
  107. s >>= (-nBits);
  108. nBits += eLen;
  109. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  110. m = e & ((1 << (-nBits)) - 1);
  111. e >>= (-nBits);
  112. nBits += mLen;
  113. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  114. if (e === 0) {
  115. e = 1 - eBias;
  116. } else if (e === eMax) {
  117. return m ? NaN : ((s ? -1 : 1) * Infinity)
  118. } else {
  119. m = m + Math.pow(2, mLen);
  120. e = e - eBias;
  121. }
  122. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  123. }
  124. function write (buffer, value, offset, isLE, mLen, nBytes) {
  125. var e, m, c;
  126. var eLen = nBytes * 8 - mLen - 1;
  127. var eMax = (1 << eLen) - 1;
  128. var eBias = eMax >> 1;
  129. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  130. var i = isLE ? 0 : (nBytes - 1);
  131. var d = isLE ? 1 : -1;
  132. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  133. value = Math.abs(value);
  134. if (isNaN(value) || value === Infinity) {
  135. m = isNaN(value) ? 1 : 0;
  136. e = eMax;
  137. } else {
  138. e = Math.floor(Math.log(value) / Math.LN2);
  139. if (value * (c = Math.pow(2, -e)) < 1) {
  140. e--;
  141. c *= 2;
  142. }
  143. if (e + eBias >= 1) {
  144. value += rt / c;
  145. } else {
  146. value += rt * Math.pow(2, 1 - eBias);
  147. }
  148. if (value * c >= 2) {
  149. e++;
  150. c /= 2;
  151. }
  152. if (e + eBias >= eMax) {
  153. m = 0;
  154. e = eMax;
  155. } else if (e + eBias >= 1) {
  156. m = (value * c - 1) * Math.pow(2, mLen);
  157. e = e + eBias;
  158. } else {
  159. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  160. e = 0;
  161. }
  162. }
  163. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  164. e = (e << mLen) | m;
  165. eLen += mLen;
  166. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  167. buffer[offset + i - d] |= s * 128;
  168. }
  169. var toString = {}.toString;
  170. var isArray$1 = Array.isArray || function (arr) {
  171. return toString.call(arr) == '[object Array]';
  172. };
  173. var INSPECT_MAX_BYTES = 50;
  174. /**
  175. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  176. * === true Use Uint8Array implementation (fastest)
  177. * === false Use Object implementation (most compatible, even IE6)
  178. *
  179. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  180. * Opera 11.6+, iOS 4.2+.
  181. *
  182. * Due to various browser bugs, sometimes the Object implementation will be used even
  183. * when the browser supports typed arrays.
  184. *
  185. * Note:
  186. *
  187. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  188. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  189. *
  190. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  191. *
  192. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  193. * incorrect length in some situations.
  194. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  195. * get the Object implementation, which is slower but behaves correctly.
  196. */
  197. Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
  198. ? global$1.TYPED_ARRAY_SUPPORT
  199. : true;
  200. /*
  201. * Export kMaxLength after typed array support is determined.
  202. */
  203. kMaxLength();
  204. function kMaxLength () {
  205. return Buffer.TYPED_ARRAY_SUPPORT
  206. ? 0x7fffffff
  207. : 0x3fffffff
  208. }
  209. function createBuffer (that, length) {
  210. if (kMaxLength() < length) {
  211. throw new RangeError('Invalid typed array length')
  212. }
  213. if (Buffer.TYPED_ARRAY_SUPPORT) {
  214. // Return an augmented `Uint8Array` instance, for best performance
  215. that = new Uint8Array(length);
  216. that.__proto__ = Buffer.prototype;
  217. } else {
  218. // Fallback: Return an object instance of the Buffer class
  219. if (that === null) {
  220. that = new Buffer(length);
  221. }
  222. that.length = length;
  223. }
  224. return that
  225. }
  226. /**
  227. * The Buffer constructor returns instances of `Uint8Array` that have their
  228. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  229. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  230. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  231. * returns a single octet.
  232. *
  233. * The `Uint8Array` prototype remains unmodified.
  234. */
  235. function Buffer (arg, encodingOrOffset, length) {
  236. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  237. return new Buffer(arg, encodingOrOffset, length)
  238. }
  239. // Common case.
  240. if (typeof arg === 'number') {
  241. if (typeof encodingOrOffset === 'string') {
  242. throw new Error(
  243. 'If encoding is specified then the first argument must be a string'
  244. )
  245. }
  246. return allocUnsafe(this, arg)
  247. }
  248. return from(this, arg, encodingOrOffset, length)
  249. }
  250. Buffer.poolSize = 8192; // not used by this implementation
  251. // TODO: Legacy, not needed anymore. Remove in next major version.
  252. Buffer._augment = function (arr) {
  253. arr.__proto__ = Buffer.prototype;
  254. return arr
  255. };
  256. function from (that, value, encodingOrOffset, length) {
  257. if (typeof value === 'number') {
  258. throw new TypeError('"value" argument must not be a number')
  259. }
  260. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  261. return fromArrayBuffer(that, value, encodingOrOffset, length)
  262. }
  263. if (typeof value === 'string') {
  264. return fromString(that, value, encodingOrOffset)
  265. }
  266. return fromObject(that, value)
  267. }
  268. /**
  269. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  270. * if value is a number.
  271. * Buffer.from(str[, encoding])
  272. * Buffer.from(array)
  273. * Buffer.from(buffer)
  274. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  275. **/
  276. Buffer.from = function (value, encodingOrOffset, length) {
  277. return from(null, value, encodingOrOffset, length)
  278. };
  279. if (Buffer.TYPED_ARRAY_SUPPORT) {
  280. Buffer.prototype.__proto__ = Uint8Array.prototype;
  281. Buffer.__proto__ = Uint8Array;
  282. if (typeof Symbol !== 'undefined' && Symbol.species &&
  283. Buffer[Symbol.species] === Buffer) ;
  284. }
  285. function assertSize (size) {
  286. if (typeof size !== 'number') {
  287. throw new TypeError('"size" argument must be a number')
  288. } else if (size < 0) {
  289. throw new RangeError('"size" argument must not be negative')
  290. }
  291. }
  292. function alloc (that, size, fill, encoding) {
  293. assertSize(size);
  294. if (size <= 0) {
  295. return createBuffer(that, size)
  296. }
  297. if (fill !== undefined) {
  298. // Only pay attention to encoding if it's a string. This
  299. // prevents accidentally sending in a number that would
  300. // be interpretted as a start offset.
  301. return typeof encoding === 'string'
  302. ? createBuffer(that, size).fill(fill, encoding)
  303. : createBuffer(that, size).fill(fill)
  304. }
  305. return createBuffer(that, size)
  306. }
  307. /**
  308. * Creates a new filled Buffer instance.
  309. * alloc(size[, fill[, encoding]])
  310. **/
  311. Buffer.alloc = function (size, fill, encoding) {
  312. return alloc(null, size, fill, encoding)
  313. };
  314. function allocUnsafe (that, size) {
  315. assertSize(size);
  316. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  317. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  318. for (var i = 0; i < size; ++i) {
  319. that[i] = 0;
  320. }
  321. }
  322. return that
  323. }
  324. /**
  325. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  326. * */
  327. Buffer.allocUnsafe = function (size) {
  328. return allocUnsafe(null, size)
  329. };
  330. /**
  331. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  332. */
  333. Buffer.allocUnsafeSlow = function (size) {
  334. return allocUnsafe(null, size)
  335. };
  336. function fromString (that, string, encoding) {
  337. if (typeof encoding !== 'string' || encoding === '') {
  338. encoding = 'utf8';
  339. }
  340. if (!Buffer.isEncoding(encoding)) {
  341. throw new TypeError('"encoding" must be a valid string encoding')
  342. }
  343. var length = byteLength(string, encoding) | 0;
  344. that = createBuffer(that, length);
  345. var actual = that.write(string, encoding);
  346. if (actual !== length) {
  347. // Writing a hex string, for example, that contains invalid characters will
  348. // cause everything after the first invalid character to be ignored. (e.g.
  349. // 'abxxcd' will be treated as 'ab')
  350. that = that.slice(0, actual);
  351. }
  352. return that
  353. }
  354. function fromArrayLike (that, array) {
  355. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  356. that = createBuffer(that, length);
  357. for (var i = 0; i < length; i += 1) {
  358. that[i] = array[i] & 255;
  359. }
  360. return that
  361. }
  362. function fromArrayBuffer (that, array, byteOffset, length) {
  363. array.byteLength; // this throws if `array` is not a valid ArrayBuffer
  364. if (byteOffset < 0 || array.byteLength < byteOffset) {
  365. throw new RangeError('\'offset\' is out of bounds')
  366. }
  367. if (array.byteLength < byteOffset + (length || 0)) {
  368. throw new RangeError('\'length\' is out of bounds')
  369. }
  370. if (byteOffset === undefined && length === undefined) {
  371. array = new Uint8Array(array);
  372. } else if (length === undefined) {
  373. array = new Uint8Array(array, byteOffset);
  374. } else {
  375. array = new Uint8Array(array, byteOffset, length);
  376. }
  377. if (Buffer.TYPED_ARRAY_SUPPORT) {
  378. // Return an augmented `Uint8Array` instance, for best performance
  379. that = array;
  380. that.__proto__ = Buffer.prototype;
  381. } else {
  382. // Fallback: Return an object instance of the Buffer class
  383. that = fromArrayLike(that, array);
  384. }
  385. return that
  386. }
  387. function fromObject (that, obj) {
  388. if (internalIsBuffer(obj)) {
  389. var len = checked(obj.length) | 0;
  390. that = createBuffer(that, len);
  391. if (that.length === 0) {
  392. return that
  393. }
  394. obj.copy(that, 0, 0, len);
  395. return that
  396. }
  397. if (obj) {
  398. if ((typeof ArrayBuffer !== 'undefined' &&
  399. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  400. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  401. return createBuffer(that, 0)
  402. }
  403. return fromArrayLike(that, obj)
  404. }
  405. if (obj.type === 'Buffer' && isArray$1(obj.data)) {
  406. return fromArrayLike(that, obj.data)
  407. }
  408. }
  409. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  410. }
  411. function checked (length) {
  412. // Note: cannot use `length < kMaxLength()` here because that fails when
  413. // length is NaN (which is otherwise coerced to zero.)
  414. if (length >= kMaxLength()) {
  415. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  416. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  417. }
  418. return length | 0
  419. }
  420. Buffer.isBuffer = isBuffer;
  421. function internalIsBuffer (b) {
  422. return !!(b != null && b._isBuffer)
  423. }
  424. Buffer.compare = function compare (a, b) {
  425. if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
  426. throw new TypeError('Arguments must be Buffers')
  427. }
  428. if (a === b) return 0
  429. var x = a.length;
  430. var y = b.length;
  431. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  432. if (a[i] !== b[i]) {
  433. x = a[i];
  434. y = b[i];
  435. break
  436. }
  437. }
  438. if (x < y) return -1
  439. if (y < x) return 1
  440. return 0
  441. };
  442. Buffer.isEncoding = function isEncoding (encoding) {
  443. switch (String(encoding).toLowerCase()) {
  444. case 'hex':
  445. case 'utf8':
  446. case 'utf-8':
  447. case 'ascii':
  448. case 'latin1':
  449. case 'binary':
  450. case 'base64':
  451. case 'ucs2':
  452. case 'ucs-2':
  453. case 'utf16le':
  454. case 'utf-16le':
  455. return true
  456. default:
  457. return false
  458. }
  459. };
  460. Buffer.concat = function concat (list, length) {
  461. if (!isArray$1(list)) {
  462. throw new TypeError('"list" argument must be an Array of Buffers')
  463. }
  464. if (list.length === 0) {
  465. return Buffer.alloc(0)
  466. }
  467. var i;
  468. if (length === undefined) {
  469. length = 0;
  470. for (i = 0; i < list.length; ++i) {
  471. length += list[i].length;
  472. }
  473. }
  474. var buffer = Buffer.allocUnsafe(length);
  475. var pos = 0;
  476. for (i = 0; i < list.length; ++i) {
  477. var buf = list[i];
  478. if (!internalIsBuffer(buf)) {
  479. throw new TypeError('"list" argument must be an Array of Buffers')
  480. }
  481. buf.copy(buffer, pos);
  482. pos += buf.length;
  483. }
  484. return buffer
  485. };
  486. function byteLength (string, encoding) {
  487. if (internalIsBuffer(string)) {
  488. return string.length
  489. }
  490. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  491. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  492. return string.byteLength
  493. }
  494. if (typeof string !== 'string') {
  495. string = '' + string;
  496. }
  497. var len = string.length;
  498. if (len === 0) return 0
  499. // Use a for loop to avoid recursion
  500. var loweredCase = false;
  501. for (;;) {
  502. switch (encoding) {
  503. case 'ascii':
  504. case 'latin1':
  505. case 'binary':
  506. return len
  507. case 'utf8':
  508. case 'utf-8':
  509. case undefined:
  510. return utf8ToBytes(string).length
  511. case 'ucs2':
  512. case 'ucs-2':
  513. case 'utf16le':
  514. case 'utf-16le':
  515. return len * 2
  516. case 'hex':
  517. return len >>> 1
  518. case 'base64':
  519. return base64ToBytes(string).length
  520. default:
  521. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  522. encoding = ('' + encoding).toLowerCase();
  523. loweredCase = true;
  524. }
  525. }
  526. }
  527. Buffer.byteLength = byteLength;
  528. function slowToString (encoding, start, end) {
  529. var loweredCase = false;
  530. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  531. // property of a typed array.
  532. // This behaves neither like String nor Uint8Array in that we set start/end
  533. // to their upper/lower bounds if the value passed is out of range.
  534. // undefined is handled specially as per ECMA-262 6th Edition,
  535. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  536. if (start === undefined || start < 0) {
  537. start = 0;
  538. }
  539. // Return early if start > this.length. Done here to prevent potential uint32
  540. // coercion fail below.
  541. if (start > this.length) {
  542. return ''
  543. }
  544. if (end === undefined || end > this.length) {
  545. end = this.length;
  546. }
  547. if (end <= 0) {
  548. return ''
  549. }
  550. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  551. end >>>= 0;
  552. start >>>= 0;
  553. if (end <= start) {
  554. return ''
  555. }
  556. if (!encoding) encoding = 'utf8';
  557. while (true) {
  558. switch (encoding) {
  559. case 'hex':
  560. return hexSlice(this, start, end)
  561. case 'utf8':
  562. case 'utf-8':
  563. return utf8Slice(this, start, end)
  564. case 'ascii':
  565. return asciiSlice(this, start, end)
  566. case 'latin1':
  567. case 'binary':
  568. return latin1Slice(this, start, end)
  569. case 'base64':
  570. return base64Slice(this, start, end)
  571. case 'ucs2':
  572. case 'ucs-2':
  573. case 'utf16le':
  574. case 'utf-16le':
  575. return utf16leSlice(this, start, end)
  576. default:
  577. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  578. encoding = (encoding + '').toLowerCase();
  579. loweredCase = true;
  580. }
  581. }
  582. }
  583. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  584. // Buffer instances.
  585. Buffer.prototype._isBuffer = true;
  586. function swap (b, n, m) {
  587. var i = b[n];
  588. b[n] = b[m];
  589. b[m] = i;
  590. }
  591. Buffer.prototype.swap16 = function swap16 () {
  592. var len = this.length;
  593. if (len % 2 !== 0) {
  594. throw new RangeError('Buffer size must be a multiple of 16-bits')
  595. }
  596. for (var i = 0; i < len; i += 2) {
  597. swap(this, i, i + 1);
  598. }
  599. return this
  600. };
  601. Buffer.prototype.swap32 = function swap32 () {
  602. var len = this.length;
  603. if (len % 4 !== 0) {
  604. throw new RangeError('Buffer size must be a multiple of 32-bits')
  605. }
  606. for (var i = 0; i < len; i += 4) {
  607. swap(this, i, i + 3);
  608. swap(this, i + 1, i + 2);
  609. }
  610. return this
  611. };
  612. Buffer.prototype.swap64 = function swap64 () {
  613. var len = this.length;
  614. if (len % 8 !== 0) {
  615. throw new RangeError('Buffer size must be a multiple of 64-bits')
  616. }
  617. for (var i = 0; i < len; i += 8) {
  618. swap(this, i, i + 7);
  619. swap(this, i + 1, i + 6);
  620. swap(this, i + 2, i + 5);
  621. swap(this, i + 3, i + 4);
  622. }
  623. return this
  624. };
  625. Buffer.prototype.toString = function toString () {
  626. var length = this.length | 0;
  627. if (length === 0) return ''
  628. if (arguments.length === 0) return utf8Slice(this, 0, length)
  629. return slowToString.apply(this, arguments)
  630. };
  631. Buffer.prototype.equals = function equals (b) {
  632. if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
  633. if (this === b) return true
  634. return Buffer.compare(this, b) === 0
  635. };
  636. Buffer.prototype.inspect = function inspect () {
  637. var str = '';
  638. var max = INSPECT_MAX_BYTES;
  639. if (this.length > 0) {
  640. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
  641. if (this.length > max) str += ' ... ';
  642. }
  643. return '<Buffer ' + str + '>'
  644. };
  645. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  646. if (!internalIsBuffer(target)) {
  647. throw new TypeError('Argument must be a Buffer')
  648. }
  649. if (start === undefined) {
  650. start = 0;
  651. }
  652. if (end === undefined) {
  653. end = target ? target.length : 0;
  654. }
  655. if (thisStart === undefined) {
  656. thisStart = 0;
  657. }
  658. if (thisEnd === undefined) {
  659. thisEnd = this.length;
  660. }
  661. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  662. throw new RangeError('out of range index')
  663. }
  664. if (thisStart >= thisEnd && start >= end) {
  665. return 0
  666. }
  667. if (thisStart >= thisEnd) {
  668. return -1
  669. }
  670. if (start >= end) {
  671. return 1
  672. }
  673. start >>>= 0;
  674. end >>>= 0;
  675. thisStart >>>= 0;
  676. thisEnd >>>= 0;
  677. if (this === target) return 0
  678. var x = thisEnd - thisStart;
  679. var y = end - start;
  680. var len = Math.min(x, y);
  681. var thisCopy = this.slice(thisStart, thisEnd);
  682. var targetCopy = target.slice(start, end);
  683. for (var i = 0; i < len; ++i) {
  684. if (thisCopy[i] !== targetCopy[i]) {
  685. x = thisCopy[i];
  686. y = targetCopy[i];
  687. break
  688. }
  689. }
  690. if (x < y) return -1
  691. if (y < x) return 1
  692. return 0
  693. };
  694. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  695. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  696. //
  697. // Arguments:
  698. // - buffer - a Buffer to search
  699. // - val - a string, Buffer, or number
  700. // - byteOffset - an index into `buffer`; will be clamped to an int32
  701. // - encoding - an optional encoding, relevant is val is a string
  702. // - dir - true for indexOf, false for lastIndexOf
  703. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  704. // Empty buffer means no match
  705. if (buffer.length === 0) return -1
  706. // Normalize byteOffset
  707. if (typeof byteOffset === 'string') {
  708. encoding = byteOffset;
  709. byteOffset = 0;
  710. } else if (byteOffset > 0x7fffffff) {
  711. byteOffset = 0x7fffffff;
  712. } else if (byteOffset < -0x80000000) {
  713. byteOffset = -0x80000000;
  714. }
  715. byteOffset = +byteOffset; // Coerce to Number.
  716. if (isNaN(byteOffset)) {
  717. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  718. byteOffset = dir ? 0 : (buffer.length - 1);
  719. }
  720. // Normalize byteOffset: negative offsets start from the end of the buffer
  721. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  722. if (byteOffset >= buffer.length) {
  723. if (dir) return -1
  724. else byteOffset = buffer.length - 1;
  725. } else if (byteOffset < 0) {
  726. if (dir) byteOffset = 0;
  727. else return -1
  728. }
  729. // Normalize val
  730. if (typeof val === 'string') {
  731. val = Buffer.from(val, encoding);
  732. }
  733. // Finally, search either indexOf (if dir is true) or lastIndexOf
  734. if (internalIsBuffer(val)) {
  735. // Special case: looking for empty string/buffer always fails
  736. if (val.length === 0) {
  737. return -1
  738. }
  739. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  740. } else if (typeof val === 'number') {
  741. val = val & 0xFF; // Search for a byte value [0-255]
  742. if (Buffer.TYPED_ARRAY_SUPPORT &&
  743. typeof Uint8Array.prototype.indexOf === 'function') {
  744. if (dir) {
  745. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  746. } else {
  747. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  748. }
  749. }
  750. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  751. }
  752. throw new TypeError('val must be string, number or Buffer')
  753. }
  754. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  755. var indexSize = 1;
  756. var arrLength = arr.length;
  757. var valLength = val.length;
  758. if (encoding !== undefined) {
  759. encoding = String(encoding).toLowerCase();
  760. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  761. encoding === 'utf16le' || encoding === 'utf-16le') {
  762. if (arr.length < 2 || val.length < 2) {
  763. return -1
  764. }
  765. indexSize = 2;
  766. arrLength /= 2;
  767. valLength /= 2;
  768. byteOffset /= 2;
  769. }
  770. }
  771. function read (buf, i) {
  772. if (indexSize === 1) {
  773. return buf[i]
  774. } else {
  775. return buf.readUInt16BE(i * indexSize)
  776. }
  777. }
  778. var i;
  779. if (dir) {
  780. var foundIndex = -1;
  781. for (i = byteOffset; i < arrLength; i++) {
  782. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  783. if (foundIndex === -1) foundIndex = i;
  784. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  785. } else {
  786. if (foundIndex !== -1) i -= i - foundIndex;
  787. foundIndex = -1;
  788. }
  789. }
  790. } else {
  791. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  792. for (i = byteOffset; i >= 0; i--) {
  793. var found = true;
  794. for (var j = 0; j < valLength; j++) {
  795. if (read(arr, i + j) !== read(val, j)) {
  796. found = false;
  797. break
  798. }
  799. }
  800. if (found) return i
  801. }
  802. }
  803. return -1
  804. }
  805. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  806. return this.indexOf(val, byteOffset, encoding) !== -1
  807. };
  808. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  809. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  810. };
  811. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  812. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  813. };
  814. function hexWrite (buf, string, offset, length) {
  815. offset = Number(offset) || 0;
  816. var remaining = buf.length - offset;
  817. if (!length) {
  818. length = remaining;
  819. } else {
  820. length = Number(length);
  821. if (length > remaining) {
  822. length = remaining;
  823. }
  824. }
  825. // must be an even number of digits
  826. var strLen = string.length;
  827. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  828. if (length > strLen / 2) {
  829. length = strLen / 2;
  830. }
  831. for (var i = 0; i < length; ++i) {
  832. var parsed = parseInt(string.substr(i * 2, 2), 16);
  833. if (isNaN(parsed)) return i
  834. buf[offset + i] = parsed;
  835. }
  836. return i
  837. }
  838. function utf8Write (buf, string, offset, length) {
  839. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  840. }
  841. function asciiWrite (buf, string, offset, length) {
  842. return blitBuffer(asciiToBytes(string), buf, offset, length)
  843. }
  844. function latin1Write (buf, string, offset, length) {
  845. return asciiWrite(buf, string, offset, length)
  846. }
  847. function base64Write (buf, string, offset, length) {
  848. return blitBuffer(base64ToBytes(string), buf, offset, length)
  849. }
  850. function ucs2Write (buf, string, offset, length) {
  851. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  852. }
  853. Buffer.prototype.write = function write (string, offset, length, encoding) {
  854. // Buffer#write(string)
  855. if (offset === undefined) {
  856. encoding = 'utf8';
  857. length = this.length;
  858. offset = 0;
  859. // Buffer#write(string, encoding)
  860. } else if (length === undefined && typeof offset === 'string') {
  861. encoding = offset;
  862. length = this.length;
  863. offset = 0;
  864. // Buffer#write(string, offset[, length][, encoding])
  865. } else if (isFinite(offset)) {
  866. offset = offset | 0;
  867. if (isFinite(length)) {
  868. length = length | 0;
  869. if (encoding === undefined) encoding = 'utf8';
  870. } else {
  871. encoding = length;
  872. length = undefined;
  873. }
  874. // legacy write(string, encoding, offset, length) - remove in v0.13
  875. } else {
  876. throw new Error(
  877. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  878. )
  879. }
  880. var remaining = this.length - offset;
  881. if (length === undefined || length > remaining) length = remaining;
  882. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  883. throw new RangeError('Attempt to write outside buffer bounds')
  884. }
  885. if (!encoding) encoding = 'utf8';
  886. var loweredCase = false;
  887. for (;;) {
  888. switch (encoding) {
  889. case 'hex':
  890. return hexWrite(this, string, offset, length)
  891. case 'utf8':
  892. case 'utf-8':
  893. return utf8Write(this, string, offset, length)
  894. case 'ascii':
  895. return asciiWrite(this, string, offset, length)
  896. case 'latin1':
  897. case 'binary':
  898. return latin1Write(this, string, offset, length)
  899. case 'base64':
  900. // Warning: maxLength not taken into account in base64Write
  901. return base64Write(this, string, offset, length)
  902. case 'ucs2':
  903. case 'ucs-2':
  904. case 'utf16le':
  905. case 'utf-16le':
  906. return ucs2Write(this, string, offset, length)
  907. default:
  908. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  909. encoding = ('' + encoding).toLowerCase();
  910. loweredCase = true;
  911. }
  912. }
  913. };
  914. Buffer.prototype.toJSON = function toJSON () {
  915. return {
  916. type: 'Buffer',
  917. data: Array.prototype.slice.call(this._arr || this, 0)
  918. }
  919. };
  920. function base64Slice (buf, start, end) {
  921. if (start === 0 && end === buf.length) {
  922. return fromByteArray(buf)
  923. } else {
  924. return fromByteArray(buf.slice(start, end))
  925. }
  926. }
  927. function utf8Slice (buf, start, end) {
  928. end = Math.min(buf.length, end);
  929. var res = [];
  930. var i = start;
  931. while (i < end) {
  932. var firstByte = buf[i];
  933. var codePoint = null;
  934. var bytesPerSequence = (firstByte > 0xEF) ? 4
  935. : (firstByte > 0xDF) ? 3
  936. : (firstByte > 0xBF) ? 2
  937. : 1;
  938. if (i + bytesPerSequence <= end) {
  939. var secondByte, thirdByte, fourthByte, tempCodePoint;
  940. switch (bytesPerSequence) {
  941. case 1:
  942. if (firstByte < 0x80) {
  943. codePoint = firstByte;
  944. }
  945. break
  946. case 2:
  947. secondByte = buf[i + 1];
  948. if ((secondByte & 0xC0) === 0x80) {
  949. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  950. if (tempCodePoint > 0x7F) {
  951. codePoint = tempCodePoint;
  952. }
  953. }
  954. break
  955. case 3:
  956. secondByte = buf[i + 1];
  957. thirdByte = buf[i + 2];
  958. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  959. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  960. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  961. codePoint = tempCodePoint;
  962. }
  963. }
  964. break
  965. case 4:
  966. secondByte = buf[i + 1];
  967. thirdByte = buf[i + 2];
  968. fourthByte = buf[i + 3];
  969. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  970. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  971. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  972. codePoint = tempCodePoint;
  973. }
  974. }
  975. }
  976. }
  977. if (codePoint === null) {
  978. // we did not generate a valid codePoint so insert a
  979. // replacement char (U+FFFD) and advance only 1 byte
  980. codePoint = 0xFFFD;
  981. bytesPerSequence = 1;
  982. } else if (codePoint > 0xFFFF) {
  983. // encode to utf16 (surrogate pair dance)
  984. codePoint -= 0x10000;
  985. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  986. codePoint = 0xDC00 | codePoint & 0x3FF;
  987. }
  988. res.push(codePoint);
  989. i += bytesPerSequence;
  990. }
  991. return decodeCodePointsArray(res)
  992. }
  993. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  994. // the lowest limit is Chrome, with 0x10000 args.
  995. // We go 1 magnitude less, for safety
  996. var MAX_ARGUMENTS_LENGTH = 0x1000;
  997. function decodeCodePointsArray (codePoints) {
  998. var len = codePoints.length;
  999. if (len <= MAX_ARGUMENTS_LENGTH) {
  1000. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1001. }
  1002. // Decode in chunks to avoid "call stack size exceeded".
  1003. var res = '';
  1004. var i = 0;
  1005. while (i < len) {
  1006. res += String.fromCharCode.apply(
  1007. String,
  1008. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1009. );
  1010. }
  1011. return res
  1012. }
  1013. function asciiSlice (buf, start, end) {
  1014. var ret = '';
  1015. end = Math.min(buf.length, end);
  1016. for (var i = start; i < end; ++i) {
  1017. ret += String.fromCharCode(buf[i] & 0x7F);
  1018. }
  1019. return ret
  1020. }
  1021. function latin1Slice (buf, start, end) {
  1022. var ret = '';
  1023. end = Math.min(buf.length, end);
  1024. for (var i = start; i < end; ++i) {
  1025. ret += String.fromCharCode(buf[i]);
  1026. }
  1027. return ret
  1028. }
  1029. function hexSlice (buf, start, end) {
  1030. var len = buf.length;
  1031. if (!start || start < 0) start = 0;
  1032. if (!end || end < 0 || end > len) end = len;
  1033. var out = '';
  1034. for (var i = start; i < end; ++i) {
  1035. out += toHex(buf[i]);
  1036. }
  1037. return out
  1038. }
  1039. function utf16leSlice (buf, start, end) {
  1040. var bytes = buf.slice(start, end);
  1041. var res = '';
  1042. for (var i = 0; i < bytes.length; i += 2) {
  1043. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  1044. }
  1045. return res
  1046. }
  1047. Buffer.prototype.slice = function slice (start, end) {
  1048. var len = this.length;
  1049. start = ~~start;
  1050. end = end === undefined ? len : ~~end;
  1051. if (start < 0) {
  1052. start += len;
  1053. if (start < 0) start = 0;
  1054. } else if (start > len) {
  1055. start = len;
  1056. }
  1057. if (end < 0) {
  1058. end += len;
  1059. if (end < 0) end = 0;
  1060. } else if (end > len) {
  1061. end = len;
  1062. }
  1063. if (end < start) end = start;
  1064. var newBuf;
  1065. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1066. newBuf = this.subarray(start, end);
  1067. newBuf.__proto__ = Buffer.prototype;
  1068. } else {
  1069. var sliceLen = end - start;
  1070. newBuf = new Buffer(sliceLen, undefined);
  1071. for (var i = 0; i < sliceLen; ++i) {
  1072. newBuf[i] = this[i + start];
  1073. }
  1074. }
  1075. return newBuf
  1076. };
  1077. /*
  1078. * Need to make sure that buffer isn't trying to write out of bounds.
  1079. */
  1080. function checkOffset (offset, ext, length) {
  1081. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1082. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1083. }
  1084. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1085. offset = offset | 0;
  1086. byteLength = byteLength | 0;
  1087. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1088. var val = this[offset];
  1089. var mul = 1;
  1090. var i = 0;
  1091. while (++i < byteLength && (mul *= 0x100)) {
  1092. val += this[offset + i] * mul;
  1093. }
  1094. return val
  1095. };
  1096. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1097. offset = offset | 0;
  1098. byteLength = byteLength | 0;
  1099. if (!noAssert) {
  1100. checkOffset(offset, byteLength, this.length);
  1101. }
  1102. var val = this[offset + --byteLength];
  1103. var mul = 1;
  1104. while (byteLength > 0 && (mul *= 0x100)) {
  1105. val += this[offset + --byteLength] * mul;
  1106. }
  1107. return val
  1108. };
  1109. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1110. if (!noAssert) checkOffset(offset, 1, this.length);
  1111. return this[offset]
  1112. };
  1113. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1114. if (!noAssert) checkOffset(offset, 2, this.length);
  1115. return this[offset] | (this[offset + 1] << 8)
  1116. };
  1117. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1118. if (!noAssert) checkOffset(offset, 2, this.length);
  1119. return (this[offset] << 8) | this[offset + 1]
  1120. };
  1121. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1122. if (!noAssert) checkOffset(offset, 4, this.length);
  1123. return ((this[offset]) |
  1124. (this[offset + 1] << 8) |
  1125. (this[offset + 2] << 16)) +
  1126. (this[offset + 3] * 0x1000000)
  1127. };
  1128. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1129. if (!noAssert) checkOffset(offset, 4, this.length);
  1130. return (this[offset] * 0x1000000) +
  1131. ((this[offset + 1] << 16) |
  1132. (this[offset + 2] << 8) |
  1133. this[offset + 3])
  1134. };
  1135. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1136. offset = offset | 0;
  1137. byteLength = byteLength | 0;
  1138. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1139. var val = this[offset];
  1140. var mul = 1;
  1141. var i = 0;
  1142. while (++i < byteLength && (mul *= 0x100)) {
  1143. val += this[offset + i] * mul;
  1144. }
  1145. mul *= 0x80;
  1146. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1147. return val
  1148. };
  1149. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1150. offset = offset | 0;
  1151. byteLength = byteLength | 0;
  1152. if (!noAssert) checkOffset(offset, byteLength, this.length);
  1153. var i = byteLength;
  1154. var mul = 1;
  1155. var val = this[offset + --i];
  1156. while (i > 0 && (mul *= 0x100)) {
  1157. val += this[offset + --i] * mul;
  1158. }
  1159. mul *= 0x80;
  1160. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  1161. return val
  1162. };
  1163. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1164. if (!noAssert) checkOffset(offset, 1, this.length);
  1165. if (!(this[offset] & 0x80)) return (this[offset])
  1166. return ((0xff - this[offset] + 1) * -1)
  1167. };
  1168. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1169. if (!noAssert) checkOffset(offset, 2, this.length);
  1170. var val = this[offset] | (this[offset + 1] << 8);
  1171. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1172. };
  1173. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1174. if (!noAssert) checkOffset(offset, 2, this.length);
  1175. var val = this[offset + 1] | (this[offset] << 8);
  1176. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1177. };
  1178. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1179. if (!noAssert) checkOffset(offset, 4, this.length);
  1180. return (this[offset]) |
  1181. (this[offset + 1] << 8) |
  1182. (this[offset + 2] << 16) |
  1183. (this[offset + 3] << 24)
  1184. };
  1185. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1186. if (!noAssert) checkOffset(offset, 4, this.length);
  1187. return (this[offset] << 24) |
  1188. (this[offset + 1] << 16) |
  1189. (this[offset + 2] << 8) |
  1190. (this[offset + 3])
  1191. };
  1192. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1193. if (!noAssert) checkOffset(offset, 4, this.length);
  1194. return read(this, offset, true, 23, 4)
  1195. };
  1196. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1197. if (!noAssert) checkOffset(offset, 4, this.length);
  1198. return read(this, offset, false, 23, 4)
  1199. };
  1200. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1201. if (!noAssert) checkOffset(offset, 8, this.length);
  1202. return read(this, offset, true, 52, 8)
  1203. };
  1204. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1205. if (!noAssert) checkOffset(offset, 8, this.length);
  1206. return read(this, offset, false, 52, 8)
  1207. };
  1208. function checkInt (buf, value, offset, ext, max, min) {
  1209. if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1210. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1211. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1212. }
  1213. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1214. value = +value;
  1215. offset = offset | 0;
  1216. byteLength = byteLength | 0;
  1217. if (!noAssert) {
  1218. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  1219. checkInt(this, value, offset, byteLength, maxBytes, 0);
  1220. }
  1221. var mul = 1;
  1222. var i = 0;
  1223. this[offset] = value & 0xFF;
  1224. while (++i < byteLength && (mul *= 0x100)) {
  1225. this[offset + i] = (value / mul) & 0xFF;
  1226. }
  1227. return offset + byteLength
  1228. };
  1229. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1230. value = +value;
  1231. offset = offset | 0;
  1232. byteLength = byteLength | 0;
  1233. if (!noAssert) {
  1234. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  1235. checkInt(this, value, offset, byteLength, maxBytes, 0);
  1236. }
  1237. var i = byteLength - 1;
  1238. var mul = 1;
  1239. this[offset + i] = value & 0xFF;
  1240. while (--i >= 0 && (mul *= 0x100)) {
  1241. this[offset + i] = (value / mul) & 0xFF;
  1242. }
  1243. return offset + byteLength
  1244. };
  1245. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1246. value = +value;
  1247. offset = offset | 0;
  1248. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  1249. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  1250. this[offset] = (value & 0xff);
  1251. return offset + 1
  1252. };
  1253. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1254. if (value < 0) value = 0xffff + value + 1;
  1255. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1256. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1257. (littleEndian ? i : 1 - i) * 8;
  1258. }
  1259. }
  1260. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1261. value = +value;
  1262. offset = offset | 0;
  1263. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  1264. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1265. this[offset] = (value & 0xff);
  1266. this[offset + 1] = (value >>> 8);
  1267. } else {
  1268. objectWriteUInt16(this, value, offset, true);
  1269. }
  1270. return offset + 2
  1271. };
  1272. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1273. value = +value;
  1274. offset = offset | 0;
  1275. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  1276. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1277. this[offset] = (value >>> 8);
  1278. this[offset + 1] = (value & 0xff);
  1279. } else {
  1280. objectWriteUInt16(this, value, offset, false);
  1281. }
  1282. return offset + 2
  1283. };
  1284. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1285. if (value < 0) value = 0xffffffff + value + 1;
  1286. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1287. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
  1288. }
  1289. }
  1290. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1291. value = +value;
  1292. offset = offset | 0;
  1293. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  1294. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1295. this[offset + 3] = (value >>> 24);
  1296. this[offset + 2] = (value >>> 16);
  1297. this[offset + 1] = (value >>> 8);
  1298. this[offset] = (value & 0xff);
  1299. } else {
  1300. objectWriteUInt32(this, value, offset, true);
  1301. }
  1302. return offset + 4
  1303. };
  1304. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1305. value = +value;
  1306. offset = offset | 0;
  1307. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  1308. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1309. this[offset] = (value >>> 24);
  1310. this[offset + 1] = (value >>> 16);
  1311. this[offset + 2] = (value >>> 8);
  1312. this[offset + 3] = (value & 0xff);
  1313. } else {
  1314. objectWriteUInt32(this, value, offset, false);
  1315. }
  1316. return offset + 4
  1317. };
  1318. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1319. value = +value;
  1320. offset = offset | 0;
  1321. if (!noAssert) {
  1322. var limit = Math.pow(2, 8 * byteLength - 1);
  1323. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  1324. }
  1325. var i = 0;
  1326. var mul = 1;
  1327. var sub = 0;
  1328. this[offset] = value & 0xFF;
  1329. while (++i < byteLength && (mul *= 0x100)) {
  1330. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1331. sub = 1;
  1332. }
  1333. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  1334. }
  1335. return offset + byteLength
  1336. };
  1337. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1338. value = +value;
  1339. offset = offset | 0;
  1340. if (!noAssert) {
  1341. var limit = Math.pow(2, 8 * byteLength - 1);
  1342. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  1343. }
  1344. var i = byteLength - 1;
  1345. var mul = 1;
  1346. var sub = 0;
  1347. this[offset + i] = value & 0xFF;
  1348. while (--i >= 0 && (mul *= 0x100)) {
  1349. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1350. sub = 1;
  1351. }
  1352. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  1353. }
  1354. return offset + byteLength
  1355. };
  1356. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1357. value = +value;
  1358. offset = offset | 0;
  1359. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  1360. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
  1361. if (value < 0) value = 0xff + value + 1;
  1362. this[offset] = (value & 0xff);
  1363. return offset + 1
  1364. };
  1365. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1366. value = +value;
  1367. offset = offset | 0;
  1368. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  1369. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1370. this[offset] = (value & 0xff);
  1371. this[offset + 1] = (value >>> 8);
  1372. } else {
  1373. objectWriteUInt16(this, value, offset, true);
  1374. }
  1375. return offset + 2
  1376. };
  1377. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1378. value = +value;
  1379. offset = offset | 0;
  1380. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  1381. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1382. this[offset] = (value >>> 8);
  1383. this[offset + 1] = (value & 0xff);
  1384. } else {
  1385. objectWriteUInt16(this, value, offset, false);
  1386. }
  1387. return offset + 2
  1388. };
  1389. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1390. value = +value;
  1391. offset = offset | 0;
  1392. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  1393. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1394. this[offset] = (value & 0xff);
  1395. this[offset + 1] = (value >>> 8);
  1396. this[offset + 2] = (value >>> 16);
  1397. this[offset + 3] = (value >>> 24);
  1398. } else {
  1399. objectWriteUInt32(this, value, offset, true);
  1400. }
  1401. return offset + 4
  1402. };
  1403. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1404. value = +value;
  1405. offset = offset | 0;
  1406. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  1407. if (value < 0) value = 0xffffffff + value + 1;
  1408. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1409. this[offset] = (value >>> 24);
  1410. this[offset + 1] = (value >>> 16);
  1411. this[offset + 2] = (value >>> 8);
  1412. this[offset + 3] = (value & 0xff);
  1413. } else {
  1414. objectWriteUInt32(this, value, offset, false);
  1415. }
  1416. return offset + 4
  1417. };
  1418. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1419. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1420. if (offset < 0) throw new RangeError('Index out of range')
  1421. }
  1422. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1423. if (!noAssert) {
  1424. checkIEEE754(buf, value, offset, 4);
  1425. }
  1426. write(buf, value, offset, littleEndian, 23, 4);
  1427. return offset + 4
  1428. }
  1429. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1430. return writeFloat(this, value, offset, true, noAssert)
  1431. };
  1432. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1433. return writeFloat(this, value, offset, false, noAssert)
  1434. };
  1435. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1436. if (!noAssert) {
  1437. checkIEEE754(buf, value, offset, 8);
  1438. }
  1439. write(buf, value, offset, littleEndian, 52, 8);
  1440. return offset + 8
  1441. }
  1442. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1443. return writeDouble(this, value, offset, true, noAssert)
  1444. };
  1445. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1446. return writeDouble(this, value, offset, false, noAssert)
  1447. };
  1448. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1449. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1450. if (!start) start = 0;
  1451. if (!end && end !== 0) end = this.length;
  1452. if (targetStart >= target.length) targetStart = target.length;
  1453. if (!targetStart) targetStart = 0;
  1454. if (end > 0 && end < start) end = start;
  1455. // Copy 0 bytes; we're done
  1456. if (end === start) return 0
  1457. if (target.length === 0 || this.length === 0) return 0
  1458. // Fatal error conditions
  1459. if (targetStart < 0) {
  1460. throw new RangeError('targetStart out of bounds')
  1461. }
  1462. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1463. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1464. // Are we oob?
  1465. if (end > this.length) end = this.length;
  1466. if (target.length - targetStart < end - start) {
  1467. end = target.length - targetStart + start;
  1468. }
  1469. var len = end - start;
  1470. var i;
  1471. if (this === target && start < targetStart && targetStart < end) {
  1472. // descending copy from end
  1473. for (i = len - 1; i >= 0; --i) {
  1474. target[i + targetStart] = this[i + start];
  1475. }
  1476. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1477. // ascending copy from start
  1478. for (i = 0; i < len; ++i) {
  1479. target[i + targetStart] = this[i + start];
  1480. }
  1481. } else {
  1482. Uint8Array.prototype.set.call(
  1483. target,
  1484. this.subarray(start, start + len),
  1485. targetStart
  1486. );
  1487. }
  1488. return len
  1489. };
  1490. // Usage:
  1491. // buffer.fill(number[, offset[, end]])
  1492. // buffer.fill(buffer[, offset[, end]])
  1493. // buffer.fill(string[, offset[, end]][, encoding])
  1494. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1495. // Handle string cases:
  1496. if (typeof val === 'string') {
  1497. if (typeof start === 'string') {
  1498. encoding = start;
  1499. start = 0;
  1500. end = this.length;
  1501. } else if (typeof end === 'string') {
  1502. encoding = end;
  1503. end = this.length;
  1504. }
  1505. if (val.length === 1) {
  1506. var code = val.charCodeAt(0);
  1507. if (code < 256) {
  1508. val = code;
  1509. }
  1510. }
  1511. if (encoding !== undefined && typeof encoding !== 'string') {
  1512. throw new TypeError('encoding must be a string')
  1513. }
  1514. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1515. throw new TypeError('Unknown encoding: ' + encoding)
  1516. }
  1517. } else if (typeof val === 'number') {
  1518. val = val & 255;
  1519. }
  1520. // Invalid ranges are not set to a default, so can range check early.
  1521. if (start < 0 || this.length < start || this.length < end) {
  1522. throw new RangeError('Out of range index')
  1523. }
  1524. if (end <= start) {
  1525. return this
  1526. }
  1527. start = start >>> 0;
  1528. end = end === undefined ? this.length : end >>> 0;
  1529. if (!val) val = 0;
  1530. var i;
  1531. if (typeof val === 'number') {
  1532. for (i = start; i < end; ++i) {
  1533. this[i] = val;
  1534. }
  1535. } else {
  1536. var bytes = internalIsBuffer(val)
  1537. ? val
  1538. : utf8ToBytes(new Buffer(val, encoding).toString());
  1539. var len = bytes.length;
  1540. for (i = 0; i < end - start; ++i) {
  1541. this[i + start] = bytes[i % len];
  1542. }
  1543. }
  1544. return this
  1545. };
  1546. // HELPER FUNCTIONS
  1547. // ================
  1548. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
  1549. function base64clean (str) {
  1550. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1551. str = stringtrim(str).replace(INVALID_BASE64_RE, '');
  1552. // Node converts strings with length < 2 to ''
  1553. if (str.length < 2) return ''
  1554. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1555. while (str.length % 4 !== 0) {
  1556. str = str + '=';
  1557. }
  1558. return str
  1559. }
  1560. function stringtrim (str) {
  1561. if (str.trim) return str.trim()
  1562. return str.replace(/^\s+|\s+$/g, '')
  1563. }
  1564. function toHex (n) {
  1565. if (n < 16) return '0' + n.toString(16)
  1566. return n.toString(16)
  1567. }
  1568. function utf8ToBytes (string, units) {
  1569. units = units || Infinity;
  1570. var codePoint;
  1571. var length = string.length;
  1572. var leadSurrogate = null;
  1573. var bytes = [];
  1574. for (var i = 0; i < length; ++i) {
  1575. codePoint = string.charCodeAt(i);
  1576. // is surrogate component
  1577. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1578. // last char was a lead
  1579. if (!leadSurrogate) {
  1580. // no lead yet
  1581. if (codePoint > 0xDBFF) {
  1582. // unexpected trail
  1583. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1584. continue
  1585. } else if (i + 1 === length) {
  1586. // unpaired lead
  1587. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1588. continue
  1589. }
  1590. // valid lead
  1591. leadSurrogate = codePoint;
  1592. continue
  1593. }
  1594. // 2 leads in a row
  1595. if (codePoint < 0xDC00) {
  1596. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1597. leadSurrogate = codePoint;
  1598. continue
  1599. }
  1600. // valid surrogate pair
  1601. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  1602. } else if (leadSurrogate) {
  1603. // valid bmp char, but last char was a lead
  1604. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  1605. }
  1606. leadSurrogate = null;
  1607. // encode utf8
  1608. if (codePoint < 0x80) {
  1609. if ((units -= 1) < 0) break
  1610. bytes.push(codePoint);
  1611. } else if (codePoint < 0x800) {
  1612. if ((units -= 2) < 0) break
  1613. bytes.push(
  1614. codePoint >> 0x6 | 0xC0,
  1615. codePoint & 0x3F | 0x80
  1616. );
  1617. } else if (codePoint < 0x10000) {
  1618. if ((units -= 3) < 0) break
  1619. bytes.push(
  1620. codePoint >> 0xC | 0xE0,
  1621. codePoint >> 0x6 & 0x3F | 0x80,
  1622. codePoint & 0x3F | 0x80
  1623. );
  1624. } else if (codePoint < 0x110000) {
  1625. if ((units -= 4) < 0) break
  1626. bytes.push(
  1627. codePoint >> 0x12 | 0xF0,
  1628. codePoint >> 0xC & 0x3F | 0x80,
  1629. codePoint >> 0x6 & 0x3F | 0x80,
  1630. codePoint & 0x3F | 0x80
  1631. );
  1632. } else {
  1633. throw new Error('Invalid code point')
  1634. }
  1635. }
  1636. return bytes
  1637. }
  1638. function asciiToBytes (str) {
  1639. var byteArray = [];
  1640. for (var i = 0; i < str.length; ++i) {
  1641. // Node's code seems to be doing this and not & 0x7F..
  1642. byteArray.push(str.charCodeAt(i) & 0xFF);
  1643. }
  1644. return byteArray
  1645. }
  1646. function utf16leToBytes (str, units) {
  1647. var c, hi, lo;
  1648. var byteArray = [];
  1649. for (var i = 0; i < str.length; ++i) {
  1650. if ((units -= 2) < 0) break
  1651. c = str.charCodeAt(i);
  1652. hi = c >> 8;
  1653. lo = c % 256;
  1654. byteArray.push(lo);
  1655. byteArray.push(hi);
  1656. }
  1657. return byteArray
  1658. }
  1659. function base64ToBytes (str) {
  1660. return toByteArray(base64clean(str))
  1661. }
  1662. function blitBuffer (src, dst, offset, length) {
  1663. for (var i = 0; i < length; ++i) {
  1664. if ((i + offset >= dst.length) || (i >= src.length)) break
  1665. dst[i + offset] = src[i];
  1666. }
  1667. return i
  1668. }
  1669. function isnan (val) {
  1670. return val !== val // eslint-disable-line no-self-compare
  1671. }
  1672. // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
  1673. // The _isBuffer check is for Safari 5-7 support, because it's missing
  1674. // Object.prototype.constructor. Remove this eventually
  1675. function isBuffer(obj) {
  1676. return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
  1677. }
  1678. function isFastBuffer (obj) {
  1679. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  1680. }
  1681. // For Node v0.10 support. Remove this eventually.
  1682. function isSlowBuffer (obj) {
  1683. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
  1684. }
  1685. var domain;
  1686. // This constructor is used to store event handlers. Instantiating this is
  1687. // faster than explicitly calling `Object.create(null)` to get a "clean" empty
  1688. // object (tested with v8 v4.9).
  1689. function EventHandlers() {}
  1690. EventHandlers.prototype = Object.create(null);
  1691. function EventEmitter() {
  1692. EventEmitter.init.call(this);
  1693. }
  1694. // nodejs oddity
  1695. // require('events') === require('events').EventEmitter
  1696. EventEmitter.EventEmitter = EventEmitter;
  1697. EventEmitter.usingDomains = false;
  1698. EventEmitter.prototype.domain = undefined;
  1699. EventEmitter.prototype._events = undefined;
  1700. EventEmitter.prototype._maxListeners = undefined;
  1701. // By default EventEmitters will print a warning if more than 10 listeners are
  1702. // added to it. This is a useful default which helps finding memory leaks.
  1703. EventEmitter.defaultMaxListeners = 10;
  1704. EventEmitter.init = function() {
  1705. this.domain = null;
  1706. if (EventEmitter.usingDomains) {
  1707. // if there is an active domain, then attach to it.
  1708. if (domain.active ) ;
  1709. }
  1710. if (!this._events || this._events === Object.getPrototypeOf(this)._events) {
  1711. this._events = new EventHandlers();
  1712. this._eventsCount = 0;
  1713. }
  1714. this._maxListeners = this._maxListeners || undefined;
  1715. };
  1716. // Obviously not all Emitters should be limited to 10. This function allows
  1717. // that to be increased. Set to zero for unlimited.
  1718. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  1719. if (typeof n !== 'number' || n < 0 || isNaN(n))
  1720. throw new TypeError('"n" argument must be a positive number');
  1721. this._maxListeners = n;
  1722. return this;
  1723. };
  1724. function $getMaxListeners(that) {
  1725. if (that._maxListeners === undefined)
  1726. return EventEmitter.defaultMaxListeners;
  1727. return that._maxListeners;
  1728. }
  1729. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  1730. return $getMaxListeners(this);
  1731. };
  1732. // These standalone emit* functions are used to optimize calling of event
  1733. // handlers for fast cases because emit() itself often has a variable number of
  1734. // arguments and can be deoptimized because of that. These functions always have
  1735. // the same number of arguments and thus do not get deoptimized, so the code
  1736. // inside them can execute faster.
  1737. function emitNone(handler, isFn, self) {
  1738. if (isFn)
  1739. handler.call(self);
  1740. else {
  1741. var len = handler.length;
  1742. var listeners = arrayClone(handler, len);
  1743. for (var i = 0; i < len; ++i)
  1744. listeners[i].call(self);
  1745. }
  1746. }
  1747. function emitOne(handler, isFn, self, arg1) {
  1748. if (isFn)
  1749. handler.call(self, arg1);
  1750. else {
  1751. var len = handler.length;
  1752. var listeners = arrayClone(handler, len);
  1753. for (var i = 0; i < len; ++i)
  1754. listeners[i].call(self, arg1);
  1755. }
  1756. }
  1757. function emitTwo(handler, isFn, self, arg1, arg2) {
  1758. if (isFn)
  1759. handler.call(self, arg1, arg2);
  1760. else {
  1761. var len = handler.length;
  1762. var listeners = arrayClone(handler, len);
  1763. for (var i = 0; i < len; ++i)
  1764. listeners[i].call(self, arg1, arg2);
  1765. }
  1766. }
  1767. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  1768. if (isFn)
  1769. handler.call(self, arg1, arg2, arg3);
  1770. else {
  1771. var len = handler.length;
  1772. var listeners = arrayClone(handler, len);
  1773. for (var i = 0; i < len; ++i)
  1774. listeners[i].call(self, arg1, arg2, arg3);
  1775. }
  1776. }
  1777. function emitMany(handler, isFn, self, args) {
  1778. if (isFn)
  1779. handler.apply(self, args);
  1780. else {
  1781. var len = handler.length;
  1782. var listeners = arrayClone(handler, len);
  1783. for (var i = 0; i < len; ++i)
  1784. listeners[i].apply(self, args);
  1785. }
  1786. }
  1787. EventEmitter.prototype.emit = function emit(type) {
  1788. var er, handler, len, args, i, events, domain;
  1789. var doError = (type === 'error');
  1790. events = this._events;
  1791. if (events)
  1792. doError = (doError && events.error == null);
  1793. else if (!doError)
  1794. return false;
  1795. domain = this.domain;
  1796. // If there is no 'error' event listener then throw.
  1797. if (doError) {
  1798. er = arguments[1];
  1799. if (domain) {
  1800. if (!er)
  1801. er = new Error('Uncaught, unspecified "error" event');
  1802. er.domainEmitter = this;
  1803. er.domain = domain;
  1804. er.domainThrown = false;
  1805. domain.emit('error', er);
  1806. } else if (er instanceof Error) {
  1807. throw er; // Unhandled 'error' event
  1808. } else {
  1809. // At least give some kind of context to the user
  1810. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  1811. err.context = er;
  1812. throw err;
  1813. }
  1814. return false;
  1815. }
  1816. handler = events[type];
  1817. if (!handler)
  1818. return false;
  1819. var isFn = typeof handler === 'function';
  1820. len = arguments.length;
  1821. switch (len) {
  1822. // fast cases
  1823. case 1:
  1824. emitNone(handler, isFn, this);
  1825. break;
  1826. case 2:
  1827. emitOne(handler, isFn, this, arguments[1]);
  1828. break;
  1829. case 3:
  1830. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  1831. break;
  1832. case 4:
  1833. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  1834. break;
  1835. // slower
  1836. default:
  1837. args = new Array(len - 1);
  1838. for (i = 1; i < len; i++)
  1839. args[i - 1] = arguments[i];
  1840. emitMany(handler, isFn, this, args);
  1841. }
  1842. return true;
  1843. };
  1844. function _addListener(target, type, listener, prepend) {
  1845. var m;
  1846. var events;
  1847. var existing;
  1848. if (typeof listener !== 'function')
  1849. throw new TypeError('"listener" argument must be a function');
  1850. events = target._events;
  1851. if (!events) {
  1852. events = target._events = new EventHandlers();
  1853. target._eventsCount = 0;
  1854. } else {
  1855. // To avoid recursion in the case that type === "newListener"! Before
  1856. // adding it to the listeners, first emit "newListener".
  1857. if (events.newListener) {
  1858. target.emit('newListener', type,
  1859. listener.listener ? listener.listener : listener);
  1860. // Re-assign `events` because a newListener handler could have caused the
  1861. // this._events to be assigned to a new object
  1862. events = target._events;
  1863. }
  1864. existing = events[type];
  1865. }
  1866. if (!existing) {
  1867. // Optimize the case of one listener. Don't need the extra array object.
  1868. existing = events[type] = listener;
  1869. ++target._eventsCount;
  1870. } else {
  1871. if (typeof existing === 'function') {
  1872. // Adding the second element, need to change to array.
  1873. existing = events[type] = prepend ? [listener, existing] :
  1874. [existing, listener];
  1875. } else {
  1876. // If we've already got an array, just append.
  1877. if (prepend) {
  1878. existing.unshift(listener);
  1879. } else {
  1880. existing.push(listener);
  1881. }
  1882. }
  1883. // Check for listener leak
  1884. if (!existing.warned) {
  1885. m = $getMaxListeners(target);
  1886. if (m && m > 0 && existing.length > m) {
  1887. existing.warned = true;
  1888. var w = new Error('Possible EventEmitter memory leak detected. ' +
  1889. existing.length + ' ' + type + ' listeners added. ' +
  1890. 'Use emitter.setMaxListeners() to increase limit');
  1891. w.name = 'MaxListenersExceededWarning';
  1892. w.emitter = target;
  1893. w.type = type;
  1894. w.count = existing.length;
  1895. emitWarning(w);
  1896. }
  1897. }
  1898. }
  1899. return target;
  1900. }
  1901. function emitWarning(e) {
  1902. typeof console.warn === 'function' ? console.warn(e) : console.log(e);
  1903. }
  1904. EventEmitter.prototype.addListener = function addListener(type, listener) {
  1905. return _addListener(this, type, listener, false);
  1906. };
  1907. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  1908. EventEmitter.prototype.prependListener =
  1909. function prependListener(type, listener) {
  1910. return _addListener(this, type, listener, true);
  1911. };
  1912. function _onceWrap(target, type, listener) {
  1913. var fired = false;
  1914. function g() {
  1915. target.removeListener(type, g);
  1916. if (!fired) {
  1917. fired = true;
  1918. listener.apply(target, arguments);
  1919. }
  1920. }
  1921. g.listener = listener;
  1922. return g;
  1923. }
  1924. EventEmitter.prototype.once = function once(type, listener) {
  1925. if (typeof listener !== 'function')
  1926. throw new TypeError('"listener" argument must be a function');
  1927. this.on(type, _onceWrap(this, type, listener));
  1928. return this;
  1929. };
  1930. EventEmitter.prototype.prependOnceListener =
  1931. function prependOnceListener(type, listener) {
  1932. if (typeof listener !== 'function')
  1933. throw new TypeError('"listener" argument must be a function');
  1934. this.prependListener(type, _onceWrap(this, type, listener));
  1935. return this;
  1936. };
  1937. // emits a 'removeListener' event iff the listener was removed
  1938. EventEmitter.prototype.removeListener =
  1939. function removeListener(type, listener) {
  1940. var list, events, position, i, originalListener;
  1941. if (typeof listener !== 'function')
  1942. throw new TypeError('"listener" argument must be a function');
  1943. events = this._events;
  1944. if (!events)
  1945. return this;
  1946. list = events[type];
  1947. if (!list)
  1948. return this;
  1949. if (list === listener || (list.listener && list.listener === listener)) {
  1950. if (--this._eventsCount === 0)
  1951. this._events = new EventHandlers();
  1952. else {
  1953. delete events[type];
  1954. if (events.removeListener)
  1955. this.emit('removeListener', type, list.listener || listener);
  1956. }
  1957. } else if (typeof list !== 'function') {
  1958. position = -1;
  1959. for (i = list.length; i-- > 0;) {
  1960. if (list[i] === listener ||
  1961. (list[i].listener && list[i].listener === listener)) {
  1962. originalListener = list[i].listener;
  1963. position = i;
  1964. break;
  1965. }
  1966. }
  1967. if (position < 0)
  1968. return this;
  1969. if (list.length === 1) {
  1970. list[0] = undefined;
  1971. if (--this._eventsCount === 0) {
  1972. this._events = new EventHandlers();
  1973. return this;
  1974. } else {
  1975. delete events[type];
  1976. }
  1977. } else {
  1978. spliceOne(list, position);
  1979. }
  1980. if (events.removeListener)
  1981. this.emit('removeListener', type, originalListener || listener);
  1982. }
  1983. return this;
  1984. };
  1985. EventEmitter.prototype.removeAllListeners =
  1986. function removeAllListeners(type) {
  1987. var listeners, events;
  1988. events = this._events;
  1989. if (!events)
  1990. return this;
  1991. // not listening for removeListener, no need to emit
  1992. if (!events.removeListener) {
  1993. if (arguments.length === 0) {
  1994. this._events = new EventHandlers();
  1995. this._eventsCount = 0;
  1996. } else if (events[type]) {
  1997. if (--this._eventsCount === 0)
  1998. this._events = new EventHandlers();
  1999. else
  2000. delete events[type];
  2001. }
  2002. return this;
  2003. }
  2004. // emit removeListener for all listeners on all events
  2005. if (arguments.length === 0) {
  2006. var keys = Object.keys(events);
  2007. for (var i = 0, key; i < keys.length; ++i) {
  2008. key = keys[i];
  2009. if (key === 'removeListener') continue;
  2010. this.removeAllListeners(key);
  2011. }
  2012. this.removeAllListeners('removeListener');
  2013. this._events = new EventHandlers();
  2014. this._eventsCount = 0;
  2015. return this;
  2016. }
  2017. listeners = events[type];
  2018. if (typeof listeners === 'function') {
  2019. this.removeListener(type, listeners);
  2020. } else if (listeners) {
  2021. // LIFO order
  2022. do {
  2023. this.removeListener(type, listeners[listeners.length - 1]);
  2024. } while (listeners[0]);
  2025. }
  2026. return this;
  2027. };
  2028. EventEmitter.prototype.listeners = function listeners(type) {
  2029. var evlistener;
  2030. var ret;
  2031. var events = this._events;
  2032. if (!events)
  2033. ret = [];
  2034. else {
  2035. evlistener = events[type];
  2036. if (!evlistener)
  2037. ret = [];
  2038. else if (typeof evlistener === 'function')
  2039. ret = [evlistener.listener || evlistener];
  2040. else
  2041. ret = unwrapListeners(evlistener);
  2042. }
  2043. return ret;
  2044. };
  2045. EventEmitter.listenerCount = function(emitter, type) {
  2046. if (typeof emitter.listenerCount === 'function') {
  2047. return emitter.listenerCount(type);
  2048. } else {
  2049. return listenerCount$1.call(emitter, type);
  2050. }
  2051. };
  2052. EventEmitter.prototype.listenerCount = listenerCount$1;
  2053. function listenerCount$1(type) {
  2054. var events = this._events;
  2055. if (events) {
  2056. var evlistener = events[type];
  2057. if (typeof evlistener === 'function') {
  2058. return 1;
  2059. } else if (evlistener) {
  2060. return evlistener.length;
  2061. }
  2062. }
  2063. return 0;
  2064. }
  2065. EventEmitter.prototype.eventNames = function eventNames() {
  2066. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  2067. };
  2068. // About 1.5x faster than the two-arg version of Array#splice().
  2069. function spliceOne(list, index) {
  2070. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  2071. list[i] = list[k];
  2072. list.pop();
  2073. }
  2074. function arrayClone(arr, i) {
  2075. var copy = new Array(i);
  2076. while (i--)
  2077. copy[i] = arr[i];
  2078. return copy;
  2079. }
  2080. function unwrapListeners(arr) {
  2081. var ret = new Array(arr.length);
  2082. for (var i = 0; i < ret.length; ++i) {
  2083. ret[i] = arr[i].listener || arr[i];
  2084. }
  2085. return ret;
  2086. }
  2087. // shim for using process in browser
  2088. // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
  2089. function defaultSetTimout() {
  2090. throw new Error('setTimeout has not been defined');
  2091. }
  2092. function defaultClearTimeout () {
  2093. throw new Error('clearTimeout has not been defined');
  2094. }
  2095. var cachedSetTimeout = defaultSetTimout;
  2096. var cachedClearTimeout = defaultClearTimeout;
  2097. if (typeof global$1.setTimeout === 'function') {
  2098. cachedSetTimeout = setTimeout;
  2099. }
  2100. if (typeof global$1.clearTimeout === 'function') {
  2101. cachedClearTimeout = clearTimeout;
  2102. }
  2103. function runTimeout(fun) {
  2104. if (cachedSetTimeout === setTimeout) {
  2105. //normal enviroments in sane situations
  2106. return setTimeout(fun, 0);
  2107. }
  2108. // if setTimeout wasn't available but was latter defined
  2109. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  2110. cachedSetTimeout = setTimeout;
  2111. return setTimeout(fun, 0);
  2112. }
  2113. try {
  2114. // when when somebody has screwed with setTimeout but no I.E. maddness
  2115. return cachedSetTimeout(fun, 0);
  2116. } catch(e){
  2117. try {
  2118. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2119. return cachedSetTimeout.call(null, fun, 0);
  2120. } catch(e){
  2121. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  2122. return cachedSetTimeout.call(this, fun, 0);
  2123. }
  2124. }
  2125. }
  2126. function runClearTimeout(marker) {
  2127. if (cachedClearTimeout === clearTimeout) {
  2128. //normal enviroments in sane situations
  2129. return clearTimeout(marker);
  2130. }
  2131. // if clearTimeout wasn't available but was latter defined
  2132. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  2133. cachedClearTimeout = clearTimeout;
  2134. return clearTimeout(marker);
  2135. }
  2136. try {
  2137. // when when somebody has screwed with setTimeout but no I.E. maddness
  2138. return cachedClearTimeout(marker);
  2139. } catch (e){
  2140. try {
  2141. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2142. return cachedClearTimeout.call(null, marker);
  2143. } catch (e){
  2144. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  2145. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  2146. return cachedClearTimeout.call(this, marker);
  2147. }
  2148. }
  2149. }
  2150. var queue = [];
  2151. var draining = false;
  2152. var currentQueue;
  2153. var queueIndex = -1;
  2154. function cleanUpNextTick() {
  2155. if (!draining || !currentQueue) {
  2156. return;
  2157. }
  2158. draining = false;
  2159. if (currentQueue.length) {
  2160. queue = currentQueue.concat(queue);
  2161. } else {
  2162. queueIndex = -1;
  2163. }
  2164. if (queue.length) {
  2165. drainQueue();
  2166. }
  2167. }
  2168. function drainQueue() {
  2169. if (draining) {
  2170. return;
  2171. }
  2172. var timeout = runTimeout(cleanUpNextTick);
  2173. draining = true;
  2174. var len = queue.length;
  2175. while(len) {
  2176. currentQueue = queue;
  2177. queue = [];
  2178. while (++queueIndex < len) {
  2179. if (currentQueue) {
  2180. currentQueue[queueIndex].run();
  2181. }
  2182. }
  2183. queueIndex = -1;
  2184. len = queue.length;
  2185. }
  2186. currentQueue = null;
  2187. draining = false;
  2188. runClearTimeout(timeout);
  2189. }
  2190. function nextTick(fun) {
  2191. var args = new Array(arguments.length - 1);
  2192. if (arguments.length > 1) {
  2193. for (var i = 1; i < arguments.length; i++) {
  2194. args[i - 1] = arguments[i];
  2195. }
  2196. }
  2197. queue.push(new Item(fun, args));
  2198. if (queue.length === 1 && !draining) {
  2199. runTimeout(drainQueue);
  2200. }
  2201. }
  2202. // v8 likes predictible objects
  2203. function Item(fun, array) {
  2204. this.fun = fun;
  2205. this.array = array;
  2206. }
  2207. Item.prototype.run = function () {
  2208. this.fun.apply(null, this.array);
  2209. };
  2210. var title = 'browser';
  2211. var platform = 'browser';
  2212. var browser = true;
  2213. var env = {};
  2214. var argv = [];
  2215. var version = ''; // empty string to avoid regexp issues
  2216. var versions = {};
  2217. var release = {};
  2218. var config = {};
  2219. function noop() {}
  2220. var on = noop;
  2221. var addListener = noop;
  2222. var once = noop;
  2223. var off = noop;
  2224. var removeListener = noop;
  2225. var removeAllListeners = noop;
  2226. var emit = noop;
  2227. function binding(name) {
  2228. throw new Error('process.binding is not supported');
  2229. }
  2230. function cwd () { return '/' }
  2231. function chdir (dir) {
  2232. throw new Error('process.chdir is not supported');
  2233. }function umask() { return 0; }
  2234. // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
  2235. var performance = global$1.performance || {};
  2236. var performanceNow =
  2237. performance.now ||
  2238. performance.mozNow ||
  2239. performance.msNow ||
  2240. performance.oNow ||
  2241. performance.webkitNow ||
  2242. function(){ return (new Date()).getTime() };
  2243. // generate timestamp or delta
  2244. // see http://nodejs.org/api/process.html#process_process_hrtime
  2245. function hrtime(previousTimestamp){
  2246. var clocktime = performanceNow.call(performance)*1e-3;
  2247. var seconds = Math.floor(clocktime);
  2248. var nanoseconds = Math.floor((clocktime%1)*1e9);
  2249. if (previousTimestamp) {
  2250. seconds = seconds - previousTimestamp[0];
  2251. nanoseconds = nanoseconds - previousTimestamp[1];
  2252. if (nanoseconds<0) {
  2253. seconds--;
  2254. nanoseconds += 1e9;
  2255. }
  2256. }
  2257. return [seconds,nanoseconds]
  2258. }
  2259. var startTime = new Date();
  2260. function uptime() {
  2261. var currentTime = new Date();
  2262. var dif = currentTime - startTime;
  2263. return dif / 1000;
  2264. }
  2265. var process = {
  2266. nextTick: nextTick,
  2267. title: title,
  2268. browser: browser,
  2269. env: env,
  2270. argv: argv,
  2271. version: version,
  2272. versions: versions,
  2273. on: on,
  2274. addListener: addListener,
  2275. once: once,
  2276. off: off,
  2277. removeListener: removeListener,
  2278. removeAllListeners: removeAllListeners,
  2279. emit: emit,
  2280. binding: binding,
  2281. cwd: cwd,
  2282. chdir: chdir,
  2283. umask: umask,
  2284. hrtime: hrtime,
  2285. platform: platform,
  2286. release: release,
  2287. config: config,
  2288. uptime: uptime
  2289. };
  2290. var inherits;
  2291. if (typeof Object.create === 'function'){
  2292. inherits = function inherits(ctor, superCtor) {
  2293. // implementation from standard node.js 'util' module
  2294. ctor.super_ = superCtor;
  2295. ctor.prototype = Object.create(superCtor.prototype, {
  2296. constructor: {
  2297. value: ctor,
  2298. enumerable: false,
  2299. writable: true,
  2300. configurable: true
  2301. }
  2302. });
  2303. };
  2304. } else {
  2305. inherits = function inherits(ctor, superCtor) {
  2306. ctor.super_ = superCtor;
  2307. var TempCtor = function () {};
  2308. TempCtor.prototype = superCtor.prototype;
  2309. ctor.prototype = new TempCtor();
  2310. ctor.prototype.constructor = ctor;
  2311. };
  2312. }
  2313. var inherits$1 = inherits;
  2314. var formatRegExp = /%[sdj%]/g;
  2315. function format(f) {
  2316. if (!isString(f)) {
  2317. var objects = [];
  2318. for (var i = 0; i < arguments.length; i++) {
  2319. objects.push(inspect(arguments[i]));
  2320. }
  2321. return objects.join(' ');
  2322. }
  2323. var i = 1;
  2324. var args = arguments;
  2325. var len = args.length;
  2326. var str = String(f).replace(formatRegExp, function(x) {
  2327. if (x === '%%') return '%';
  2328. if (i >= len) return x;
  2329. switch (x) {
  2330. case '%s': return String(args[i++]);
  2331. case '%d': return Number(args[i++]);
  2332. case '%j':
  2333. try {
  2334. return JSON.stringify(args[i++]);
  2335. } catch (_) {
  2336. return '[Circular]';
  2337. }
  2338. default:
  2339. return x;
  2340. }
  2341. });
  2342. for (var x = args[i]; i < len; x = args[++i]) {
  2343. if (isNull(x) || !isObject(x)) {
  2344. str += ' ' + x;
  2345. } else {
  2346. str += ' ' + inspect(x);
  2347. }
  2348. }
  2349. return str;
  2350. }
  2351. // Mark that a method should not be used.
  2352. // Returns a modified function which warns once by default.
  2353. // If --no-deprecation is set, then it is a no-op.
  2354. function deprecate(fn, msg) {
  2355. // Allow for deprecating things in the process of starting up.
  2356. if (isUndefined(global$1.process)) {
  2357. return function() {
  2358. return deprecate(fn, msg).apply(this, arguments);
  2359. };
  2360. }
  2361. if (process.noDeprecation === true) {
  2362. return fn;
  2363. }
  2364. var warned = false;
  2365. function deprecated() {
  2366. if (!warned) {
  2367. if (process.throwDeprecation) {
  2368. throw new Error(msg);
  2369. } else if (process.traceDeprecation) {
  2370. console.trace(msg);
  2371. } else {
  2372. console.error(msg);
  2373. }
  2374. warned = true;
  2375. }
  2376. return fn.apply(this, arguments);
  2377. }
  2378. return deprecated;
  2379. }
  2380. var debugs = {};
  2381. var debugEnviron;
  2382. function debuglog(set) {
  2383. if (isUndefined(debugEnviron))
  2384. debugEnviron = process.env.NODE_DEBUG || '';
  2385. set = set.toUpperCase();
  2386. if (!debugs[set]) {
  2387. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  2388. var pid = 0;
  2389. debugs[set] = function() {
  2390. var msg = format.apply(null, arguments);
  2391. console.error('%s %d: %s', set, pid, msg);
  2392. };
  2393. } else {
  2394. debugs[set] = function() {};
  2395. }
  2396. }
  2397. return debugs[set];
  2398. }
  2399. /**
  2400. * Echos the value of a value. Trys to print the value out
  2401. * in the best way possible given the different types.
  2402. *
  2403. * @param {Object} obj The object to print out.
  2404. * @param {Object} opts Optional options object that alters the output.
  2405. */
  2406. /* legacy: obj, showHidden, depth, colors*/
  2407. function inspect(obj, opts) {
  2408. // default options
  2409. var ctx = {
  2410. seen: [],
  2411. stylize: stylizeNoColor
  2412. };
  2413. // legacy...
  2414. if (arguments.length >= 3) ctx.depth = arguments[2];
  2415. if (arguments.length >= 4) ctx.colors = arguments[3];
  2416. if (isBoolean(opts)) {
  2417. // legacy...
  2418. ctx.showHidden = opts;
  2419. } else if (opts) {
  2420. // got an "options" object
  2421. _extend(ctx, opts);
  2422. }
  2423. // set default options
  2424. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  2425. if (isUndefined(ctx.depth)) ctx.depth = 2;
  2426. if (isUndefined(ctx.colors)) ctx.colors = false;
  2427. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  2428. if (ctx.colors) ctx.stylize = stylizeWithColor;
  2429. return formatValue(ctx, obj, ctx.depth);
  2430. }
  2431. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  2432. inspect.colors = {
  2433. 'bold' : [1, 22],
  2434. 'italic' : [3, 23],
  2435. 'underline' : [4, 24],
  2436. 'inverse' : [7, 27],
  2437. 'white' : [37, 39],
  2438. 'grey' : [90, 39],
  2439. 'black' : [30, 39],
  2440. 'blue' : [34, 39],
  2441. 'cyan' : [36, 39],
  2442. 'green' : [32, 39],
  2443. 'magenta' : [35, 39],
  2444. 'red' : [31, 39],
  2445. 'yellow' : [33, 39]
  2446. };
  2447. // Don't use 'blue' not visible on cmd.exe
  2448. inspect.styles = {
  2449. 'special': 'cyan',
  2450. 'number': 'yellow',
  2451. 'boolean': 'yellow',
  2452. 'undefined': 'grey',
  2453. 'null': 'bold',
  2454. 'string': 'green',
  2455. 'date': 'magenta',
  2456. // "name": intentionally not styling
  2457. 'regexp': 'red'
  2458. };
  2459. function stylizeWithColor(str, styleType) {
  2460. var style = inspect.styles[styleType];
  2461. if (style) {
  2462. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  2463. '\u001b[' + inspect.colors[style][1] + 'm';
  2464. } else {
  2465. return str;
  2466. }
  2467. }
  2468. function stylizeNoColor(str, styleType) {
  2469. return str;
  2470. }
  2471. function arrayToHash(array) {
  2472. var hash = {};
  2473. array.forEach(function(val, idx) {
  2474. hash[val] = true;
  2475. });
  2476. return hash;
  2477. }
  2478. function formatValue(ctx, value, recurseTimes) {
  2479. // Provide a hook for user-specified inspect functions.
  2480. // Check that value is an object with an inspect function on it
  2481. if (ctx.customInspect &&
  2482. value &&
  2483. isFunction(value.inspect) &&
  2484. // Filter out the util module, it's inspect function is special
  2485. value.inspect !== inspect &&
  2486. // Also filter out any prototype objects using the circular check.
  2487. !(value.constructor && value.constructor.prototype === value)) {
  2488. var ret = value.inspect(recurseTimes, ctx);
  2489. if (!isString(ret)) {
  2490. ret = formatValue(ctx, ret, recurseTimes);
  2491. }
  2492. return ret;
  2493. }
  2494. // Primitive types cannot have properties
  2495. var primitive = formatPrimitive(ctx, value);
  2496. if (primitive) {
  2497. return primitive;
  2498. }
  2499. // Look up the keys of the object.
  2500. var keys = Object.keys(value);
  2501. var visibleKeys = arrayToHash(keys);
  2502. if (ctx.showHidden) {
  2503. keys = Object.getOwnPropertyNames(value);
  2504. }
  2505. // IE doesn't make error fields non-enumerable
  2506. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  2507. if (isError(value)
  2508. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  2509. return formatError(value);
  2510. }
  2511. // Some type of object without properties can be shortcutted.
  2512. if (keys.length === 0) {
  2513. if (isFunction(value)) {
  2514. var name = value.name ? ': ' + value.name : '';
  2515. return ctx.stylize('[Function' + name + ']', 'special');
  2516. }
  2517. if (isRegExp(value)) {
  2518. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  2519. }
  2520. if (isDate(value)) {
  2521. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  2522. }
  2523. if (isError(value)) {
  2524. return formatError(value);
  2525. }
  2526. }
  2527. var base = '', array = false, braces = ['{', '}'];
  2528. // Make Array say that they are Array
  2529. if (isArray(value)) {
  2530. array = true;
  2531. braces = ['[', ']'];
  2532. }
  2533. // Make functions say that they are functions
  2534. if (isFunction(value)) {
  2535. var n = value.name ? ': ' + value.name : '';
  2536. base = ' [Function' + n + ']';
  2537. }
  2538. // Make RegExps say that they are RegExps
  2539. if (isRegExp(value)) {
  2540. base = ' ' + RegExp.prototype.toString.call(value);
  2541. }
  2542. // Make dates with properties first say the date
  2543. if (isDate(value)) {
  2544. base = ' ' + Date.prototype.toUTCString.call(value);
  2545. }
  2546. // Make error with message first say the error
  2547. if (isError(value)) {
  2548. base = ' ' + formatError(value);
  2549. }
  2550. if (keys.length === 0 && (!array || value.length == 0)) {
  2551. return braces[0] + base + braces[1];
  2552. }
  2553. if (recurseTimes < 0) {
  2554. if (isRegExp(value)) {
  2555. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  2556. } else {
  2557. return ctx.stylize('[Object]', 'special');
  2558. }
  2559. }
  2560. ctx.seen.push(value);
  2561. var output;
  2562. if (array) {
  2563. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  2564. } else {
  2565. output = keys.map(function(key) {
  2566. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  2567. });
  2568. }
  2569. ctx.seen.pop();
  2570. return reduceToSingleString(output, base, braces);
  2571. }
  2572. function formatPrimitive(ctx, value) {
  2573. if (isUndefined(value))
  2574. return ctx.stylize('undefined', 'undefined');
  2575. if (isString(value)) {
  2576. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  2577. .replace(/'/g, "\\'")
  2578. .replace(/\\"/g, '"') + '\'';
  2579. return ctx.stylize(simple, 'string');
  2580. }
  2581. if (isNumber(value))
  2582. return ctx.stylize('' + value, 'number');
  2583. if (isBoolean(value))
  2584. return ctx.stylize('' + value, 'boolean');
  2585. // For some reason typeof null is "object", so special case here.
  2586. if (isNull(value))
  2587. return ctx.stylize('null', 'null');
  2588. }
  2589. function formatError(value) {
  2590. return '[' + Error.prototype.toString.call(value) + ']';
  2591. }
  2592. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  2593. var output = [];
  2594. for (var i = 0, l = value.length; i < l; ++i) {
  2595. if (hasOwnProperty(value, String(i))) {
  2596. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  2597. String(i), true));
  2598. } else {
  2599. output.push('');
  2600. }
  2601. }
  2602. keys.forEach(function(key) {
  2603. if (!key.match(/^\d+$/)) {
  2604. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  2605. key, true));
  2606. }
  2607. });
  2608. return output;
  2609. }
  2610. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  2611. var name, str, desc;
  2612. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  2613. if (desc.get) {
  2614. if (desc.set) {
  2615. str = ctx.stylize('[Getter/Setter]', 'special');
  2616. } else {
  2617. str = ctx.stylize('[Getter]', 'special');
  2618. }
  2619. } else {
  2620. if (desc.set) {
  2621. str = ctx.stylize('[Setter]', 'special');
  2622. }
  2623. }
  2624. if (!hasOwnProperty(visibleKeys, key)) {
  2625. name = '[' + key + ']';
  2626. }
  2627. if (!str) {
  2628. if (ctx.seen.indexOf(desc.value) < 0) {
  2629. if (isNull(recurseTimes)) {
  2630. str = formatValue(ctx, desc.value, null);
  2631. } else {
  2632. str = formatValue(ctx, desc.value, recurseTimes - 1);
  2633. }
  2634. if (str.indexOf('\n') > -1) {
  2635. if (array) {
  2636. str = str.split('\n').map(function(line) {
  2637. return ' ' + line;
  2638. }).join('\n').substr(2);
  2639. } else {
  2640. str = '\n' + str.split('\n').map(function(line) {
  2641. return ' ' + line;
  2642. }).join('\n');
  2643. }
  2644. }
  2645. } else {
  2646. str = ctx.stylize('[Circular]', 'special');
  2647. }
  2648. }
  2649. if (isUndefined(name)) {
  2650. if (array && key.match(/^\d+$/)) {
  2651. return str;
  2652. }
  2653. name = JSON.stringify('' + key);
  2654. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  2655. name = name.substr(1, name.length - 2);
  2656. name = ctx.stylize(name, 'name');
  2657. } else {
  2658. name = name.replace(/'/g, "\\'")
  2659. .replace(/\\"/g, '"')
  2660. .replace(/(^"|"$)/g, "'");
  2661. name = ctx.stylize(name, 'string');
  2662. }
  2663. }
  2664. return name + ': ' + str;
  2665. }
  2666. function reduceToSingleString(output, base, braces) {
  2667. var length = output.reduce(function(prev, cur) {
  2668. if (cur.indexOf('\n') >= 0) ;
  2669. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  2670. }, 0);
  2671. if (length > 60) {
  2672. return braces[0] +
  2673. (base === '' ? '' : base + '\n ') +
  2674. ' ' +
  2675. output.join(',\n ') +
  2676. ' ' +
  2677. braces[1];
  2678. }
  2679. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  2680. }
  2681. // NOTE: These type checking functions intentionally don't use `instanceof`
  2682. // because it is fragile and can be easily faked with `Object.create()`.
  2683. function isArray(ar) {
  2684. return Array.isArray(ar);
  2685. }
  2686. function isBoolean(arg) {
  2687. return typeof arg === 'boolean';
  2688. }
  2689. function isNull(arg) {
  2690. return arg === null;
  2691. }
  2692. function isNumber(arg) {
  2693. return typeof arg === 'number';
  2694. }
  2695. function isString(arg) {
  2696. return typeof arg === 'string';
  2697. }
  2698. function isUndefined(arg) {
  2699. return arg === void 0;
  2700. }
  2701. function isRegExp(re) {
  2702. return isObject(re) && objectToString(re) === '[object RegExp]';
  2703. }
  2704. function isObject(arg) {
  2705. return typeof arg === 'object' && arg !== null;
  2706. }
  2707. function isDate(d) {
  2708. return isObject(d) && objectToString(d) === '[object Date]';
  2709. }
  2710. function isError(e) {
  2711. return isObject(e) &&
  2712. (objectToString(e) === '[object Error]' || e instanceof Error);
  2713. }
  2714. function isFunction(arg) {
  2715. return typeof arg === 'function';
  2716. }
  2717. function objectToString(o) {
  2718. return Object.prototype.toString.call(o);
  2719. }
  2720. function _extend(origin, add) {
  2721. // Don't do anything if add isn't an object
  2722. if (!add || !isObject(add)) return origin;
  2723. var keys = Object.keys(add);
  2724. var i = keys.length;
  2725. while (i--) {
  2726. origin[keys[i]] = add[keys[i]];
  2727. }
  2728. return origin;
  2729. }
  2730. function hasOwnProperty(obj, prop) {
  2731. return Object.prototype.hasOwnProperty.call(obj, prop);
  2732. }
  2733. function BufferList() {
  2734. this.head = null;
  2735. this.tail = null;
  2736. this.length = 0;
  2737. }
  2738. BufferList.prototype.push = function (v) {
  2739. var entry = { data: v, next: null };
  2740. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  2741. this.tail = entry;
  2742. ++this.length;
  2743. };
  2744. BufferList.prototype.unshift = function (v) {
  2745. var entry = { data: v, next: this.head };
  2746. if (this.length === 0) this.tail = entry;
  2747. this.head = entry;
  2748. ++this.length;
  2749. };
  2750. BufferList.prototype.shift = function () {
  2751. if (this.length === 0) return;
  2752. var ret = this.head.data;
  2753. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  2754. --this.length;
  2755. return ret;
  2756. };
  2757. BufferList.prototype.clear = function () {
  2758. this.head = this.tail = null;
  2759. this.length = 0;
  2760. };
  2761. BufferList.prototype.join = function (s) {
  2762. if (this.length === 0) return '';
  2763. var p = this.head;
  2764. var ret = '' + p.data;
  2765. while (p = p.next) {
  2766. ret += s + p.data;
  2767. }return ret;
  2768. };
  2769. BufferList.prototype.concat = function (n) {
  2770. if (this.length === 0) return Buffer.alloc(0);
  2771. if (this.length === 1) return this.head.data;
  2772. var ret = Buffer.allocUnsafe(n >>> 0);
  2773. var p = this.head;
  2774. var i = 0;
  2775. while (p) {
  2776. p.data.copy(ret, i);
  2777. i += p.data.length;
  2778. p = p.next;
  2779. }
  2780. return ret;
  2781. };
  2782. // Copyright Joyent, Inc. and other Node contributors.
  2783. //
  2784. // Permission is hereby granted, free of charge, to any person obtaining a
  2785. // copy of this software and associated documentation files (the
  2786. // "Software"), to deal in the Software without restriction, including
  2787. // without limitation the rights to use, copy, modify, merge, publish,
  2788. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2789. // persons to whom the Software is furnished to do so, subject to the
  2790. // following conditions:
  2791. //
  2792. // The above copyright notice and this permission notice shall be included
  2793. // in all copies or substantial portions of the Software.
  2794. //
  2795. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2796. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2797. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2798. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2799. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2800. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2801. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2802. var isBufferEncoding = Buffer.isEncoding
  2803. || function(encoding) {
  2804. switch (encoding && encoding.toLowerCase()) {
  2805. case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
  2806. default: return false;
  2807. }
  2808. };
  2809. function assertEncoding(encoding) {
  2810. if (encoding && !isBufferEncoding(encoding)) {
  2811. throw new Error('Unknown encoding: ' + encoding);
  2812. }
  2813. }
  2814. // StringDecoder provides an interface for efficiently splitting a series of
  2815. // buffers into a series of JS strings without breaking apart multi-byte
  2816. // characters. CESU-8 is handled as part of the UTF-8 encoding.
  2817. //
  2818. // @TODO Handling all encodings inside a single object makes it very difficult
  2819. // to reason about this code, so it should be split up in the future.
  2820. // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
  2821. // points as used by CESU-8.
  2822. function StringDecoder(encoding) {
  2823. this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
  2824. assertEncoding(encoding);
  2825. switch (this.encoding) {
  2826. case 'utf8':
  2827. // CESU-8 represents each of Surrogate Pair by 3-bytes
  2828. this.surrogateSize = 3;
  2829. break;
  2830. case 'ucs2':
  2831. case 'utf16le':
  2832. // UTF-16 represents each of Surrogate Pair by 2-bytes
  2833. this.surrogateSize = 2;
  2834. this.detectIncompleteChar = utf16DetectIncompleteChar;
  2835. break;
  2836. case 'base64':
  2837. // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
  2838. this.surrogateSize = 3;
  2839. this.detectIncompleteChar = base64DetectIncompleteChar;
  2840. break;
  2841. default:
  2842. this.write = passThroughWrite;
  2843. return;
  2844. }
  2845. // Enough space to store all bytes of a single character. UTF-8 needs 4
  2846. // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
  2847. this.charBuffer = new Buffer(6);
  2848. // Number of bytes received for the current incomplete multi-byte character.
  2849. this.charReceived = 0;
  2850. // Number of bytes expected for the current incomplete multi-byte character.
  2851. this.charLength = 0;
  2852. }
  2853. // write decodes the given buffer and returns it as JS string that is
  2854. // guaranteed to not contain any partial multi-byte characters. Any partial
  2855. // character found at the end of the buffer is buffered up, and will be
  2856. // returned when calling write again with the remaining bytes.
  2857. //
  2858. // Note: Converting a Buffer containing an orphan surrogate to a String
  2859. // currently works, but converting a String to a Buffer (via `new Buffer`, or
  2860. // Buffer#write) will replace incomplete surrogates with the unicode
  2861. // replacement character. See https://codereview.chromium.org/121173009/ .
  2862. StringDecoder.prototype.write = function(buffer) {
  2863. var charStr = '';
  2864. // if our last write ended with an incomplete multibyte character
  2865. while (this.charLength) {
  2866. // determine how many remaining bytes this buffer has to offer for this char
  2867. var available = (buffer.length >= this.charLength - this.charReceived) ?
  2868. this.charLength - this.charReceived :
  2869. buffer.length;
  2870. // add the new bytes to the char buffer
  2871. buffer.copy(this.charBuffer, this.charReceived, 0, available);
  2872. this.charReceived += available;
  2873. if (this.charReceived < this.charLength) {
  2874. // still not enough chars in this buffer? wait for more ...
  2875. return '';
  2876. }
  2877. // remove bytes belonging to the current character from the buffer
  2878. buffer = buffer.slice(available, buffer.length);
  2879. // get the character that was split
  2880. charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
  2881. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  2882. var charCode = charStr.charCodeAt(charStr.length - 1);
  2883. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  2884. this.charLength += this.surrogateSize;
  2885. charStr = '';
  2886. continue;
  2887. }
  2888. this.charReceived = this.charLength = 0;
  2889. // if there are no more bytes in this buffer, just emit our char
  2890. if (buffer.length === 0) {
  2891. return charStr;
  2892. }
  2893. break;
  2894. }
  2895. // determine and set charLength / charReceived
  2896. this.detectIncompleteChar(buffer);
  2897. var end = buffer.length;
  2898. if (this.charLength) {
  2899. // buffer the incomplete character bytes we got
  2900. buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
  2901. end -= this.charReceived;
  2902. }
  2903. charStr += buffer.toString(this.encoding, 0, end);
  2904. var end = charStr.length - 1;
  2905. var charCode = charStr.charCodeAt(end);
  2906. // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
  2907. if (charCode >= 0xD800 && charCode <= 0xDBFF) {
  2908. var size = this.surrogateSize;
  2909. this.charLength += size;
  2910. this.charReceived += size;
  2911. this.charBuffer.copy(this.charBuffer, size, 0, size);
  2912. buffer.copy(this.charBuffer, 0, 0, size);
  2913. return charStr.substring(0, end);
  2914. }
  2915. // or just emit the charStr
  2916. return charStr;
  2917. };
  2918. // detectIncompleteChar determines if there is an incomplete UTF-8 character at
  2919. // the end of the given buffer. If so, it sets this.charLength to the byte
  2920. // length that character, and sets this.charReceived to the number of bytes
  2921. // that are available for this character.
  2922. StringDecoder.prototype.detectIncompleteChar = function(buffer) {
  2923. // determine how many bytes we have to check at the end of this buffer
  2924. var i = (buffer.length >= 3) ? 3 : buffer.length;
  2925. // Figure out if one of the last i bytes of our buffer announces an
  2926. // incomplete char.
  2927. for (; i > 0; i--) {
  2928. var c = buffer[buffer.length - i];
  2929. // See http://en.wikipedia.org/wiki/UTF-8#Description
  2930. // 110XXXXX
  2931. if (i == 1 && c >> 5 == 0x06) {
  2932. this.charLength = 2;
  2933. break;
  2934. }
  2935. // 1110XXXX
  2936. if (i <= 2 && c >> 4 == 0x0E) {
  2937. this.charLength = 3;
  2938. break;
  2939. }
  2940. // 11110XXX
  2941. if (i <= 3 && c >> 3 == 0x1E) {
  2942. this.charLength = 4;
  2943. break;
  2944. }
  2945. }
  2946. this.charReceived = i;
  2947. };
  2948. StringDecoder.prototype.end = function(buffer) {
  2949. var res = '';
  2950. if (buffer && buffer.length)
  2951. res = this.write(buffer);
  2952. if (this.charReceived) {
  2953. var cr = this.charReceived;
  2954. var buf = this.charBuffer;
  2955. var enc = this.encoding;
  2956. res += buf.slice(0, cr).toString(enc);
  2957. }
  2958. return res;
  2959. };
  2960. function passThroughWrite(buffer) {
  2961. return buffer.toString(this.encoding);
  2962. }
  2963. function utf16DetectIncompleteChar(buffer) {
  2964. this.charReceived = buffer.length % 2;
  2965. this.charLength = this.charReceived ? 2 : 0;
  2966. }
  2967. function base64DetectIncompleteChar(buffer) {
  2968. this.charReceived = buffer.length % 3;
  2969. this.charLength = this.charReceived ? 3 : 0;
  2970. }
  2971. Readable.ReadableState = ReadableState;
  2972. var debug = debuglog('stream');
  2973. inherits$1(Readable, EventEmitter);
  2974. function prependListener(emitter, event, fn) {
  2975. // Sadly this is not cacheable as some libraries bundle their own
  2976. // event emitter implementation with them.
  2977. if (typeof emitter.prependListener === 'function') {
  2978. return emitter.prependListener(event, fn);
  2979. } else {
  2980. // This is a hack to make sure that our error handler is attached before any
  2981. // userland ones. NEVER DO THIS. This is here only because this code needs
  2982. // to continue to work with older versions of Node.js that do not include
  2983. // the prependListener() method. The goal is to eventually remove this hack.
  2984. if (!emitter._events || !emitter._events[event])
  2985. emitter.on(event, fn);
  2986. else if (Array.isArray(emitter._events[event]))
  2987. emitter._events[event].unshift(fn);
  2988. else
  2989. emitter._events[event] = [fn, emitter._events[event]];
  2990. }
  2991. }
  2992. function listenerCount (emitter, type) {
  2993. return emitter.listeners(type).length;
  2994. }
  2995. function ReadableState(options, stream) {
  2996. options = options || {};
  2997. // object stream flag. Used to make read(n) ignore n and to
  2998. // make all the buffer merging and length checks go away
  2999. this.objectMode = !!options.objectMode;
  3000. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  3001. // the point at which it stops calling _read() to fill the buffer
  3002. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  3003. var hwm = options.highWaterMark;
  3004. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  3005. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  3006. // cast to ints.
  3007. this.highWaterMark = ~ ~this.highWaterMark;
  3008. // A linked list is used to store data chunks instead of an array because the
  3009. // linked list can remove elements from the beginning faster than
  3010. // array.shift()
  3011. this.buffer = new BufferList();
  3012. this.length = 0;
  3013. this.pipes = null;
  3014. this.pipesCount = 0;
  3015. this.flowing = null;
  3016. this.ended = false;
  3017. this.endEmitted = false;
  3018. this.reading = false;
  3019. // a flag to be able to tell if the onwrite cb is called immediately,
  3020. // or on a later tick. We set this to true at first, because any
  3021. // actions that shouldn't happen until "later" should generally also
  3022. // not happen before the first write call.
  3023. this.sync = true;
  3024. // whenever we return null, then we set a flag to say
  3025. // that we're awaiting a 'readable' event emission.
  3026. this.needReadable = false;
  3027. this.emittedReadable = false;
  3028. this.readableListening = false;
  3029. this.resumeScheduled = false;
  3030. // Crypto is kind of old and crusty. Historically, its default string
  3031. // encoding is 'binary' so we have to make this configurable.
  3032. // Everything else in the universe uses 'utf8', though.
  3033. this.defaultEncoding = options.defaultEncoding || 'utf8';
  3034. // when piping, we only care about 'readable' events that happen
  3035. // after read()ing all the bytes and not getting any pushback.
  3036. this.ranOut = false;
  3037. // the number of writers that are awaiting a drain event in .pipe()s
  3038. this.awaitDrain = 0;
  3039. // if true, a maybeReadMore has been scheduled
  3040. this.readingMore = false;
  3041. this.decoder = null;
  3042. this.encoding = null;
  3043. if (options.encoding) {
  3044. this.decoder = new StringDecoder(options.encoding);
  3045. this.encoding = options.encoding;
  3046. }
  3047. }
  3048. function Readable(options) {
  3049. if (!(this instanceof Readable)) return new Readable(options);
  3050. this._readableState = new ReadableState(options, this);
  3051. // legacy
  3052. this.readable = true;
  3053. if (options && typeof options.read === 'function') this._read = options.read;
  3054. EventEmitter.call(this);
  3055. }
  3056. // Manually shove something into the read() buffer.
  3057. // This returns true if the highWaterMark has not been hit yet,
  3058. // similar to how Writable.write() returns true if you should
  3059. // write() some more.
  3060. Readable.prototype.push = function (chunk, encoding) {
  3061. var state = this._readableState;
  3062. if (!state.objectMode && typeof chunk === 'string') {
  3063. encoding = encoding || state.defaultEncoding;
  3064. if (encoding !== state.encoding) {
  3065. chunk = Buffer.from(chunk, encoding);
  3066. encoding = '';
  3067. }
  3068. }
  3069. return readableAddChunk(this, state, chunk, encoding, false);
  3070. };
  3071. // Unshift should *always* be something directly out of read()
  3072. Readable.prototype.unshift = function (chunk) {
  3073. var state = this._readableState;
  3074. return readableAddChunk(this, state, chunk, '', true);
  3075. };
  3076. Readable.prototype.isPaused = function () {
  3077. return this._readableState.flowing === false;
  3078. };
  3079. function readableAddChunk(stream, state, chunk, encoding, addToFront) {
  3080. var er = chunkInvalid(state, chunk);
  3081. if (er) {
  3082. stream.emit('error', er);
  3083. } else if (chunk === null) {
  3084. state.reading = false;
  3085. onEofChunk(stream, state);
  3086. } else if (state.objectMode || chunk && chunk.length > 0) {
  3087. if (state.ended && !addToFront) {
  3088. var e = new Error('stream.push() after EOF');
  3089. stream.emit('error', e);
  3090. } else if (state.endEmitted && addToFront) {
  3091. var _e = new Error('stream.unshift() after end event');
  3092. stream.emit('error', _e);
  3093. } else {
  3094. var skipAdd;
  3095. if (state.decoder && !addToFront && !encoding) {
  3096. chunk = state.decoder.write(chunk);
  3097. skipAdd = !state.objectMode && chunk.length === 0;
  3098. }
  3099. if (!addToFront) state.reading = false;
  3100. // Don't add to the buffer if we've decoded to an empty string chunk and
  3101. // we're not in object mode
  3102. if (!skipAdd) {
  3103. // if we want the data now, just emit it.
  3104. if (state.flowing && state.length === 0 && !state.sync) {
  3105. stream.emit('data', chunk);
  3106. stream.read(0);
  3107. } else {
  3108. // update the buffer info.
  3109. state.length += state.objectMode ? 1 : chunk.length;
  3110. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  3111. if (state.needReadable) emitReadable(stream);
  3112. }
  3113. }
  3114. maybeReadMore(stream, state);
  3115. }
  3116. } else if (!addToFront) {
  3117. state.reading = false;
  3118. }
  3119. return needMoreData(state);
  3120. }
  3121. // if it's past the high water mark, we can push in some more.
  3122. // Also, if we have no data yet, we can stand some
  3123. // more bytes. This is to work around cases where hwm=0,
  3124. // such as the repl. Also, if the push() triggered a
  3125. // readable event, and the user called read(largeNumber) such that
  3126. // needReadable was set, then we ought to push more, so that another
  3127. // 'readable' event will be triggered.
  3128. function needMoreData(state) {
  3129. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  3130. }
  3131. // backwards compatibility.
  3132. Readable.prototype.setEncoding = function (enc) {
  3133. this._readableState.decoder = new StringDecoder(enc);
  3134. this._readableState.encoding = enc;
  3135. return this;
  3136. };
  3137. // Don't raise the hwm > 8MB
  3138. var MAX_HWM = 0x800000;
  3139. function computeNewHighWaterMark(n) {
  3140. if (n >= MAX_HWM) {
  3141. n = MAX_HWM;
  3142. } else {
  3143. // Get the next highest power of 2 to prevent increasing hwm excessively in
  3144. // tiny amounts
  3145. n--;
  3146. n |= n >>> 1;
  3147. n |= n >>> 2;
  3148. n |= n >>> 4;
  3149. n |= n >>> 8;
  3150. n |= n >>> 16;
  3151. n++;
  3152. }
  3153. return n;
  3154. }
  3155. // This function is designed to be inlinable, so please take care when making
  3156. // changes to the function body.
  3157. function howMuchToRead(n, state) {
  3158. if (n <= 0 || state.length === 0 && state.ended) return 0;
  3159. if (state.objectMode) return 1;
  3160. if (n !== n) {
  3161. // Only flow one buffer at a time
  3162. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  3163. }
  3164. // If we're asking for more than the current hwm, then raise the hwm.
  3165. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  3166. if (n <= state.length) return n;
  3167. // Don't have enough
  3168. if (!state.ended) {
  3169. state.needReadable = true;
  3170. return 0;
  3171. }
  3172. return state.length;
  3173. }
  3174. // you can override either this method, or the async _read(n) below.
  3175. Readable.prototype.read = function (n) {
  3176. debug('read', n);
  3177. n = parseInt(n, 10);
  3178. var state = this._readableState;
  3179. var nOrig = n;
  3180. if (n !== 0) state.emittedReadable = false;
  3181. // if we're doing read(0) to trigger a readable event, but we
  3182. // already have a bunch of data in the buffer, then just trigger
  3183. // the 'readable' event and move on.
  3184. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  3185. debug('read: emitReadable', state.length, state.ended);
  3186. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  3187. return null;
  3188. }
  3189. n = howMuchToRead(n, state);
  3190. // if we've ended, and we're now clear, then finish it up.
  3191. if (n === 0 && state.ended) {
  3192. if (state.length === 0) endReadable(this);
  3193. return null;
  3194. }
  3195. // All the actual chunk generation logic needs to be
  3196. // *below* the call to _read. The reason is that in certain
  3197. // synthetic stream cases, such as passthrough streams, _read
  3198. // may be a completely synchronous operation which may change
  3199. // the state of the read buffer, providing enough data when
  3200. // before there was *not* enough.
  3201. //
  3202. // So, the steps are:
  3203. // 1. Figure out what the state of things will be after we do
  3204. // a read from the buffer.
  3205. //
  3206. // 2. If that resulting state will trigger a _read, then call _read.
  3207. // Note that this may be asynchronous, or synchronous. Yes, it is
  3208. // deeply ugly to write APIs this way, but that still doesn't mean
  3209. // that the Readable class should behave improperly, as streams are
  3210. // designed to be sync/async agnostic.
  3211. // Take note if the _read call is sync or async (ie, if the read call
  3212. // has returned yet), so that we know whether or not it's safe to emit
  3213. // 'readable' etc.
  3214. //
  3215. // 3. Actually pull the requested chunks out of the buffer and return.
  3216. // if we need a readable event, then we need to do some reading.
  3217. var doRead = state.needReadable;
  3218. debug('need readable', doRead);
  3219. // if we currently have less than the highWaterMark, then also read some
  3220. if (state.length === 0 || state.length - n < state.highWaterMark) {
  3221. doRead = true;
  3222. debug('length less than watermark', doRead);
  3223. }
  3224. // however, if we've ended, then there's no point, and if we're already
  3225. // reading, then it's unnecessary.
  3226. if (state.ended || state.reading) {
  3227. doRead = false;
  3228. debug('reading or ended', doRead);
  3229. } else if (doRead) {
  3230. debug('do read');
  3231. state.reading = true;
  3232. state.sync = true;
  3233. // if the length is currently zero, then we *need* a readable event.
  3234. if (state.length === 0) state.needReadable = true;
  3235. // call internal read method
  3236. this._read(state.highWaterMark);
  3237. state.sync = false;
  3238. // If _read pushed data synchronously, then `reading` will be false,
  3239. // and we need to re-evaluate how much data we can return to the user.
  3240. if (!state.reading) n = howMuchToRead(nOrig, state);
  3241. }
  3242. var ret;
  3243. if (n > 0) ret = fromList(n, state);else ret = null;
  3244. if (ret === null) {
  3245. state.needReadable = true;
  3246. n = 0;
  3247. } else {
  3248. state.length -= n;
  3249. }
  3250. if (state.length === 0) {
  3251. // If we have nothing in the buffer, then we want to know
  3252. // as soon as we *do* get something into the buffer.
  3253. if (!state.ended) state.needReadable = true;
  3254. // If we tried to read() past the EOF, then emit end on the next tick.
  3255. if (nOrig !== n && state.ended) endReadable(this);
  3256. }
  3257. if (ret !== null) this.emit('data', ret);
  3258. return ret;
  3259. };
  3260. function chunkInvalid(state, chunk) {
  3261. var er = null;
  3262. if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
  3263. er = new TypeError('Invalid non-string/buffer chunk');
  3264. }
  3265. return er;
  3266. }
  3267. function onEofChunk(stream, state) {
  3268. if (state.ended) return;
  3269. if (state.decoder) {
  3270. var chunk = state.decoder.end();
  3271. if (chunk && chunk.length) {
  3272. state.buffer.push(chunk);
  3273. state.length += state.objectMode ? 1 : chunk.length;
  3274. }
  3275. }
  3276. state.ended = true;
  3277. // emit 'readable' now to make sure it gets picked up.
  3278. emitReadable(stream);
  3279. }
  3280. // Don't emit readable right away in sync mode, because this can trigger
  3281. // another read() call => stack overflow. This way, it might trigger
  3282. // a nextTick recursion warning, but that's not so bad.
  3283. function emitReadable(stream) {
  3284. var state = stream._readableState;
  3285. state.needReadable = false;
  3286. if (!state.emittedReadable) {
  3287. debug('emitReadable', state.flowing);
  3288. state.emittedReadable = true;
  3289. if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream);
  3290. }
  3291. }
  3292. function emitReadable_(stream) {
  3293. debug('emit readable');
  3294. stream.emit('readable');
  3295. flow(stream);
  3296. }
  3297. // at this point, the user has presumably seen the 'readable' event,
  3298. // and called read() to consume some data. that may have triggered
  3299. // in turn another _read(n) call, in which case reading = true if
  3300. // it's in progress.
  3301. // However, if we're not ended, or reading, and the length < hwm,
  3302. // then go ahead and try to read some more preemptively.
  3303. function maybeReadMore(stream, state) {
  3304. if (!state.readingMore) {
  3305. state.readingMore = true;
  3306. nextTick(maybeReadMore_, stream, state);
  3307. }
  3308. }
  3309. function maybeReadMore_(stream, state) {
  3310. var len = state.length;
  3311. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  3312. debug('maybeReadMore read 0');
  3313. stream.read(0);
  3314. if (len === state.length)
  3315. // didn't get any data, stop spinning.
  3316. break;else len = state.length;
  3317. }
  3318. state.readingMore = false;
  3319. }
  3320. // abstract method. to be overridden in specific implementation classes.
  3321. // call cb(er, data) where data is <= n in length.
  3322. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  3323. // arbitrary, and perhaps not very meaningful.
  3324. Readable.prototype._read = function (n) {
  3325. this.emit('error', new Error('not implemented'));
  3326. };
  3327. Readable.prototype.pipe = function (dest, pipeOpts) {
  3328. var src = this;
  3329. var state = this._readableState;
  3330. switch (state.pipesCount) {
  3331. case 0:
  3332. state.pipes = dest;
  3333. break;
  3334. case 1:
  3335. state.pipes = [state.pipes, dest];
  3336. break;
  3337. default:
  3338. state.pipes.push(dest);
  3339. break;
  3340. }
  3341. state.pipesCount += 1;
  3342. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  3343. var doEnd = (!pipeOpts || pipeOpts.end !== false);
  3344. var endFn = doEnd ? onend : cleanup;
  3345. if (state.endEmitted) nextTick(endFn);else src.once('end', endFn);
  3346. dest.on('unpipe', onunpipe);
  3347. function onunpipe(readable) {
  3348. debug('onunpipe');
  3349. if (readable === src) {
  3350. cleanup();
  3351. }
  3352. }
  3353. function onend() {
  3354. debug('onend');
  3355. dest.end();
  3356. }
  3357. // when the dest drains, it reduces the awaitDrain counter
  3358. // on the source. This would be more elegant with a .once()
  3359. // handler in flow(), but adding and removing repeatedly is
  3360. // too slow.
  3361. var ondrain = pipeOnDrain(src);
  3362. dest.on('drain', ondrain);
  3363. var cleanedUp = false;
  3364. function cleanup() {
  3365. debug('cleanup');
  3366. // cleanup event handlers once the pipe is broken
  3367. dest.removeListener('close', onclose);
  3368. dest.removeListener('finish', onfinish);
  3369. dest.removeListener('drain', ondrain);
  3370. dest.removeListener('error', onerror);
  3371. dest.removeListener('unpipe', onunpipe);
  3372. src.removeListener('end', onend);
  3373. src.removeListener('end', cleanup);
  3374. src.removeListener('data', ondata);
  3375. cleanedUp = true;
  3376. // if the reader is waiting for a drain event from this
  3377. // specific writer, then it would cause it to never start
  3378. // flowing again.
  3379. // So, if this is awaiting a drain, then we just call it now.
  3380. // If we don't know, then assume that we are waiting for one.
  3381. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  3382. }
  3383. // If the user pushes more data while we're writing to dest then we'll end up
  3384. // in ondata again. However, we only want to increase awaitDrain once because
  3385. // dest will only emit one 'drain' event for the multiple writes.
  3386. // => Introduce a guard on increasing awaitDrain.
  3387. var increasedAwaitDrain = false;
  3388. src.on('data', ondata);
  3389. function ondata(chunk) {
  3390. debug('ondata');
  3391. increasedAwaitDrain = false;
  3392. var ret = dest.write(chunk);
  3393. if (false === ret && !increasedAwaitDrain) {
  3394. // If the user unpiped during `dest.write()`, it is possible
  3395. // to get stuck in a permanently paused state if that write
  3396. // also returned false.
  3397. // => Check whether `dest` is still a piping destination.
  3398. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  3399. debug('false write response, pause', src._readableState.awaitDrain);
  3400. src._readableState.awaitDrain++;
  3401. increasedAwaitDrain = true;
  3402. }
  3403. src.pause();
  3404. }
  3405. }
  3406. // if the dest has an error, then stop piping into it.
  3407. // however, don't suppress the throwing behavior for this.
  3408. function onerror(er) {
  3409. debug('onerror', er);
  3410. unpipe();
  3411. dest.removeListener('error', onerror);
  3412. if (listenerCount(dest, 'error') === 0) dest.emit('error', er);
  3413. }
  3414. // Make sure our error handler is attached before userland ones.
  3415. prependListener(dest, 'error', onerror);
  3416. // Both close and finish should trigger unpipe, but only once.
  3417. function onclose() {
  3418. dest.removeListener('finish', onfinish);
  3419. unpipe();
  3420. }
  3421. dest.once('close', onclose);
  3422. function onfinish() {
  3423. debug('onfinish');
  3424. dest.removeListener('close', onclose);
  3425. unpipe();
  3426. }
  3427. dest.once('finish', onfinish);
  3428. function unpipe() {
  3429. debug('unpipe');
  3430. src.unpipe(dest);
  3431. }
  3432. // tell the dest that it's being piped to
  3433. dest.emit('pipe', src);
  3434. // start the flow if it hasn't been started already.
  3435. if (!state.flowing) {
  3436. debug('pipe resume');
  3437. src.resume();
  3438. }
  3439. return dest;
  3440. };
  3441. function pipeOnDrain(src) {
  3442. return function () {
  3443. var state = src._readableState;
  3444. debug('pipeOnDrain', state.awaitDrain);
  3445. if (state.awaitDrain) state.awaitDrain--;
  3446. if (state.awaitDrain === 0 && src.listeners('data').length) {
  3447. state.flowing = true;
  3448. flow(src);
  3449. }
  3450. };
  3451. }
  3452. Readable.prototype.unpipe = function (dest) {
  3453. var state = this._readableState;
  3454. // if we're not piping anywhere, then do nothing.
  3455. if (state.pipesCount === 0) return this;
  3456. // just one destination. most common case.
  3457. if (state.pipesCount === 1) {
  3458. // passed in one, but it's not the right one.
  3459. if (dest && dest !== state.pipes) return this;
  3460. if (!dest) dest = state.pipes;
  3461. // got a match.
  3462. state.pipes = null;
  3463. state.pipesCount = 0;
  3464. state.flowing = false;
  3465. if (dest) dest.emit('unpipe', this);
  3466. return this;
  3467. }
  3468. // slow case. multiple pipe destinations.
  3469. if (!dest) {
  3470. // remove all.
  3471. var dests = state.pipes;
  3472. var len = state.pipesCount;
  3473. state.pipes = null;
  3474. state.pipesCount = 0;
  3475. state.flowing = false;
  3476. for (var _i = 0; _i < len; _i++) {
  3477. dests[_i].emit('unpipe', this);
  3478. }return this;
  3479. }
  3480. // try to find the right one.
  3481. var i = indexOf(state.pipes, dest);
  3482. if (i === -1) return this;
  3483. state.pipes.splice(i, 1);
  3484. state.pipesCount -= 1;
  3485. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  3486. dest.emit('unpipe', this);
  3487. return this;
  3488. };
  3489. // set up data events if they are asked for
  3490. // Ensure readable listeners eventually get something
  3491. Readable.prototype.on = function (ev, fn) {
  3492. var res = EventEmitter.prototype.on.call(this, ev, fn);
  3493. if (ev === 'data') {
  3494. // Start flowing on next tick if stream isn't explicitly paused
  3495. if (this._readableState.flowing !== false) this.resume();
  3496. } else if (ev === 'readable') {
  3497. var state = this._readableState;
  3498. if (!state.endEmitted && !state.readableListening) {
  3499. state.readableListening = state.needReadable = true;
  3500. state.emittedReadable = false;
  3501. if (!state.reading) {
  3502. nextTick(nReadingNextTick, this);
  3503. } else if (state.length) {
  3504. emitReadable(this);
  3505. }
  3506. }
  3507. }
  3508. return res;
  3509. };
  3510. Readable.prototype.addListener = Readable.prototype.on;
  3511. function nReadingNextTick(self) {
  3512. debug('readable nexttick read 0');
  3513. self.read(0);
  3514. }
  3515. // pause() and resume() are remnants of the legacy readable stream API
  3516. // If the user uses them, then switch into old mode.
  3517. Readable.prototype.resume = function () {
  3518. var state = this._readableState;
  3519. if (!state.flowing) {
  3520. debug('resume');
  3521. state.flowing = true;
  3522. resume(this, state);
  3523. }
  3524. return this;
  3525. };
  3526. function resume(stream, state) {
  3527. if (!state.resumeScheduled) {
  3528. state.resumeScheduled = true;
  3529. nextTick(resume_, stream, state);
  3530. }
  3531. }
  3532. function resume_(stream, state) {
  3533. if (!state.reading) {
  3534. debug('resume read 0');
  3535. stream.read(0);
  3536. }
  3537. state.resumeScheduled = false;
  3538. state.awaitDrain = 0;
  3539. stream.emit('resume');
  3540. flow(stream);
  3541. if (state.flowing && !state.reading) stream.read(0);
  3542. }
  3543. Readable.prototype.pause = function () {
  3544. debug('call pause flowing=%j', this._readableState.flowing);
  3545. if (false !== this._readableState.flowing) {
  3546. debug('pause');
  3547. this._readableState.flowing = false;
  3548. this.emit('pause');
  3549. }
  3550. return this;
  3551. };
  3552. function flow(stream) {
  3553. var state = stream._readableState;
  3554. debug('flow', state.flowing);
  3555. while (state.flowing && stream.read() !== null) {}
  3556. }
  3557. // wrap an old-style stream as the async data source.
  3558. // This is *not* part of the readable stream interface.
  3559. // It is an ugly unfortunate mess of history.
  3560. Readable.prototype.wrap = function (stream) {
  3561. var state = this._readableState;
  3562. var paused = false;
  3563. var self = this;
  3564. stream.on('end', function () {
  3565. debug('wrapped end');
  3566. if (state.decoder && !state.ended) {
  3567. var chunk = state.decoder.end();
  3568. if (chunk && chunk.length) self.push(chunk);
  3569. }
  3570. self.push(null);
  3571. });
  3572. stream.on('data', function (chunk) {
  3573. debug('wrapped data');
  3574. if (state.decoder) chunk = state.decoder.write(chunk);
  3575. // don't skip over falsy values in objectMode
  3576. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  3577. var ret = self.push(chunk);
  3578. if (!ret) {
  3579. paused = true;
  3580. stream.pause();
  3581. }
  3582. });
  3583. // proxy all the other methods.
  3584. // important when wrapping filters and duplexes.
  3585. for (var i in stream) {
  3586. if (this[i] === undefined && typeof stream[i] === 'function') {
  3587. this[i] = function (method) {
  3588. return function () {
  3589. return stream[method].apply(stream, arguments);
  3590. };
  3591. }(i);
  3592. }
  3593. }
  3594. // proxy certain important events.
  3595. var events = ['error', 'close', 'destroy', 'pause', 'resume'];
  3596. forEach(events, function (ev) {
  3597. stream.on(ev, self.emit.bind(self, ev));
  3598. });
  3599. // when we try to consume some more bytes, simply unpause the
  3600. // underlying stream.
  3601. self._read = function (n) {
  3602. debug('wrapped _read', n);
  3603. if (paused) {
  3604. paused = false;
  3605. stream.resume();
  3606. }
  3607. };
  3608. return self;
  3609. };
  3610. // exposed for testing purposes only.
  3611. Readable._fromList = fromList;
  3612. // Pluck off n bytes from an array of buffers.
  3613. // Length is the combined lengths of all the buffers in the list.
  3614. // This function is designed to be inlinable, so please take care when making
  3615. // changes to the function body.
  3616. function fromList(n, state) {
  3617. // nothing buffered
  3618. if (state.length === 0) return null;
  3619. var ret;
  3620. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  3621. // read it all, truncate the list
  3622. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  3623. state.buffer.clear();
  3624. } else {
  3625. // read part of list
  3626. ret = fromListPartial(n, state.buffer, state.decoder);
  3627. }
  3628. return ret;
  3629. }
  3630. // Extracts only enough buffered data to satisfy the amount requested.
  3631. // This function is designed to be inlinable, so please take care when making
  3632. // changes to the function body.
  3633. function fromListPartial(n, list, hasStrings) {
  3634. var ret;
  3635. if (n < list.head.data.length) {
  3636. // slice is the same for buffers and strings
  3637. ret = list.head.data.slice(0, n);
  3638. list.head.data = list.head.data.slice(n);
  3639. } else if (n === list.head.data.length) {
  3640. // first chunk is a perfect match
  3641. ret = list.shift();
  3642. } else {
  3643. // result spans more than one buffer
  3644. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  3645. }
  3646. return ret;
  3647. }
  3648. // Copies a specified amount of characters from the list of buffered data
  3649. // chunks.
  3650. // This function is designed to be inlinable, so please take care when making
  3651. // changes to the function body.
  3652. function copyFromBufferString(n, list) {
  3653. var p = list.head;
  3654. var c = 1;
  3655. var ret = p.data;
  3656. n -= ret.length;
  3657. while (p = p.next) {
  3658. var str = p.data;
  3659. var nb = n > str.length ? str.length : n;
  3660. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  3661. n -= nb;
  3662. if (n === 0) {
  3663. if (nb === str.length) {
  3664. ++c;
  3665. if (p.next) list.head = p.next;else list.head = list.tail = null;
  3666. } else {
  3667. list.head = p;
  3668. p.data = str.slice(nb);
  3669. }
  3670. break;
  3671. }
  3672. ++c;
  3673. }
  3674. list.length -= c;
  3675. return ret;
  3676. }
  3677. // Copies a specified amount of bytes from the list of buffered data chunks.
  3678. // This function is designed to be inlinable, so please take care when making
  3679. // changes to the function body.
  3680. function copyFromBuffer(n, list) {
  3681. var ret = Buffer.allocUnsafe(n);
  3682. var p = list.head;
  3683. var c = 1;
  3684. p.data.copy(ret);
  3685. n -= p.data.length;
  3686. while (p = p.next) {
  3687. var buf = p.data;
  3688. var nb = n > buf.length ? buf.length : n;
  3689. buf.copy(ret, ret.length - n, 0, nb);
  3690. n -= nb;
  3691. if (n === 0) {
  3692. if (nb === buf.length) {
  3693. ++c;
  3694. if (p.next) list.head = p.next;else list.head = list.tail = null;
  3695. } else {
  3696. list.head = p;
  3697. p.data = buf.slice(nb);
  3698. }
  3699. break;
  3700. }
  3701. ++c;
  3702. }
  3703. list.length -= c;
  3704. return ret;
  3705. }
  3706. function endReadable(stream) {
  3707. var state = stream._readableState;
  3708. // If we get here before consuming all the bytes, then that is a
  3709. // bug in node. Should never happen.
  3710. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  3711. if (!state.endEmitted) {
  3712. state.ended = true;
  3713. nextTick(endReadableNT, state, stream);
  3714. }
  3715. }
  3716. function endReadableNT(state, stream) {
  3717. // Check that we didn't get one last unshift.
  3718. if (!state.endEmitted && state.length === 0) {
  3719. state.endEmitted = true;
  3720. stream.readable = false;
  3721. stream.emit('end');
  3722. }
  3723. }
  3724. function forEach(xs, f) {
  3725. for (var i = 0, l = xs.length; i < l; i++) {
  3726. f(xs[i], i);
  3727. }
  3728. }
  3729. function indexOf(xs, x) {
  3730. for (var i = 0, l = xs.length; i < l; i++) {
  3731. if (xs[i] === x) return i;
  3732. }
  3733. return -1;
  3734. }
  3735. // A bit simpler than readable streams.
  3736. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  3737. // the drain event emission and buffering.
  3738. Writable.WritableState = WritableState;
  3739. inherits$1(Writable, EventEmitter);
  3740. function nop() {}
  3741. function WriteReq(chunk, encoding, cb) {
  3742. this.chunk = chunk;
  3743. this.encoding = encoding;
  3744. this.callback = cb;
  3745. this.next = null;
  3746. }
  3747. function WritableState(options, stream) {
  3748. Object.defineProperty(this, 'buffer', {
  3749. get: deprecate(function () {
  3750. return this.getBuffer();
  3751. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
  3752. });
  3753. options = options || {};
  3754. // object stream flag to indicate whether or not this stream
  3755. // contains buffers or objects.
  3756. this.objectMode = !!options.objectMode;
  3757. if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  3758. // the point at which write() starts returning false
  3759. // Note: 0 is a valid value, means that we always return false if
  3760. // the entire buffer is not flushed immediately on write()
  3761. var hwm = options.highWaterMark;
  3762. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  3763. this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
  3764. // cast to ints.
  3765. this.highWaterMark = ~ ~this.highWaterMark;
  3766. this.needDrain = false;
  3767. // at the start of calling end()
  3768. this.ending = false;
  3769. // when end() has been called, and returned
  3770. this.ended = false;
  3771. // when 'finish' is emitted
  3772. this.finished = false;
  3773. // should we decode strings into buffers before passing to _write?
  3774. // this is here so that some node-core streams can optimize string
  3775. // handling at a lower level.
  3776. var noDecode = options.decodeStrings === false;
  3777. this.decodeStrings = !noDecode;
  3778. // Crypto is kind of old and crusty. Historically, its default string
  3779. // encoding is 'binary' so we have to make this configurable.
  3780. // Everything else in the universe uses 'utf8', though.
  3781. this.defaultEncoding = options.defaultEncoding || 'utf8';
  3782. // not an actual buffer we keep track of, but a measurement
  3783. // of how much we're waiting to get pushed to some underlying
  3784. // socket or file.
  3785. this.length = 0;
  3786. // a flag to see when we're in the middle of a write.
  3787. this.writing = false;
  3788. // when true all writes will be buffered until .uncork() call
  3789. this.corked = 0;
  3790. // a flag to be able to tell if the onwrite cb is called immediately,
  3791. // or on a later tick. We set this to true at first, because any
  3792. // actions that shouldn't happen until "later" should generally also
  3793. // not happen before the first write call.
  3794. this.sync = true;
  3795. // a flag to know if we're processing previously buffered items, which
  3796. // may call the _write() callback in the same tick, so that we don't
  3797. // end up in an overlapped onwrite situation.
  3798. this.bufferProcessing = false;
  3799. // the callback that's passed to _write(chunk,cb)
  3800. this.onwrite = function (er) {
  3801. onwrite(stream, er);
  3802. };
  3803. // the callback that the user supplies to write(chunk,encoding,cb)
  3804. this.writecb = null;
  3805. // the amount that is being written when _write is called.
  3806. this.writelen = 0;
  3807. this.bufferedRequest = null;
  3808. this.lastBufferedRequest = null;
  3809. // number of pending user-supplied write callbacks
  3810. // this must be 0 before 'finish' can be emitted
  3811. this.pendingcb = 0;
  3812. // emit prefinish if the only thing we're waiting for is _write cbs
  3813. // This is relevant for synchronous Transform streams
  3814. this.prefinished = false;
  3815. // True if the error was already emitted and should not be thrown again
  3816. this.errorEmitted = false;
  3817. // count buffered requests
  3818. this.bufferedRequestCount = 0;
  3819. // allocate the first CorkedRequest, there is always
  3820. // one allocated and free to use, and we maintain at most two
  3821. this.corkedRequestsFree = new CorkedRequest(this);
  3822. }
  3823. WritableState.prototype.getBuffer = function writableStateGetBuffer() {
  3824. var current = this.bufferedRequest;
  3825. var out = [];
  3826. while (current) {
  3827. out.push(current);
  3828. current = current.next;
  3829. }
  3830. return out;
  3831. };
  3832. function Writable(options) {
  3833. // Writable ctor is applied to Duplexes, though they're not
  3834. // instanceof Writable, they're instanceof Readable.
  3835. if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);
  3836. this._writableState = new WritableState(options, this);
  3837. // legacy.
  3838. this.writable = true;
  3839. if (options) {
  3840. if (typeof options.write === 'function') this._write = options.write;
  3841. if (typeof options.writev === 'function') this._writev = options.writev;
  3842. }
  3843. EventEmitter.call(this);
  3844. }
  3845. // Otherwise people can pipe Writable streams, which is just wrong.
  3846. Writable.prototype.pipe = function () {
  3847. this.emit('error', new Error('Cannot pipe, not readable'));
  3848. };
  3849. function writeAfterEnd(stream, cb) {
  3850. var er = new Error('write after end');
  3851. // TODO: defer error events consistently everywhere, not just the cb
  3852. stream.emit('error', er);
  3853. nextTick(cb, er);
  3854. }
  3855. // If we get something that is not a buffer, string, null, or undefined,
  3856. // and we're not in objectMode, then that's an error.
  3857. // Otherwise stream chunks are all considered to be of length=1, and the
  3858. // watermarks determine how many objects to keep in the buffer, rather than
  3859. // how many bytes or characters.
  3860. function validChunk(stream, state, chunk, cb) {
  3861. var valid = true;
  3862. var er = false;
  3863. // Always throw error if a null is written
  3864. // if we are not in object mode then throw
  3865. // if it is not a buffer, string, or undefined.
  3866. if (chunk === null) {
  3867. er = new TypeError('May not write null values to stream');
  3868. } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  3869. er = new TypeError('Invalid non-string/buffer chunk');
  3870. }
  3871. if (er) {
  3872. stream.emit('error', er);
  3873. nextTick(cb, er);
  3874. valid = false;
  3875. }
  3876. return valid;
  3877. }
  3878. Writable.prototype.write = function (chunk, encoding, cb) {
  3879. var state = this._writableState;
  3880. var ret = false;
  3881. if (typeof encoding === 'function') {
  3882. cb = encoding;
  3883. encoding = null;
  3884. }
  3885. if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  3886. if (typeof cb !== 'function') cb = nop;
  3887. if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {
  3888. state.pendingcb++;
  3889. ret = writeOrBuffer(this, state, chunk, encoding, cb);
  3890. }
  3891. return ret;
  3892. };
  3893. Writable.prototype.cork = function () {
  3894. var state = this._writableState;
  3895. state.corked++;
  3896. };
  3897. Writable.prototype.uncork = function () {
  3898. var state = this._writableState;
  3899. if (state.corked) {
  3900. state.corked--;
  3901. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  3902. }
  3903. };
  3904. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  3905. // node::ParseEncoding() requires lower case.
  3906. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  3907. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  3908. this._writableState.defaultEncoding = encoding;
  3909. return this;
  3910. };
  3911. function decodeChunk(state, chunk, encoding) {
  3912. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  3913. chunk = Buffer.from(chunk, encoding);
  3914. }
  3915. return chunk;
  3916. }
  3917. // if we're already writing something, then just put this
  3918. // in the queue, and wait our turn. Otherwise, call _write
  3919. // If we return false, then we need a drain event, so set that flag.
  3920. function writeOrBuffer(stream, state, chunk, encoding, cb) {
  3921. chunk = decodeChunk(state, chunk, encoding);
  3922. if (Buffer.isBuffer(chunk)) encoding = 'buffer';
  3923. var len = state.objectMode ? 1 : chunk.length;
  3924. state.length += len;
  3925. var ret = state.length < state.highWaterMark;
  3926. // we must ensure that previous needDrain will not be reset to false.
  3927. if (!ret) state.needDrain = true;
  3928. if (state.writing || state.corked) {
  3929. var last = state.lastBufferedRequest;
  3930. state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
  3931. if (last) {
  3932. last.next = state.lastBufferedRequest;
  3933. } else {
  3934. state.bufferedRequest = state.lastBufferedRequest;
  3935. }
  3936. state.bufferedRequestCount += 1;
  3937. } else {
  3938. doWrite(stream, state, false, len, chunk, encoding, cb);
  3939. }
  3940. return ret;
  3941. }
  3942. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  3943. state.writelen = len;
  3944. state.writecb = cb;
  3945. state.writing = true;
  3946. state.sync = true;
  3947. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  3948. state.sync = false;
  3949. }
  3950. function onwriteError(stream, state, sync, er, cb) {
  3951. --state.pendingcb;
  3952. if (sync) nextTick(cb, er);else cb(er);
  3953. stream._writableState.errorEmitted = true;
  3954. stream.emit('error', er);
  3955. }
  3956. function onwriteStateUpdate(state) {
  3957. state.writing = false;
  3958. state.writecb = null;
  3959. state.length -= state.writelen;
  3960. state.writelen = 0;
  3961. }
  3962. function onwrite(stream, er) {
  3963. var state = stream._writableState;
  3964. var sync = state.sync;
  3965. var cb = state.writecb;
  3966. onwriteStateUpdate(state);
  3967. if (er) onwriteError(stream, state, sync, er, cb);else {
  3968. // Check if we're actually ready to finish, but don't emit yet
  3969. var finished = needFinish(state);
  3970. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  3971. clearBuffer(stream, state);
  3972. }
  3973. if (sync) {
  3974. /*<replacement>*/
  3975. nextTick(afterWrite, stream, state, finished, cb);
  3976. /*</replacement>*/
  3977. } else {
  3978. afterWrite(stream, state, finished, cb);
  3979. }
  3980. }
  3981. }
  3982. function afterWrite(stream, state, finished, cb) {
  3983. if (!finished) onwriteDrain(stream, state);
  3984. state.pendingcb--;
  3985. cb();
  3986. finishMaybe(stream, state);
  3987. }
  3988. // Must force callback to be called on nextTick, so that we don't
  3989. // emit 'drain' before the write() consumer gets the 'false' return
  3990. // value, and has a chance to attach a 'drain' listener.
  3991. function onwriteDrain(stream, state) {
  3992. if (state.length === 0 && state.needDrain) {
  3993. state.needDrain = false;
  3994. stream.emit('drain');
  3995. }
  3996. }
  3997. // if there's something in the buffer waiting, then process it
  3998. function clearBuffer(stream, state) {
  3999. state.bufferProcessing = true;
  4000. var entry = state.bufferedRequest;
  4001. if (stream._writev && entry && entry.next) {
  4002. // Fast case, write everything using _writev()
  4003. var l = state.bufferedRequestCount;
  4004. var buffer = new Array(l);
  4005. var holder = state.corkedRequestsFree;
  4006. holder.entry = entry;
  4007. var count = 0;
  4008. while (entry) {
  4009. buffer[count] = entry;
  4010. entry = entry.next;
  4011. count += 1;
  4012. }
  4013. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  4014. // doWrite is almost always async, defer these to save a bit of time
  4015. // as the hot path ends with doWrite
  4016. state.pendingcb++;
  4017. state.lastBufferedRequest = null;
  4018. if (holder.next) {
  4019. state.corkedRequestsFree = holder.next;
  4020. holder.next = null;
  4021. } else {
  4022. state.corkedRequestsFree = new CorkedRequest(state);
  4023. }
  4024. } else {
  4025. // Slow case, write chunks one-by-one
  4026. while (entry) {
  4027. var chunk = entry.chunk;
  4028. var encoding = entry.encoding;
  4029. var cb = entry.callback;
  4030. var len = state.objectMode ? 1 : chunk.length;
  4031. doWrite(stream, state, false, len, chunk, encoding, cb);
  4032. entry = entry.next;
  4033. // if we didn't call the onwrite immediately, then
  4034. // it means that we need to wait until it does.
  4035. // also, that means that the chunk and cb are currently
  4036. // being processed, so move the buffer counter past them.
  4037. if (state.writing) {
  4038. break;
  4039. }
  4040. }
  4041. if (entry === null) state.lastBufferedRequest = null;
  4042. }
  4043. state.bufferedRequestCount = 0;
  4044. state.bufferedRequest = entry;
  4045. state.bufferProcessing = false;
  4046. }
  4047. Writable.prototype._write = function (chunk, encoding, cb) {
  4048. cb(new Error('not implemented'));
  4049. };
  4050. Writable.prototype._writev = null;
  4051. Writable.prototype.end = function (chunk, encoding, cb) {
  4052. var state = this._writableState;
  4053. if (typeof chunk === 'function') {
  4054. cb = chunk;
  4055. chunk = null;
  4056. encoding = null;
  4057. } else if (typeof encoding === 'function') {
  4058. cb = encoding;
  4059. encoding = null;
  4060. }
  4061. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  4062. // .end() fully uncorks
  4063. if (state.corked) {
  4064. state.corked = 1;
  4065. this.uncork();
  4066. }
  4067. // ignore unnecessary end() calls.
  4068. if (!state.ending && !state.finished) endWritable(this, state, cb);
  4069. };
  4070. function needFinish(state) {
  4071. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  4072. }
  4073. function prefinish(stream, state) {
  4074. if (!state.prefinished) {
  4075. state.prefinished = true;
  4076. stream.emit('prefinish');
  4077. }
  4078. }
  4079. function finishMaybe(stream, state) {
  4080. var need = needFinish(state);
  4081. if (need) {
  4082. if (state.pendingcb === 0) {
  4083. prefinish(stream, state);
  4084. state.finished = true;
  4085. stream.emit('finish');
  4086. } else {
  4087. prefinish(stream, state);
  4088. }
  4089. }
  4090. return need;
  4091. }
  4092. function endWritable(stream, state, cb) {
  4093. state.ending = true;
  4094. finishMaybe(stream, state);
  4095. if (cb) {
  4096. if (state.finished) nextTick(cb);else stream.once('finish', cb);
  4097. }
  4098. state.ended = true;
  4099. stream.writable = false;
  4100. }
  4101. // It seems a linked list but it is not
  4102. // there will be only 2 of these for each stream
  4103. function CorkedRequest(state) {
  4104. var _this = this;
  4105. this.next = null;
  4106. this.entry = null;
  4107. this.finish = function (err) {
  4108. var entry = _this.entry;
  4109. _this.entry = null;
  4110. while (entry) {
  4111. var cb = entry.callback;
  4112. state.pendingcb--;
  4113. cb(err);
  4114. entry = entry.next;
  4115. }
  4116. if (state.corkedRequestsFree) {
  4117. state.corkedRequestsFree.next = _this;
  4118. } else {
  4119. state.corkedRequestsFree = _this;
  4120. }
  4121. };
  4122. }
  4123. inherits$1(Duplex, Readable);
  4124. var keys = Object.keys(Writable.prototype);
  4125. for (var v = 0; v < keys.length; v++) {
  4126. var method = keys[v];
  4127. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  4128. }
  4129. function Duplex(options) {
  4130. if (!(this instanceof Duplex)) return new Duplex(options);
  4131. Readable.call(this, options);
  4132. Writable.call(this, options);
  4133. if (options && options.readable === false) this.readable = false;
  4134. if (options && options.writable === false) this.writable = false;
  4135. this.allowHalfOpen = true;
  4136. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  4137. this.once('end', onend);
  4138. }
  4139. // the no-half-open enforcer
  4140. function onend() {
  4141. // if we allow half-open state, or if the writable side ended,
  4142. // then we're ok.
  4143. if (this.allowHalfOpen || this._writableState.ended) return;
  4144. // no more data can be written.
  4145. // But allow more writes to happen in this tick.
  4146. nextTick(onEndNT, this);
  4147. }
  4148. function onEndNT(self) {
  4149. self.end();
  4150. }
  4151. // a transform stream is a readable/writable stream where you do
  4152. // something with the data. Sometimes it's called a "filter",
  4153. // but that's not a great name for it, since that implies a thing where
  4154. // some bits pass through, and others are simply ignored. (That would
  4155. // be a valid example of a transform, of course.)
  4156. //
  4157. // While the output is causally related to the input, it's not a
  4158. // necessarily symmetric or synchronous transformation. For example,
  4159. // a zlib stream might take multiple plain-text writes(), and then
  4160. // emit a single compressed chunk some time in the future.
  4161. //
  4162. // Here's how this works:
  4163. //
  4164. // The Transform stream has all the aspects of the readable and writable
  4165. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  4166. // internally, and returns false if there's a lot of pending writes
  4167. // buffered up. When you call read(), that calls _read(n) until
  4168. // there's enough pending readable data buffered up.
  4169. //
  4170. // In a transform stream, the written data is placed in a buffer. When
  4171. // _read(n) is called, it transforms the queued up data, calling the
  4172. // buffered _write cb's as it consumes chunks. If consuming a single
  4173. // written chunk would result in multiple output chunks, then the first
  4174. // outputted bit calls the readcb, and subsequent chunks just go into
  4175. // the read buffer, and will cause it to emit 'readable' if necessary.
  4176. //
  4177. // This way, back-pressure is actually determined by the reading side,
  4178. // since _read has to be called to start processing a new chunk. However,
  4179. // a pathological inflate type of transform can cause excessive buffering
  4180. // here. For example, imagine a stream where every byte of input is
  4181. // interpreted as an integer from 0-255, and then results in that many
  4182. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  4183. // 1kb of data being output. In this case, you could write a very small
  4184. // amount of input, and end up with a very large amount of output. In
  4185. // such a pathological inflating mechanism, there'd be no way to tell
  4186. // the system to stop doing the transform. A single 4MB write could
  4187. // cause the system to run out of memory.
  4188. //
  4189. // However, even in such a pathological case, only a single written chunk
  4190. // would be consumed, and then the rest would wait (un-transformed) until
  4191. // the results of the previous transformed chunk were consumed.
  4192. inherits$1(Transform, Duplex);
  4193. function TransformState(stream) {
  4194. this.afterTransform = function (er, data) {
  4195. return afterTransform(stream, er, data);
  4196. };
  4197. this.needTransform = false;
  4198. this.transforming = false;
  4199. this.writecb = null;
  4200. this.writechunk = null;
  4201. this.writeencoding = null;
  4202. }
  4203. function afterTransform(stream, er, data) {
  4204. var ts = stream._transformState;
  4205. ts.transforming = false;
  4206. var cb = ts.writecb;
  4207. if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
  4208. ts.writechunk = null;
  4209. ts.writecb = null;
  4210. if (data !== null && data !== undefined) stream.push(data);
  4211. cb(er);
  4212. var rs = stream._readableState;
  4213. rs.reading = false;
  4214. if (rs.needReadable || rs.length < rs.highWaterMark) {
  4215. stream._read(rs.highWaterMark);
  4216. }
  4217. }
  4218. function Transform(options) {
  4219. if (!(this instanceof Transform)) return new Transform(options);
  4220. Duplex.call(this, options);
  4221. this._transformState = new TransformState(this);
  4222. // when the writable side finishes, then flush out anything remaining.
  4223. var stream = this;
  4224. // start out asking for a readable event once data is transformed.
  4225. this._readableState.needReadable = true;
  4226. // we have implemented the _read method, and done the other things
  4227. // that Readable wants before the first _read call, so unset the
  4228. // sync guard flag.
  4229. this._readableState.sync = false;
  4230. if (options) {
  4231. if (typeof options.transform === 'function') this._transform = options.transform;
  4232. if (typeof options.flush === 'function') this._flush = options.flush;
  4233. }
  4234. this.once('prefinish', function () {
  4235. if (typeof this._flush === 'function') this._flush(function (er) {
  4236. done(stream, er);
  4237. });else done(stream);
  4238. });
  4239. }
  4240. Transform.prototype.push = function (chunk, encoding) {
  4241. this._transformState.needTransform = false;
  4242. return Duplex.prototype.push.call(this, chunk, encoding);
  4243. };
  4244. // This is the part where you do stuff!
  4245. // override this function in implementation classes.
  4246. // 'chunk' is an input chunk.
  4247. //
  4248. // Call `push(newChunk)` to pass along transformed output
  4249. // to the readable side. You may call 'push' zero or more times.
  4250. //
  4251. // Call `cb(err)` when you are done with this chunk. If you pass
  4252. // an error, then that'll put the hurt on the whole operation. If you
  4253. // never call cb(), then you'll never get another chunk.
  4254. Transform.prototype._transform = function (chunk, encoding, cb) {
  4255. throw new Error('Not implemented');
  4256. };
  4257. Transform.prototype._write = function (chunk, encoding, cb) {
  4258. var ts = this._transformState;
  4259. ts.writecb = cb;
  4260. ts.writechunk = chunk;
  4261. ts.writeencoding = encoding;
  4262. if (!ts.transforming) {
  4263. var rs = this._readableState;
  4264. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  4265. }
  4266. };
  4267. // Doesn't matter what the args are here.
  4268. // _transform does all the work.
  4269. // That we got here means that the readable side wants more data.
  4270. Transform.prototype._read = function (n) {
  4271. var ts = this._transformState;
  4272. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  4273. ts.transforming = true;
  4274. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  4275. } else {
  4276. // mark that we need a transform, so that any data that comes in
  4277. // will get processed, now that we've asked for it.
  4278. ts.needTransform = true;
  4279. }
  4280. };
  4281. function done(stream, er) {
  4282. if (er) return stream.emit('error', er);
  4283. // if there's nothing in the write buffer, then that means
  4284. // that nothing more will ever be provided
  4285. var ws = stream._writableState;
  4286. var ts = stream._transformState;
  4287. if (ws.length) throw new Error('Calling transform done when ws.length != 0');
  4288. if (ts.transforming) throw new Error('Calling transform done when still transforming');
  4289. return stream.push(null);
  4290. }
  4291. inherits$1(PassThrough, Transform);
  4292. function PassThrough(options) {
  4293. if (!(this instanceof PassThrough)) return new PassThrough(options);
  4294. Transform.call(this, options);
  4295. }
  4296. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  4297. cb(null, chunk);
  4298. };
  4299. inherits$1(Stream, EventEmitter);
  4300. Stream.Readable = Readable;
  4301. Stream.Writable = Writable;
  4302. Stream.Duplex = Duplex;
  4303. Stream.Transform = Transform;
  4304. Stream.PassThrough = PassThrough;
  4305. // Backwards-compat with node 0.4.x
  4306. Stream.Stream = Stream;
  4307. // old-style streams. Note that the pipe method (the only relevant
  4308. // part of this class) is overridden in the Readable class.
  4309. function Stream() {
  4310. EventEmitter.call(this);
  4311. }
  4312. Stream.prototype.pipe = function(dest, options) {
  4313. var source = this;
  4314. function ondata(chunk) {
  4315. if (dest.writable) {
  4316. if (false === dest.write(chunk) && source.pause) {
  4317. source.pause();
  4318. }
  4319. }
  4320. }
  4321. source.on('data', ondata);
  4322. function ondrain() {
  4323. if (source.readable && source.resume) {
  4324. source.resume();
  4325. }
  4326. }
  4327. dest.on('drain', ondrain);
  4328. // If the 'end' option is not supplied, dest.end() will be called when
  4329. // source gets the 'end' or 'close' events. Only dest.end() once.
  4330. if (!dest._isStdio && (!options || options.end !== false)) {
  4331. source.on('end', onend);
  4332. source.on('close', onclose);
  4333. }
  4334. var didOnEnd = false;
  4335. function onend() {
  4336. if (didOnEnd) return;
  4337. didOnEnd = true;
  4338. dest.end();
  4339. }
  4340. function onclose() {
  4341. if (didOnEnd) return;
  4342. didOnEnd = true;
  4343. if (typeof dest.destroy === 'function') dest.destroy();
  4344. }
  4345. // don't leave dangling pipes when there are errors.
  4346. function onerror(er) {
  4347. cleanup();
  4348. if (EventEmitter.listenerCount(this, 'error') === 0) {
  4349. throw er; // Unhandled stream error in pipe.
  4350. }
  4351. }
  4352. source.on('error', onerror);
  4353. dest.on('error', onerror);
  4354. // remove all the event listeners that were added.
  4355. function cleanup() {
  4356. source.removeListener('data', ondata);
  4357. dest.removeListener('drain', ondrain);
  4358. source.removeListener('end', onend);
  4359. source.removeListener('close', onclose);
  4360. source.removeListener('error', onerror);
  4361. dest.removeListener('error', onerror);
  4362. source.removeListener('end', cleanup);
  4363. source.removeListener('close', cleanup);
  4364. dest.removeListener('close', cleanup);
  4365. }
  4366. source.on('end', cleanup);
  4367. source.on('close', cleanup);
  4368. dest.on('close', cleanup);
  4369. dest.emit('pipe', source);
  4370. // Allow for unix-like usage: A.pipe(B).pipe(C)
  4371. return dest;
  4372. };
  4373. const is_object = function(obj){
  4374. return (typeof obj === 'object' && obj !== null && !Array.isArray(obj));
  4375. };
  4376. class CsvError extends Error {
  4377. constructor(code, message, options, ...contexts) {
  4378. if(Array.isArray(message)) message = message.join(' ').trim();
  4379. super(message);
  4380. if(Error.captureStackTrace !== undefined){
  4381. Error.captureStackTrace(this, CsvError);
  4382. }
  4383. this.code = code;
  4384. for(const context of contexts){
  4385. for(const key in context){
  4386. const value = context[key];
  4387. this[key] = isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value));
  4388. }
  4389. }
  4390. }
  4391. }
  4392. const normalize_columns_array = function(columns){
  4393. const normalizedColumns = [];
  4394. for(let i = 0, l = columns.length; i < l; i++){
  4395. const column = columns[i];
  4396. if(column === undefined || column === null || column === false){
  4397. normalizedColumns[i] = { disabled: true };
  4398. }else if(typeof column === 'string'){
  4399. normalizedColumns[i] = { name: column };
  4400. }else if(is_object(column)){
  4401. if(typeof column.name !== 'string'){
  4402. throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [
  4403. 'Option columns missing name:',
  4404. `property "name" is required at position ${i}`,
  4405. 'when column is an object literal'
  4406. ]);
  4407. }
  4408. normalizedColumns[i] = column;
  4409. }else {
  4410. throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [
  4411. 'Invalid column definition:',
  4412. 'expect a string or a literal object,',
  4413. `got ${JSON.stringify(column)} at position ${i}`
  4414. ]);
  4415. }
  4416. }
  4417. return normalizedColumns;
  4418. };
  4419. class ResizeableBuffer{
  4420. constructor(size=100){
  4421. this.size = size;
  4422. this.length = 0;
  4423. this.buf = Buffer.allocUnsafe(size);
  4424. }
  4425. prepend(val){
  4426. if(isBuffer(val)){
  4427. const length = this.length + val.length;
  4428. if(length >= this.size){
  4429. this.resize();
  4430. if(length >= this.size){
  4431. throw Error('INVALID_BUFFER_STATE');
  4432. }
  4433. }
  4434. const buf = this.buf;
  4435. this.buf = Buffer.allocUnsafe(this.size);
  4436. val.copy(this.buf, 0);
  4437. buf.copy(this.buf, val.length);
  4438. this.length += val.length;
  4439. }else {
  4440. const length = this.length++;
  4441. if(length === this.size){
  4442. this.resize();
  4443. }
  4444. const buf = this.clone();
  4445. this.buf[0] = val;
  4446. buf.copy(this.buf,1, 0, length);
  4447. }
  4448. }
  4449. append(val){
  4450. const length = this.length++;
  4451. if(length === this.size){
  4452. this.resize();
  4453. }
  4454. this.buf[length] = val;
  4455. }
  4456. clone(){
  4457. return Buffer.from(this.buf.slice(0, this.length));
  4458. }
  4459. resize(){
  4460. const length = this.length;
  4461. this.size = this.size * 2;
  4462. const buf = Buffer.allocUnsafe(this.size);
  4463. this.buf.copy(buf,0, 0, length);
  4464. this.buf = buf;
  4465. }
  4466. toString(encoding){
  4467. if(encoding){
  4468. return this.buf.slice(0, this.length).toString(encoding);
  4469. }else {
  4470. return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length));
  4471. }
  4472. }
  4473. toJSON(){
  4474. return this.toString('utf8');
  4475. }
  4476. reset(){
  4477. this.length = 0;
  4478. }
  4479. }
  4480. // white space characters
  4481. // https://en.wikipedia.org/wiki/Whitespace_character
  4482. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types
  4483. // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff
  4484. const np = 12;
  4485. const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal
  4486. const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal
  4487. const space = 32;
  4488. const tab = 9;
  4489. const init_state = function(options){
  4490. return {
  4491. bomSkipped: false,
  4492. bufBytesStart: 0,
  4493. castField: options.cast_function,
  4494. commenting: false,
  4495. // Current error encountered by a record
  4496. error: undefined,
  4497. enabled: options.from_line === 1,
  4498. escaping: false,
  4499. escapeIsQuote: isBuffer(options.escape) && isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0,
  4500. // columns can be `false`, `true`, `Array`
  4501. expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined,
  4502. field: new ResizeableBuffer(20),
  4503. firstLineToHeaders: options.cast_first_line_to_header,
  4504. needMoreDataSize: Math.max(
  4505. // Skip if the remaining buffer smaller than comment
  4506. options.comment !== null ? options.comment.length : 0,
  4507. // Skip if the remaining buffer can be delimiter
  4508. ...options.delimiter.map((delimiter) => delimiter.length),
  4509. // Skip if the remaining buffer can be escape sequence
  4510. options.quote !== null ? options.quote.length : 0,
  4511. ),
  4512. previousBuf: undefined,
  4513. quoting: false,
  4514. stop: false,
  4515. rawBuffer: new ResizeableBuffer(100),
  4516. record: [],
  4517. recordHasError: false,
  4518. record_length: 0,
  4519. recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)),
  4520. trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]],
  4521. wasQuoting: false,
  4522. wasRowDelimiter: false,
  4523. timchars: [
  4524. Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding),
  4525. Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding),
  4526. Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding),
  4527. Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding),
  4528. Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding),
  4529. ]
  4530. };
  4531. };
  4532. const underscore = function(str){
  4533. return str.replace(/([A-Z])/g, function(_, match){
  4534. return '_' + match.toLowerCase();
  4535. });
  4536. };
  4537. const normalize_options = function(opts){
  4538. const options = {};
  4539. // Merge with user options
  4540. for(const opt in opts){
  4541. options[underscore(opt)] = opts[opt];
  4542. }
  4543. // Normalize option `encoding`
  4544. // Note: defined first because other options depends on it
  4545. // to convert chars/strings into buffers.
  4546. if(options.encoding === undefined || options.encoding === true){
  4547. options.encoding = 'utf8';
  4548. }else if(options.encoding === null || options.encoding === false){
  4549. options.encoding = null;
  4550. }else if(typeof options.encoding !== 'string' && options.encoding !== null){
  4551. throw new CsvError('CSV_INVALID_OPTION_ENCODING', [
  4552. 'Invalid option encoding:',
  4553. 'encoding must be a string or null to return a buffer,',
  4554. `got ${JSON.stringify(options.encoding)}`
  4555. ], options);
  4556. }
  4557. // Normalize option `bom`
  4558. if(options.bom === undefined || options.bom === null || options.bom === false){
  4559. options.bom = false;
  4560. }else if(options.bom !== true){
  4561. throw new CsvError('CSV_INVALID_OPTION_BOM', [
  4562. 'Invalid option bom:', 'bom must be true,',
  4563. `got ${JSON.stringify(options.bom)}`
  4564. ], options);
  4565. }
  4566. // Normalize option `cast`
  4567. options.cast_function = null;
  4568. if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){
  4569. options.cast = undefined;
  4570. }else if(typeof options.cast === 'function'){
  4571. options.cast_function = options.cast;
  4572. options.cast = true;
  4573. }else if(options.cast !== true){
  4574. throw new CsvError('CSV_INVALID_OPTION_CAST', [
  4575. 'Invalid option cast:', 'cast must be true or a function,',
  4576. `got ${JSON.stringify(options.cast)}`
  4577. ], options);
  4578. }
  4579. // Normalize option `cast_date`
  4580. if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){
  4581. options.cast_date = false;
  4582. }else if(options.cast_date === true){
  4583. options.cast_date = function(value){
  4584. const date = Date.parse(value);
  4585. return !isNaN(date) ? new Date(date) : value;
  4586. };
  4587. }else if (typeof options.cast_date !== 'function'){
  4588. throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [
  4589. 'Invalid option cast_date:', 'cast_date must be true or a function,',
  4590. `got ${JSON.stringify(options.cast_date)}`
  4591. ], options);
  4592. }
  4593. // Normalize option `columns`
  4594. options.cast_first_line_to_header = null;
  4595. if(options.columns === true){
  4596. // Fields in the first line are converted as-is to columns
  4597. options.cast_first_line_to_header = undefined;
  4598. }else if(typeof options.columns === 'function'){
  4599. options.cast_first_line_to_header = options.columns;
  4600. options.columns = true;
  4601. }else if(Array.isArray(options.columns)){
  4602. options.columns = normalize_columns_array(options.columns);
  4603. }else if(options.columns === undefined || options.columns === null || options.columns === false){
  4604. options.columns = false;
  4605. }else {
  4606. throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [
  4607. 'Invalid option columns:',
  4608. 'expect an array, a function or true,',
  4609. `got ${JSON.stringify(options.columns)}`
  4610. ], options);
  4611. }
  4612. // Normalize option `group_columns_by_name`
  4613. if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){
  4614. options.group_columns_by_name = false;
  4615. }else if(options.group_columns_by_name !== true){
  4616. throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [
  4617. 'Invalid option group_columns_by_name:',
  4618. 'expect an boolean,',
  4619. `got ${JSON.stringify(options.group_columns_by_name)}`
  4620. ], options);
  4621. }else if(options.columns === false){
  4622. throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [
  4623. 'Invalid option group_columns_by_name:',
  4624. 'the `columns` mode must be activated.'
  4625. ], options);
  4626. }
  4627. // Normalize option `comment`
  4628. if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){
  4629. options.comment = null;
  4630. }else {
  4631. if(typeof options.comment === 'string'){
  4632. options.comment = Buffer.from(options.comment, options.encoding);
  4633. }
  4634. if(!isBuffer(options.comment)){
  4635. throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
  4636. 'Invalid option comment:',
  4637. 'comment must be a buffer or a string,',
  4638. `got ${JSON.stringify(options.comment)}`
  4639. ], options);
  4640. }
  4641. }
  4642. // Normalize option `comment_no_infix`
  4643. if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){
  4644. options.comment_no_infix = false;
  4645. }else if(options.comment_no_infix !== true){
  4646. throw new CsvError('CSV_INVALID_OPTION_COMMENT', [
  4647. 'Invalid option comment_no_infix:',
  4648. 'value must be a boolean,',
  4649. `got ${JSON.stringify(options.comment_no_infix)}`
  4650. ], options);
  4651. }
  4652. // Normalize option `delimiter`
  4653. const delimiter_json = JSON.stringify(options.delimiter);
  4654. if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter];
  4655. if(options.delimiter.length === 0){
  4656. throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [
  4657. 'Invalid option delimiter:',
  4658. 'delimiter must be a non empty string or buffer or array of string|buffer,',
  4659. `got ${delimiter_json}`
  4660. ], options);
  4661. }
  4662. options.delimiter = options.delimiter.map(function(delimiter){
  4663. if(delimiter === undefined || delimiter === null || delimiter === false){
  4664. return Buffer.from(',', options.encoding);
  4665. }
  4666. if(typeof delimiter === 'string'){
  4667. delimiter = Buffer.from(delimiter, options.encoding);
  4668. }
  4669. if(!isBuffer(delimiter) || delimiter.length === 0){
  4670. throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [
  4671. 'Invalid option delimiter:',
  4672. 'delimiter must be a non empty string or buffer or array of string|buffer,',
  4673. `got ${delimiter_json}`
  4674. ], options);
  4675. }
  4676. return delimiter;
  4677. });
  4678. // Normalize option `escape`
  4679. if(options.escape === undefined || options.escape === true){
  4680. options.escape = Buffer.from('"', options.encoding);
  4681. }else if(typeof options.escape === 'string'){
  4682. options.escape = Buffer.from(options.escape, options.encoding);
  4683. }else if (options.escape === null || options.escape === false){
  4684. options.escape = null;
  4685. }
  4686. if(options.escape !== null){
  4687. if(!isBuffer(options.escape)){
  4688. throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`);
  4689. }
  4690. }
  4691. // Normalize option `from`
  4692. if(options.from === undefined || options.from === null){
  4693. options.from = 1;
  4694. }else {
  4695. if(typeof options.from === 'string' && /\d+/.test(options.from)){
  4696. options.from = parseInt(options.from);
  4697. }
  4698. if(Number.isInteger(options.from)){
  4699. if(options.from < 0){
  4700. throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`);
  4701. }
  4702. }else {
  4703. throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`);
  4704. }
  4705. }
  4706. // Normalize option `from_line`
  4707. if(options.from_line === undefined || options.from_line === null){
  4708. options.from_line = 1;
  4709. }else {
  4710. if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){
  4711. options.from_line = parseInt(options.from_line);
  4712. }
  4713. if(Number.isInteger(options.from_line)){
  4714. if(options.from_line <= 0){
  4715. throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`);
  4716. }
  4717. }else {
  4718. throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`);
  4719. }
  4720. }
  4721. // Normalize options `ignore_last_delimiters`
  4722. if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){
  4723. options.ignore_last_delimiters = false;
  4724. }else if(typeof options.ignore_last_delimiters === 'number'){
  4725. options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters);
  4726. if(options.ignore_last_delimiters === 0){
  4727. options.ignore_last_delimiters = false;
  4728. }
  4729. }else if(typeof options.ignore_last_delimiters !== 'boolean'){
  4730. throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [
  4731. 'Invalid option `ignore_last_delimiters`:',
  4732. 'the value must be a boolean value or an integer,',
  4733. `got ${JSON.stringify(options.ignore_last_delimiters)}`
  4734. ], options);
  4735. }
  4736. if(options.ignore_last_delimiters === true && options.columns === false){
  4737. throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [
  4738. 'The option `ignore_last_delimiters`',
  4739. 'requires the activation of the `columns` option'
  4740. ], options);
  4741. }
  4742. // Normalize option `info`
  4743. if(options.info === undefined || options.info === null || options.info === false){
  4744. options.info = false;
  4745. }else if(options.info !== true){
  4746. throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`);
  4747. }
  4748. // Normalize option `max_record_size`
  4749. if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){
  4750. options.max_record_size = 0;
  4751. }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){
  4752. options.max_record_size = parseInt(options.max_record_size);
  4753. }else {
  4754. throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`);
  4755. }
  4756. // Normalize option `objname`
  4757. if(options.objname === undefined || options.objname === null || options.objname === false){
  4758. options.objname = undefined;
  4759. }else if(isBuffer(options.objname)){
  4760. if(options.objname.length === 0){
  4761. throw new Error(`Invalid Option: objname must be a non empty buffer`);
  4762. }
  4763. if(options.encoding === null);else {
  4764. options.objname = options.objname.toString(options.encoding);
  4765. }
  4766. }else if(typeof options.objname === 'string'){
  4767. if(options.objname.length === 0){
  4768. throw new Error(`Invalid Option: objname must be a non empty string`);
  4769. }
  4770. // Great, nothing to do
  4771. }else if(typeof options.objname === 'number');else {
  4772. throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`);
  4773. }
  4774. if(options.objname !== undefined){
  4775. if(typeof options.objname === 'number'){
  4776. if(options.columns !== false){
  4777. throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field');
  4778. }
  4779. }else { // A string or a buffer
  4780. if(options.columns === false){
  4781. throw Error('Invalid Option: objname field must be combined with columns or be defined as an index');
  4782. }
  4783. }
  4784. }
  4785. // Normalize option `on_record`
  4786. if(options.on_record === undefined || options.on_record === null){
  4787. options.on_record = undefined;
  4788. }else if(typeof options.on_record !== 'function'){
  4789. throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [
  4790. 'Invalid option `on_record`:',
  4791. 'expect a function,',
  4792. `got ${JSON.stringify(options.on_record)}`
  4793. ], options);
  4794. }
  4795. // Normalize option `quote`
  4796. if(options.quote === null || options.quote === false || options.quote === ''){
  4797. options.quote = null;
  4798. }else {
  4799. if(options.quote === undefined || options.quote === true){
  4800. options.quote = Buffer.from('"', options.encoding);
  4801. }else if(typeof options.quote === 'string'){
  4802. options.quote = Buffer.from(options.quote, options.encoding);
  4803. }
  4804. if(!isBuffer(options.quote)){
  4805. throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`);
  4806. }
  4807. }
  4808. // Normalize option `raw`
  4809. if(options.raw === undefined || options.raw === null || options.raw === false){
  4810. options.raw = false;
  4811. }else if(options.raw !== true){
  4812. throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`);
  4813. }
  4814. // Normalize option `record_delimiter`
  4815. if(options.record_delimiter === undefined){
  4816. options.record_delimiter = [];
  4817. }else if(typeof options.record_delimiter === 'string' || isBuffer(options.record_delimiter)){
  4818. if(options.record_delimiter.length === 0){
  4819. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  4820. 'Invalid option `record_delimiter`:',
  4821. 'value must be a non empty string or buffer,',
  4822. `got ${JSON.stringify(options.record_delimiter)}`
  4823. ], options);
  4824. }
  4825. options.record_delimiter = [options.record_delimiter];
  4826. }else if(!Array.isArray(options.record_delimiter)){
  4827. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  4828. 'Invalid option `record_delimiter`:',
  4829. 'value must be a string, a buffer or array of string|buffer,',
  4830. `got ${JSON.stringify(options.record_delimiter)}`
  4831. ], options);
  4832. }
  4833. options.record_delimiter = options.record_delimiter.map(function(rd, i){
  4834. if(typeof rd !== 'string' && ! isBuffer(rd)){
  4835. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  4836. 'Invalid option `record_delimiter`:',
  4837. 'value must be a string, a buffer or array of string|buffer',
  4838. `at index ${i},`,
  4839. `got ${JSON.stringify(rd)}`
  4840. ], options);
  4841. }else if(rd.length === 0){
  4842. throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [
  4843. 'Invalid option `record_delimiter`:',
  4844. 'value must be a non empty string or buffer',
  4845. `at index ${i},`,
  4846. `got ${JSON.stringify(rd)}`
  4847. ], options);
  4848. }
  4849. if(typeof rd === 'string'){
  4850. rd = Buffer.from(rd, options.encoding);
  4851. }
  4852. return rd;
  4853. });
  4854. // Normalize option `relax_column_count`
  4855. if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){
  4856. options.relax_column_count = false;
  4857. }else {
  4858. throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`);
  4859. }
  4860. if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){
  4861. options.relax_column_count_less = false;
  4862. }else {
  4863. throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`);
  4864. }
  4865. if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){
  4866. options.relax_column_count_more = false;
  4867. }else {
  4868. throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`);
  4869. }
  4870. // Normalize option `relax_quotes`
  4871. if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){
  4872. options.relax_quotes = false;
  4873. }else {
  4874. throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`);
  4875. }
  4876. // Normalize option `skip_empty_lines`
  4877. if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){
  4878. options.skip_empty_lines = false;
  4879. }else {
  4880. throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`);
  4881. }
  4882. // Normalize option `skip_records_with_empty_values`
  4883. if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){
  4884. options.skip_records_with_empty_values = false;
  4885. }else {
  4886. throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`);
  4887. }
  4888. // Normalize option `skip_records_with_error`
  4889. if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){
  4890. options.skip_records_with_error = false;
  4891. }else {
  4892. throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`);
  4893. }
  4894. // Normalize option `rtrim`
  4895. if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){
  4896. options.rtrim = false;
  4897. }else if(options.rtrim !== true){
  4898. throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`);
  4899. }
  4900. // Normalize option `ltrim`
  4901. if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){
  4902. options.ltrim = false;
  4903. }else if(options.ltrim !== true){
  4904. throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`);
  4905. }
  4906. // Normalize option `trim`
  4907. if(options.trim === undefined || options.trim === null || options.trim === false){
  4908. options.trim = false;
  4909. }else if(options.trim !== true){
  4910. throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`);
  4911. }
  4912. // Normalize options `trim`, `ltrim` and `rtrim`
  4913. if(options.trim === true && opts.ltrim !== false){
  4914. options.ltrim = true;
  4915. }else if(options.ltrim !== true){
  4916. options.ltrim = false;
  4917. }
  4918. if(options.trim === true && opts.rtrim !== false){
  4919. options.rtrim = true;
  4920. }else if(options.rtrim !== true){
  4921. options.rtrim = false;
  4922. }
  4923. // Normalize option `to`
  4924. if(options.to === undefined || options.to === null){
  4925. options.to = -1;
  4926. }else {
  4927. if(typeof options.to === 'string' && /\d+/.test(options.to)){
  4928. options.to = parseInt(options.to);
  4929. }
  4930. if(Number.isInteger(options.to)){
  4931. if(options.to <= 0){
  4932. throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`);
  4933. }
  4934. }else {
  4935. throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`);
  4936. }
  4937. }
  4938. // Normalize option `to_line`
  4939. if(options.to_line === undefined || options.to_line === null){
  4940. options.to_line = -1;
  4941. }else {
  4942. if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){
  4943. options.to_line = parseInt(options.to_line);
  4944. }
  4945. if(Number.isInteger(options.to_line)){
  4946. if(options.to_line <= 0){
  4947. throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`);
  4948. }
  4949. }else {
  4950. throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`);
  4951. }
  4952. }
  4953. return options;
  4954. };
  4955. const isRecordEmpty = function(record){
  4956. return record.every((field) => field == null || field.toString && field.toString().trim() === '');
  4957. };
  4958. const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal
  4959. const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal
  4960. const boms = {
  4961. // Note, the following are equals:
  4962. // Buffer.from("\ufeff")
  4963. // Buffer.from([239, 187, 191])
  4964. // Buffer.from('EFBBBF', 'hex')
  4965. 'utf8': Buffer.from([239, 187, 191]),
  4966. // Note, the following are equals:
  4967. // Buffer.from "\ufeff", 'utf16le
  4968. // Buffer.from([255, 254])
  4969. 'utf16le': Buffer.from([255, 254])
  4970. };
  4971. const transform = function(original_options = {}) {
  4972. const info = {
  4973. bytes: 0,
  4974. comment_lines: 0,
  4975. empty_lines: 0,
  4976. invalid_field_length: 0,
  4977. lines: 1,
  4978. records: 0
  4979. };
  4980. const options = normalize_options(original_options);
  4981. return {
  4982. info: info,
  4983. original_options: original_options,
  4984. options: options,
  4985. state: init_state(options),
  4986. __needMoreData: function(i, bufLen, end){
  4987. if(end) return false;
  4988. const {encoding, escape, quote} = this.options;
  4989. const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state;
  4990. const numOfCharLeft = bufLen - i - 1;
  4991. const requiredLength = Math.max(
  4992. needMoreDataSize,
  4993. // Skip if the remaining buffer smaller than record delimiter
  4994. // If "record_delimiter" is yet to be discovered:
  4995. // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0`
  4996. // 2. We set the length to windows line ending in the current encoding
  4997. // Note, that encoding is known from user or bom discovery at that point
  4998. // recordDelimiterMaxLength,
  4999. recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength,
  5000. // Skip if remaining buffer can be an escaped quote
  5001. quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0,
  5002. // Skip if remaining buffer can be record delimiter following the closing quote
  5003. quoting ? (quote.length + recordDelimiterMaxLength) : 0,
  5004. );
  5005. return numOfCharLeft < requiredLength;
  5006. },
  5007. // Central parser implementation
  5008. parse: function(nextBuf, end, push, close){
  5009. const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options;
  5010. let {comment, escape, quote, record_delimiter} = this.options;
  5011. const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state;
  5012. let buf;
  5013. if(previousBuf === undefined){
  5014. if(nextBuf === undefined){
  5015. // Handle empty string
  5016. close();
  5017. return;
  5018. }else {
  5019. buf = nextBuf;
  5020. }
  5021. }else if(previousBuf !== undefined && nextBuf === undefined){
  5022. buf = previousBuf;
  5023. }else {
  5024. buf = Buffer.concat([previousBuf, nextBuf]);
  5025. }
  5026. // Handle UTF BOM
  5027. if(bomSkipped === false){
  5028. if(bom === false){
  5029. this.state.bomSkipped = true;
  5030. }else if(buf.length < 3){
  5031. // No enough data
  5032. if(end === false){
  5033. // Wait for more data
  5034. this.state.previousBuf = buf;
  5035. return;
  5036. }
  5037. }else {
  5038. for(const encoding in boms){
  5039. if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){
  5040. // Skip BOM
  5041. const bomLength = boms[encoding].length;
  5042. this.state.bufBytesStart += bomLength;
  5043. buf = buf.slice(bomLength);
  5044. // Renormalize original options with the new encoding
  5045. this.options = normalize_options({...this.original_options, encoding: encoding});
  5046. // Options will re-evaluate the Buffer with the new encoding
  5047. ({comment, escape, quote } = this.options);
  5048. break;
  5049. }
  5050. }
  5051. this.state.bomSkipped = true;
  5052. }
  5053. }
  5054. const bufLen = buf.length;
  5055. let pos;
  5056. for(pos = 0; pos < bufLen; pos++){
  5057. // Ensure we get enough space to look ahead
  5058. // There should be a way to move this out of the loop
  5059. if(this.__needMoreData(pos, bufLen, end)){
  5060. break;
  5061. }
  5062. if(this.state.wasRowDelimiter === true){
  5063. this.info.lines++;
  5064. this.state.wasRowDelimiter = false;
  5065. }
  5066. if(to_line !== -1 && this.info.lines > to_line){
  5067. this.state.stop = true;
  5068. close();
  5069. return;
  5070. }
  5071. // Auto discovery of record_delimiter, unix, mac and windows supported
  5072. if(this.state.quoting === false && record_delimiter.length === 0){
  5073. const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos);
  5074. if(record_delimiterCount){
  5075. record_delimiter = this.options.record_delimiter;
  5076. }
  5077. }
  5078. const chr = buf[pos];
  5079. if(raw === true){
  5080. rawBuffer.append(chr);
  5081. }
  5082. if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){
  5083. this.state.wasRowDelimiter = true;
  5084. }
  5085. // Previous char was a valid escape char
  5086. // treat the current char as a regular char
  5087. if(this.state.escaping === true){
  5088. this.state.escaping = false;
  5089. }else {
  5090. // Escape is only active inside quoted fields
  5091. // We are quoting, the char is an escape chr and there is a chr to escape
  5092. // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){
  5093. if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){
  5094. if(escapeIsQuote){
  5095. if(this.__isQuote(buf, pos+escape.length)){
  5096. this.state.escaping = true;
  5097. pos += escape.length - 1;
  5098. continue;
  5099. }
  5100. }else {
  5101. this.state.escaping = true;
  5102. pos += escape.length - 1;
  5103. continue;
  5104. }
  5105. }
  5106. // Not currently escaping and chr is a quote
  5107. // TODO: need to compare bytes instead of single char
  5108. if(this.state.commenting === false && this.__isQuote(buf, pos)){
  5109. if(this.state.quoting === true){
  5110. const nextChr = buf[pos+quote.length];
  5111. const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length);
  5112. const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr);
  5113. const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr);
  5114. const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length);
  5115. // Escape a quote
  5116. // Treat next char as a regular character
  5117. if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){
  5118. pos += escape.length - 1;
  5119. }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){
  5120. this.state.quoting = false;
  5121. this.state.wasQuoting = true;
  5122. pos += quote.length - 1;
  5123. continue;
  5124. }else if(relax_quotes === false){
  5125. const err = this.__error(
  5126. new CsvError('CSV_INVALID_CLOSING_QUOTE', [
  5127. 'Invalid Closing Quote:',
  5128. `got "${String.fromCharCode(nextChr)}"`,
  5129. `at line ${this.info.lines}`,
  5130. 'instead of delimiter, record delimiter, trimable character',
  5131. '(if activated) or comment',
  5132. ], this.options, this.__infoField())
  5133. );
  5134. if(err !== undefined) return err;
  5135. }else {
  5136. this.state.quoting = false;
  5137. this.state.wasQuoting = true;
  5138. this.state.field.prepend(quote);
  5139. pos += quote.length - 1;
  5140. }
  5141. }else {
  5142. if(this.state.field.length !== 0){
  5143. // In relax_quotes mode, treat opening quote preceded by chrs as regular
  5144. if(relax_quotes === false){
  5145. const info = this.__infoField();
  5146. const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0];
  5147. const err = this.__error(
  5148. new CsvError('INVALID_OPENING_QUOTE', [
  5149. 'Invalid Opening Quote:',
  5150. `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`,
  5151. bom ? `(${bom} bom)` : undefined
  5152. ], this.options, info, {
  5153. field: this.state.field,
  5154. })
  5155. );
  5156. if(err !== undefined) return err;
  5157. }
  5158. }else {
  5159. this.state.quoting = true;
  5160. pos += quote.length - 1;
  5161. continue;
  5162. }
  5163. }
  5164. }
  5165. if(this.state.quoting === false){
  5166. const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos);
  5167. if(recordDelimiterLength !== 0){
  5168. // Do not emit comments which take a full line
  5169. const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0);
  5170. if(skipCommentLine){
  5171. this.info.comment_lines++;
  5172. // Skip full comment line
  5173. }else {
  5174. // Activate records emition if above from_line
  5175. if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){
  5176. this.state.enabled = true;
  5177. this.__resetField();
  5178. this.__resetRecord();
  5179. pos += recordDelimiterLength - 1;
  5180. continue;
  5181. }
  5182. // Skip if line is empty and skip_empty_lines activated
  5183. if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){
  5184. this.info.empty_lines++;
  5185. pos += recordDelimiterLength - 1;
  5186. continue;
  5187. }
  5188. this.info.bytes = this.state.bufBytesStart + pos;
  5189. const errField = this.__onField();
  5190. if(errField !== undefined) return errField;
  5191. this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength;
  5192. const errRecord = this.__onRecord(push);
  5193. if(errRecord !== undefined) return errRecord;
  5194. if(to !== -1 && this.info.records >= to){
  5195. this.state.stop = true;
  5196. close();
  5197. return;
  5198. }
  5199. }
  5200. this.state.commenting = false;
  5201. pos += recordDelimiterLength - 1;
  5202. continue;
  5203. }
  5204. if(this.state.commenting){
  5205. continue;
  5206. }
  5207. const commentCount = comment === null ? 0 : this.__compareBytes(comment, buf, pos, chr);
  5208. if(commentCount !== 0 && (comment_no_infix === false || this.state.field.length === 0)){
  5209. this.state.commenting = true;
  5210. continue;
  5211. }
  5212. const delimiterLength = this.__isDelimiter(buf, pos, chr);
  5213. if(delimiterLength !== 0){
  5214. this.info.bytes = this.state.bufBytesStart + pos;
  5215. const errField = this.__onField();
  5216. if(errField !== undefined) return errField;
  5217. pos += delimiterLength - 1;
  5218. continue;
  5219. }
  5220. }
  5221. }
  5222. if(this.state.commenting === false){
  5223. if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){
  5224. return this.__error(
  5225. new CsvError('CSV_MAX_RECORD_SIZE', [
  5226. 'Max Record Size:',
  5227. 'record exceed the maximum number of tolerated bytes',
  5228. `of ${max_record_size}`,
  5229. `at line ${this.info.lines}`,
  5230. ], this.options, this.__infoField())
  5231. );
  5232. }
  5233. }
  5234. const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos);
  5235. // rtrim in non quoting is handle in __onField
  5236. const rappend = rtrim === false || this.state.wasQuoting === false;
  5237. if(lappend === true && rappend === true){
  5238. this.state.field.append(chr);
  5239. }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){
  5240. return this.__error(
  5241. new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [
  5242. 'Invalid Closing Quote:',
  5243. 'found non trimable byte after quote',
  5244. `at line ${this.info.lines}`,
  5245. ], this.options, this.__infoField())
  5246. );
  5247. }else {
  5248. if(lappend === false){
  5249. pos += this.__isCharTrimable(buf, pos) - 1;
  5250. }
  5251. continue;
  5252. }
  5253. }
  5254. if(end === true){
  5255. // Ensure we are not ending in a quoting state
  5256. if(this.state.quoting === true){
  5257. const err = this.__error(
  5258. new CsvError('CSV_QUOTE_NOT_CLOSED', [
  5259. 'Quote Not Closed:',
  5260. `the parsing is finished with an opening quote at line ${this.info.lines}`,
  5261. ], this.options, this.__infoField())
  5262. );
  5263. if(err !== undefined) return err;
  5264. }else {
  5265. // Skip last line if it has no characters
  5266. if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){
  5267. this.info.bytes = this.state.bufBytesStart + pos;
  5268. const errField = this.__onField();
  5269. if(errField !== undefined) return errField;
  5270. const errRecord = this.__onRecord(push);
  5271. if(errRecord !== undefined) return errRecord;
  5272. }else if(this.state.wasRowDelimiter === true){
  5273. this.info.empty_lines++;
  5274. }else if(this.state.commenting === true){
  5275. this.info.comment_lines++;
  5276. }
  5277. }
  5278. }else {
  5279. this.state.bufBytesStart += pos;
  5280. this.state.previousBuf = buf.slice(pos);
  5281. }
  5282. if(this.state.wasRowDelimiter === true){
  5283. this.info.lines++;
  5284. this.state.wasRowDelimiter = false;
  5285. }
  5286. },
  5287. __onRecord: function(push){
  5288. const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options;
  5289. const {enabled, record} = this.state;
  5290. if(enabled === false){
  5291. return this.__resetRecord();
  5292. }
  5293. // Convert the first line into column names
  5294. const recordLength = record.length;
  5295. if(columns === true){
  5296. if(skip_records_with_empty_values === true && isRecordEmpty(record)){
  5297. this.__resetRecord();
  5298. return;
  5299. }
  5300. return this.__firstLineToColumns(record);
  5301. }
  5302. if(columns === false && this.info.records === 0){
  5303. this.state.expectedRecordLength = recordLength;
  5304. }
  5305. if(recordLength !== this.state.expectedRecordLength){
  5306. const err = columns === false ?
  5307. new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [
  5308. 'Invalid Record Length:',
  5309. `expect ${this.state.expectedRecordLength},`,
  5310. `got ${recordLength} on line ${this.info.lines}`,
  5311. ], this.options, this.__infoField(), {
  5312. record: record,
  5313. })
  5314. :
  5315. new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [
  5316. 'Invalid Record Length:',
  5317. `columns length is ${columns.length},`, // rename columns
  5318. `got ${recordLength} on line ${this.info.lines}`,
  5319. ], this.options, this.__infoField(), {
  5320. record: record,
  5321. });
  5322. if(relax_column_count === true ||
  5323. (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) ||
  5324. (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){
  5325. this.info.invalid_field_length++;
  5326. this.state.error = err;
  5327. // Error is undefined with skip_records_with_error
  5328. }else {
  5329. const finalErr = this.__error(err);
  5330. if(finalErr) return finalErr;
  5331. }
  5332. }
  5333. if(skip_records_with_empty_values === true && isRecordEmpty(record)){
  5334. this.__resetRecord();
  5335. return;
  5336. }
  5337. if(this.state.recordHasError === true){
  5338. this.__resetRecord();
  5339. this.state.recordHasError = false;
  5340. return;
  5341. }
  5342. this.info.records++;
  5343. if(from === 1 || this.info.records >= from){
  5344. const {objname} = this.options;
  5345. // With columns, records are object
  5346. if(columns !== false){
  5347. const obj = {};
  5348. // Transform record array to an object
  5349. for(let i = 0, l = record.length; i < l; i++){
  5350. if(columns[i] === undefined || columns[i].disabled) continue;
  5351. // Turn duplicate columns into an array
  5352. if (group_columns_by_name === true && obj[columns[i].name] !== undefined) {
  5353. if (Array.isArray(obj[columns[i].name])) {
  5354. obj[columns[i].name] = obj[columns[i].name].concat(record[i]);
  5355. } else {
  5356. obj[columns[i].name] = [obj[columns[i].name], record[i]];
  5357. }
  5358. } else {
  5359. obj[columns[i].name] = record[i];
  5360. }
  5361. }
  5362. // Without objname (default)
  5363. if(raw === true || info === true){
  5364. const extRecord = Object.assign(
  5365. {record: obj},
  5366. (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}),
  5367. (info === true ? {info: this.__infoRecord()}: {})
  5368. );
  5369. const err = this.__push(
  5370. objname === undefined ? extRecord : [obj[objname], extRecord]
  5371. , push);
  5372. if(err){
  5373. return err;
  5374. }
  5375. }else {
  5376. const err = this.__push(
  5377. objname === undefined ? obj : [obj[objname], obj]
  5378. , push);
  5379. if(err){
  5380. return err;
  5381. }
  5382. }
  5383. // Without columns, records are array
  5384. }else {
  5385. if(raw === true || info === true){
  5386. const extRecord = Object.assign(
  5387. {record: record},
  5388. raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {},
  5389. info === true ? {info: this.__infoRecord()}: {}
  5390. );
  5391. const err = this.__push(
  5392. objname === undefined ? extRecord : [record[objname], extRecord]
  5393. , push);
  5394. if(err){
  5395. return err;
  5396. }
  5397. }else {
  5398. const err = this.__push(
  5399. objname === undefined ? record : [record[objname], record]
  5400. , push);
  5401. if(err){
  5402. return err;
  5403. }
  5404. }
  5405. }
  5406. }
  5407. this.__resetRecord();
  5408. },
  5409. __firstLineToColumns: function(record){
  5410. const {firstLineToHeaders} = this.state;
  5411. try{
  5412. const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record);
  5413. if(!Array.isArray(headers)){
  5414. return this.__error(
  5415. new CsvError('CSV_INVALID_COLUMN_MAPPING', [
  5416. 'Invalid Column Mapping:',
  5417. 'expect an array from column function,',
  5418. `got ${JSON.stringify(headers)}`
  5419. ], this.options, this.__infoField(), {
  5420. headers: headers,
  5421. })
  5422. );
  5423. }
  5424. const normalizedHeaders = normalize_columns_array(headers);
  5425. this.state.expectedRecordLength = normalizedHeaders.length;
  5426. this.options.columns = normalizedHeaders;
  5427. this.__resetRecord();
  5428. return;
  5429. }catch(err){
  5430. return err;
  5431. }
  5432. },
  5433. __resetRecord: function(){
  5434. if(this.options.raw === true){
  5435. this.state.rawBuffer.reset();
  5436. }
  5437. this.state.error = undefined;
  5438. this.state.record = [];
  5439. this.state.record_length = 0;
  5440. },
  5441. __onField: function(){
  5442. const {cast, encoding, rtrim, max_record_size} = this.options;
  5443. const {enabled, wasQuoting} = this.state;
  5444. // Short circuit for the from_line options
  5445. if(enabled === false){
  5446. return this.__resetField();
  5447. }
  5448. let field = this.state.field.toString(encoding);
  5449. if(rtrim === true && wasQuoting === false){
  5450. field = field.trimRight();
  5451. }
  5452. if(cast === true){
  5453. const [err, f] = this.__cast(field);
  5454. if(err !== undefined) return err;
  5455. field = f;
  5456. }
  5457. this.state.record.push(field);
  5458. // Increment record length if record size must not exceed a limit
  5459. if(max_record_size !== 0 && typeof field === 'string'){
  5460. this.state.record_length += field.length;
  5461. }
  5462. this.__resetField();
  5463. },
  5464. __resetField: function(){
  5465. this.state.field.reset();
  5466. this.state.wasQuoting = false;
  5467. },
  5468. __push: function(record, push){
  5469. const {on_record} = this.options;
  5470. if(on_record !== undefined){
  5471. const info = this.__infoRecord();
  5472. try{
  5473. record = on_record.call(null, record, info);
  5474. }catch(err){
  5475. return err;
  5476. }
  5477. if(record === undefined || record === null){ return; }
  5478. }
  5479. push(record);
  5480. },
  5481. // Return a tuple with the error and the casted value
  5482. __cast: function(field){
  5483. const {columns, relax_column_count} = this.options;
  5484. const isColumns = Array.isArray(columns);
  5485. // Dont loose time calling cast
  5486. // because the final record is an object
  5487. // and this field can't be associated to a key present in columns
  5488. if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){
  5489. return [undefined, undefined];
  5490. }
  5491. if(this.state.castField !== null){
  5492. try{
  5493. const info = this.__infoField();
  5494. return [undefined, this.state.castField.call(null, field, info)];
  5495. }catch(err){
  5496. return [err];
  5497. }
  5498. }
  5499. if(this.__isFloat(field)){
  5500. return [undefined, parseFloat(field)];
  5501. }else if(this.options.cast_date !== false){
  5502. const info = this.__infoField();
  5503. return [undefined, this.options.cast_date.call(null, field, info)];
  5504. }
  5505. return [undefined, field];
  5506. },
  5507. // Helper to test if a character is a space or a line delimiter
  5508. __isCharTrimable: function(buf, pos){
  5509. const isTrim = (buf, pos) => {
  5510. const {timchars} = this.state;
  5511. loop1: for(let i = 0; i < timchars.length; i++){
  5512. const timchar = timchars[i];
  5513. for(let j = 0; j < timchar.length; j++){
  5514. if(timchar[j] !== buf[pos+j]) continue loop1;
  5515. }
  5516. return timchar.length;
  5517. }
  5518. return 0;
  5519. };
  5520. return isTrim(buf, pos);
  5521. },
  5522. // Keep it in case we implement the `cast_int` option
  5523. // __isInt(value){
  5524. // // return Number.isInteger(parseInt(value))
  5525. // // return !isNaN( parseInt( obj ) );
  5526. // return /^(\-|\+)?[1-9][0-9]*$/.test(value)
  5527. // }
  5528. __isFloat: function(value){
  5529. return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery
  5530. },
  5531. __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){
  5532. if(sourceBuf[0] !== firstByte) return 0;
  5533. const sourceLength = sourceBuf.length;
  5534. for(let i = 1; i < sourceLength; i++){
  5535. if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0;
  5536. }
  5537. return sourceLength;
  5538. },
  5539. __isDelimiter: function(buf, pos, chr){
  5540. const {delimiter, ignore_last_delimiters} = this.options;
  5541. if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){
  5542. return 0;
  5543. }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){
  5544. return 0;
  5545. }
  5546. loop1: for(let i = 0; i < delimiter.length; i++){
  5547. const del = delimiter[i];
  5548. if(del[0] === chr){
  5549. for(let j = 1; j < del.length; j++){
  5550. if(del[j] !== buf[pos+j]) continue loop1;
  5551. }
  5552. return del.length;
  5553. }
  5554. }
  5555. return 0;
  5556. },
  5557. __isRecordDelimiter: function(chr, buf, pos){
  5558. const {record_delimiter} = this.options;
  5559. const recordDelimiterLength = record_delimiter.length;
  5560. loop1: for(let i = 0; i < recordDelimiterLength; i++){
  5561. const rd = record_delimiter[i];
  5562. const rdLength = rd.length;
  5563. if(rd[0] !== chr){
  5564. continue;
  5565. }
  5566. for(let j = 1; j < rdLength; j++){
  5567. if(rd[j] !== buf[pos+j]){
  5568. continue loop1;
  5569. }
  5570. }
  5571. return rd.length;
  5572. }
  5573. return 0;
  5574. },
  5575. __isEscape: function(buf, pos, chr){
  5576. const {escape} = this.options;
  5577. if(escape === null) return false;
  5578. const l = escape.length;
  5579. if(escape[0] === chr){
  5580. for(let i = 0; i < l; i++){
  5581. if(escape[i] !== buf[pos+i]){
  5582. return false;
  5583. }
  5584. }
  5585. return true;
  5586. }
  5587. return false;
  5588. },
  5589. __isQuote: function(buf, pos){
  5590. const {quote} = this.options;
  5591. if(quote === null) return false;
  5592. const l = quote.length;
  5593. for(let i = 0; i < l; i++){
  5594. if(quote[i] !== buf[pos+i]){
  5595. return false;
  5596. }
  5597. }
  5598. return true;
  5599. },
  5600. __autoDiscoverRecordDelimiter: function(buf, pos){
  5601. const { encoding } = this.options;
  5602. // Note, we don't need to cache this information in state,
  5603. // It is only called on the first line until we find out a suitable
  5604. // record delimiter.
  5605. const rds = [
  5606. // Important, the windows line ending must be before mac os 9
  5607. Buffer.from('\r\n', encoding),
  5608. Buffer.from('\n', encoding),
  5609. Buffer.from('\r', encoding),
  5610. ];
  5611. loop: for(let i = 0; i < rds.length; i++){
  5612. const l = rds[i].length;
  5613. for(let j = 0; j < l; j++){
  5614. if(rds[i][j] !== buf[pos + j]){
  5615. continue loop;
  5616. }
  5617. }
  5618. this.options.record_delimiter.push(rds[i]);
  5619. this.state.recordDelimiterMaxLength = rds[i].length;
  5620. return rds[i].length;
  5621. }
  5622. return 0;
  5623. },
  5624. __error: function(msg){
  5625. const {encoding, raw, skip_records_with_error} = this.options;
  5626. const err = typeof msg === 'string' ? new Error(msg) : msg;
  5627. if(skip_records_with_error){
  5628. this.state.recordHasError = true;
  5629. if(this.options.on_skip !== undefined){
  5630. this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
  5631. }
  5632. // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined);
  5633. return undefined;
  5634. }else {
  5635. return err;
  5636. }
  5637. },
  5638. __infoDataSet: function(){
  5639. return {
  5640. ...this.info,
  5641. columns: this.options.columns
  5642. };
  5643. },
  5644. __infoRecord: function(){
  5645. const {columns, raw, encoding} = this.options;
  5646. return {
  5647. ...this.__infoDataSet(),
  5648. error: this.state.error,
  5649. header: columns === true,
  5650. index: this.state.record.length,
  5651. raw: raw ? this.state.rawBuffer.toString(encoding) : undefined
  5652. };
  5653. },
  5654. __infoField: function(){
  5655. const {columns} = this.options;
  5656. const isColumns = Array.isArray(columns);
  5657. return {
  5658. ...this.__infoRecord(),
  5659. column: isColumns === true ?
  5660. (columns.length > this.state.record.length ?
  5661. columns[this.state.record.length].name :
  5662. null
  5663. ) :
  5664. this.state.record.length,
  5665. quoting: this.state.wasQuoting,
  5666. };
  5667. }
  5668. };
  5669. };
  5670. class Parser extends Transform {
  5671. constructor(opts = {}){
  5672. super({...{readableObjectMode: true}, ...opts, encoding: null});
  5673. this.api = transform(opts);
  5674. this.api.options.on_skip = (err, chunk) => {
  5675. this.emit('skip', err, chunk);
  5676. };
  5677. // Backward compatibility
  5678. this.state = this.api.state;
  5679. this.options = this.api.options;
  5680. this.info = this.api.info;
  5681. }
  5682. // Implementation of `Transform._transform`
  5683. _transform(buf, _, callback){
  5684. if(this.state.stop === true){
  5685. return;
  5686. }
  5687. const err = this.api.parse(buf, false, (record) => {
  5688. this.push(record);
  5689. }, () => {
  5690. this.push(null);
  5691. this.end();
  5692. // Fix #333 and break #410
  5693. // ko: api.stream.iterator.coffee
  5694. // ko with v21.4.0, ok with node v20.5.1: api.stream.finished # aborted (with generate())
  5695. // ko: api.stream.finished # aborted (with Readable)
  5696. // this.destroy()
  5697. // Fix #410 and partially break #333
  5698. // ok: api.stream.iterator.coffee
  5699. // ok: api.stream.finished # aborted (with generate())
  5700. // broken: api.stream.finished # aborted (with Readable)
  5701. this.on('end', this.destroy);
  5702. });
  5703. if(err !== undefined){
  5704. this.state.stop = true;
  5705. }
  5706. callback(err);
  5707. }
  5708. // Implementation of `Transform._flush`
  5709. _flush(callback){
  5710. if(this.state.stop === true){
  5711. return;
  5712. }
  5713. const err = this.api.parse(undefined, true, (record) => {
  5714. this.push(record);
  5715. }, () => {
  5716. this.push(null);
  5717. this.on('end', this.destroy);
  5718. });
  5719. callback(err);
  5720. }
  5721. }
  5722. const parse = function(){
  5723. let data, options, callback;
  5724. for(const i in arguments){
  5725. const argument = arguments[i];
  5726. const type = typeof argument;
  5727. if(data === undefined && (typeof argument === 'string' || isBuffer(argument))){
  5728. data = argument;
  5729. }else if(options === undefined && is_object(argument)){
  5730. options = argument;
  5731. }else if(callback === undefined && type === 'function'){
  5732. callback = argument;
  5733. }else {
  5734. throw new CsvError('CSV_INVALID_ARGUMENT', [
  5735. 'Invalid argument:',
  5736. `got ${JSON.stringify(argument)} at index ${i}`
  5737. ], options || {});
  5738. }
  5739. }
  5740. const parser = new Parser(options);
  5741. if(callback){
  5742. const records = options === undefined || options.objname === undefined ? [] : {};
  5743. parser.on('readable', function(){
  5744. let record;
  5745. while((record = this.read()) !== null){
  5746. if(options === undefined || options.objname === undefined){
  5747. records.push(record);
  5748. }else {
  5749. records[record[0]] = record[1];
  5750. }
  5751. }
  5752. });
  5753. parser.on('error', function(err){
  5754. callback(err, undefined, parser.api.__infoDataSet());
  5755. });
  5756. parser.on('end', function(){
  5757. callback(undefined, records, parser.api.__infoDataSet());
  5758. });
  5759. }
  5760. if(data !== undefined){
  5761. const writer = function(){
  5762. parser.write(data);
  5763. parser.end();
  5764. };
  5765. // Support Deno, Rollup doesnt provide a shim for setImmediate
  5766. if(typeof setImmediate === 'function'){
  5767. setImmediate(writer);
  5768. }else {
  5769. setTimeout(writer, 0);
  5770. }
  5771. }
  5772. return parser;
  5773. };
  5774. export { CsvError, Parser, parse };