wechat wss demo

mqtt.js 310KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.mqtt = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (process,global){
  3. 'use strict'
  4. /**
  5. * Module dependencies
  6. */
  7. var events = require('events')
  8. var Store = require('./store')
  9. var eos = require('end-of-stream')
  10. var mqttPacket = require('mqtt-packet')
  11. var Writable = require('readable-stream').Writable
  12. var inherits = require('inherits')
  13. var reInterval = require('reinterval')
  14. var validations = require('./validations')
  15. var xtend = require('xtend')
  16. var setImmediate = global.setImmediate || function (callback) {
  17. // works in node v0.8
  18. process.nextTick(callback)
  19. }
  20. var defaultConnectOptions = {
  21. keepalive: 60,
  22. reschedulePings: true,
  23. protocolId: 'MQTT',
  24. protocolVersion: 4,
  25. reconnectPeriod: 1000,
  26. connectTimeout: 30 * 1000,
  27. clean: true,
  28. resubscribe: true
  29. }
  30. function defaultId () {
  31. return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
  32. }
  33. function sendPacket (client, packet, cb) {
  34. client.emit('packetsend', packet)
  35. var result = mqttPacket.writeToStream(packet, client.stream)
  36. if (!result && cb) {
  37. client.stream.once('drain', cb)
  38. } else if (cb) {
  39. cb()
  40. }
  41. }
  42. function flush (queue) {
  43. if (queue) {
  44. Object.keys(queue).forEach(function (messageId) {
  45. if (typeof queue[messageId] === 'function') {
  46. queue[messageId](new Error('Connection closed'))
  47. delete queue[messageId]
  48. }
  49. })
  50. }
  51. }
  52. function storeAndSend (client, packet, cb) {
  53. client.outgoingStore.put(packet, function storedPacket (err) {
  54. if (err) {
  55. return cb && cb(err)
  56. }
  57. sendPacket(client, packet, cb)
  58. })
  59. }
  60. function nop () {}
  61. /**
  62. * MqttClient constructor
  63. *
  64. * @param {Stream} stream - stream
  65. * @param {Object} [options] - connection options
  66. * (see Connection#connect)
  67. */
  68. function MqttClient (streamBuilder, options) {
  69. var k
  70. var that = this
  71. if (!(this instanceof MqttClient)) {
  72. return new MqttClient(streamBuilder, options)
  73. }
  74. this.options = options || {}
  75. // Defaults
  76. for (k in defaultConnectOptions) {
  77. if (typeof this.options[k] === 'undefined') {
  78. this.options[k] = defaultConnectOptions[k]
  79. } else {
  80. this.options[k] = options[k]
  81. }
  82. }
  83. this.options.clientId = (typeof this.options.clientId === 'string') ? this.options.clientId : defaultId()
  84. this.streamBuilder = streamBuilder
  85. // Inflight message storages
  86. this.outgoingStore = this.options.outgoingStore || new Store()
  87. this.incomingStore = this.options.incomingStore || new Store()
  88. // Should QoS zero messages be queued when the connection is broken?
  89. this.queueQoSZero = this.options.queueQoSZero === undefined ? true : this.options.queueQoSZero
  90. // map of subscribed topics to support reconnection
  91. this._resubscribeTopics = {}
  92. // map of a subscribe messageId and a topic
  93. this.messageIdToTopic = {}
  94. // Ping timer, setup in _setupPingTimer
  95. this.pingTimer = null
  96. // Is the client connected?
  97. this.connected = false
  98. // Are we disconnecting?
  99. this.disconnecting = false
  100. // Packet queue
  101. this.queue = []
  102. // connack timer
  103. this.connackTimer = null
  104. // Reconnect timer
  105. this.reconnectTimer = null
  106. // MessageIDs starting with 1
  107. this.nextId = Math.floor(Math.random() * 65535)
  108. // Inflight callbacks
  109. this.outgoing = {}
  110. // Mark connected on connect
  111. this.on('connect', function () {
  112. if (this.disconnected) {
  113. return
  114. }
  115. this.connected = true
  116. var outStore = null
  117. outStore = this.outgoingStore.createStream()
  118. // Control of stored messages
  119. outStore.once('readable', function () {
  120. function storeDeliver () {
  121. var packet = outStore.read(1)
  122. var cb
  123. if (!packet) {
  124. return
  125. }
  126. // Avoid unnecessary stream read operations when disconnected
  127. if (!that.disconnecting && !that.reconnectTimer && that.options.reconnectPeriod > 0) {
  128. outStore.read(0)
  129. cb = that.outgoing[packet.messageId]
  130. that.outgoing[packet.messageId] = function (err, status) {
  131. // Ensure that the original callback passed in to publish gets invoked
  132. if (cb) {
  133. cb(err, status)
  134. }
  135. storeDeliver()
  136. }
  137. that._sendPacket(packet)
  138. } else if (outStore.destroy) {
  139. outStore.destroy()
  140. }
  141. }
  142. storeDeliver()
  143. }).on('error', this.emit.bind(this, 'error'))
  144. })
  145. // Mark disconnected on stream close
  146. this.on('close', function () {
  147. this.connected = false
  148. clearTimeout(this.connackTimer)
  149. })
  150. // Setup ping timer
  151. this.on('connect', this._setupPingTimer)
  152. // Send queued packets
  153. this.on('connect', function () {
  154. var queue = this.queue
  155. function deliver () {
  156. var entry = queue.shift()
  157. var packet = null
  158. if (!entry) {
  159. return
  160. }
  161. packet = entry.packet
  162. that._sendPacket(
  163. packet,
  164. function (err) {
  165. if (entry.cb) {
  166. entry.cb(err)
  167. }
  168. deliver()
  169. }
  170. )
  171. }
  172. deliver()
  173. })
  174. var firstConnection = true
  175. // resubscribe
  176. this.on('connect', function () {
  177. if (!firstConnection &&
  178. this.options.clean &&
  179. Object.keys(this._resubscribeTopics).length > 0) {
  180. if (this.options.resubscribe) {
  181. this._resubscribeTopics.resubscribe = true
  182. this.subscribe(this._resubscribeTopics)
  183. } else {
  184. this._resubscribeTopics = {}
  185. }
  186. }
  187. firstConnection = false
  188. })
  189. // Clear ping timer
  190. this.on('close', function () {
  191. if (that.pingTimer !== null) {
  192. that.pingTimer.clear()
  193. that.pingTimer = null
  194. }
  195. })
  196. // Setup reconnect timer on disconnect
  197. this.on('close', this._setupReconnect)
  198. events.EventEmitter.call(this)
  199. this._setupStream()
  200. }
  201. inherits(MqttClient, events.EventEmitter)
  202. /**
  203. * setup the event handlers in the inner stream.
  204. *
  205. * @api private
  206. */
  207. MqttClient.prototype._setupStream = function () {
  208. var connectPacket
  209. var that = this
  210. var writable = new Writable()
  211. var parser = mqttPacket.parser(this.options)
  212. var completeParse = null
  213. var packets = []
  214. this._clearReconnect()
  215. this.stream = this.streamBuilder(this)
  216. parser.on('packet', function (packet) {
  217. packets.push(packet)
  218. })
  219. function nextTickWork () {
  220. process.nextTick(work)
  221. }
  222. function work () {
  223. var packet = packets.shift()
  224. var done = completeParse
  225. if (packet) {
  226. that._handlePacket(packet, nextTickWork)
  227. } else {
  228. completeParse = null
  229. done()
  230. }
  231. }
  232. writable._write = function (buf, enc, done) {
  233. completeParse = done
  234. parser.parse(buf)
  235. work()
  236. }
  237. this.stream.pipe(writable)
  238. // Suppress connection errors
  239. this.stream.on('error', nop)
  240. // Echo stream close
  241. eos(this.stream, this.emit.bind(this, 'close'))
  242. // Send a connect packet
  243. connectPacket = Object.create(this.options)
  244. connectPacket.cmd = 'connect'
  245. // avoid message queue
  246. sendPacket(this, connectPacket)
  247. // Echo connection errors
  248. parser.on('error', this.emit.bind(this, 'error'))
  249. // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
  250. this.stream.setMaxListeners(1000)
  251. clearTimeout(this.connackTimer)
  252. this.connackTimer = setTimeout(function () {
  253. that._cleanUp(true)
  254. }, this.options.connectTimeout)
  255. }
  256. MqttClient.prototype._handlePacket = function (packet, done) {
  257. this.emit('packetreceive', packet)
  258. switch (packet.cmd) {
  259. case 'publish':
  260. this._handlePublish(packet, done)
  261. break
  262. case 'puback':
  263. case 'pubrec':
  264. case 'pubcomp':
  265. case 'suback':
  266. case 'unsuback':
  267. this._handleAck(packet)
  268. done()
  269. break
  270. case 'pubrel':
  271. this._handlePubrel(packet, done)
  272. break
  273. case 'connack':
  274. this._handleConnack(packet)
  275. done()
  276. break
  277. case 'pingresp':
  278. this._handlePingresp(packet)
  279. done()
  280. break
  281. default:
  282. // do nothing
  283. // maybe we should do an error handling
  284. // or just log it
  285. break
  286. }
  287. }
  288. MqttClient.prototype._checkDisconnecting = function (callback) {
  289. if (this.disconnecting) {
  290. if (callback) {
  291. callback(new Error('client disconnecting'))
  292. } else {
  293. this.emit('error', new Error('client disconnecting'))
  294. }
  295. }
  296. return this.disconnecting
  297. }
  298. /**
  299. * publish - publish <message> to <topic>
  300. *
  301. * @param {String} topic - topic to publish to
  302. * @param {String, Buffer} message - message to publish
  303. * @param {Object} [opts] - publish options, includes:
  304. * {Number} qos - qos level to publish on
  305. * {Boolean} retain - whether or not to retain the message
  306. * {Boolean} dup - whether or not mark a message as duplicate
  307. * @param {Function} [callback] - function(err){}
  308. * called when publish succeeds or fails
  309. * @returns {MqttClient} this - for chaining
  310. * @api public
  311. *
  312. * @example client.publish('topic', 'message');
  313. * @example
  314. * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
  315. * @example client.publish('topic', 'message', console.log);
  316. */
  317. MqttClient.prototype.publish = function (topic, message, opts, callback) {
  318. var packet
  319. // .publish(topic, payload, cb);
  320. if (typeof opts === 'function') {
  321. callback = opts
  322. opts = null
  323. }
  324. // default opts
  325. var defaultOpts = {qos: 0, retain: false, dup: false}
  326. opts = xtend(defaultOpts, opts)
  327. if (this._checkDisconnecting(callback)) {
  328. return this
  329. }
  330. packet = {
  331. cmd: 'publish',
  332. topic: topic,
  333. payload: message,
  334. qos: opts.qos,
  335. retain: opts.retain,
  336. messageId: this._nextId(),
  337. dup: opts.dup
  338. }
  339. switch (opts.qos) {
  340. case 1:
  341. case 2:
  342. // Add to callbacks
  343. this.outgoing[packet.messageId] = callback || nop
  344. this._sendPacket(packet)
  345. break
  346. default:
  347. this._sendPacket(packet, callback)
  348. break
  349. }
  350. return this
  351. }
  352. /**
  353. * subscribe - subscribe to <topic>
  354. *
  355. * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
  356. * @param {Object} [opts] - optional subscription options, includes:
  357. * {Number} qos - subscribe qos level
  358. * @param {Function} [callback] - function(err, granted){} where:
  359. * {Error} err - subscription error (none at the moment!)
  360. * {Array} granted - array of {topic: 't', qos: 0}
  361. * @returns {MqttClient} this - for chaining
  362. * @api public
  363. * @example client.subscribe('topic');
  364. * @example client.subscribe('topic', {qos: 1});
  365. * @example client.subscribe({'topic': 0, 'topic2': 1}, console.log);
  366. * @example client.subscribe('topic', console.log);
  367. */
  368. MqttClient.prototype.subscribe = function () {
  369. var packet
  370. var args = Array.prototype.slice.call(arguments)
  371. var subs = []
  372. var obj = args.shift()
  373. var resubscribe = obj.resubscribe
  374. var callback = args.pop() || nop
  375. var opts = args.pop()
  376. var invalidTopic
  377. var that = this
  378. delete obj.resubscribe
  379. if (typeof obj === 'string') {
  380. obj = [obj]
  381. }
  382. if (typeof callback !== 'function') {
  383. opts = callback
  384. callback = nop
  385. }
  386. invalidTopic = validations.validateTopics(obj)
  387. if (invalidTopic !== null) {
  388. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  389. return this
  390. }
  391. if (this._checkDisconnecting(callback)) {
  392. return this
  393. }
  394. var defaultOpts = { qos: 0 }
  395. opts = xtend(defaultOpts, opts)
  396. if (Array.isArray(obj)) {
  397. obj.forEach(function (topic) {
  398. if (that._resubscribeTopics[topic] < opts.qos ||
  399. !that._resubscribeTopics.hasOwnProperty(topic) ||
  400. resubscribe) {
  401. subs.push({
  402. topic: topic,
  403. qos: opts.qos
  404. })
  405. }
  406. })
  407. } else {
  408. Object
  409. .keys(obj)
  410. .forEach(function (k) {
  411. if (that._resubscribeTopics[k] < obj[k] ||
  412. !that._resubscribeTopics.hasOwnProperty(k) ||
  413. resubscribe) {
  414. subs.push({
  415. topic: k,
  416. qos: obj[k]
  417. })
  418. }
  419. })
  420. }
  421. packet = {
  422. cmd: 'subscribe',
  423. subscriptions: subs,
  424. qos: 1,
  425. retain: false,
  426. dup: false,
  427. messageId: this._nextId()
  428. }
  429. if (!subs.length) {
  430. callback(null, [])
  431. return
  432. }
  433. // subscriptions to resubscribe to in case of disconnect
  434. if (this.options.resubscribe) {
  435. var topics = []
  436. subs.forEach(function (sub) {
  437. if (that.options.reconnectPeriod > 0) {
  438. that._resubscribeTopics[sub.topic] = sub.qos
  439. topics.push(sub.topic)
  440. }
  441. })
  442. that.messageIdToTopic[packet.messageId] = topics
  443. }
  444. this.outgoing[packet.messageId] = function (err, packet) {
  445. if (!err) {
  446. var granted = packet.granted
  447. for (var i = 0; i < granted.length; i += 1) {
  448. subs[i].qos = granted[i]
  449. }
  450. }
  451. callback(err, subs)
  452. }
  453. this._sendPacket(packet)
  454. return this
  455. }
  456. /**
  457. * unsubscribe - unsubscribe from topic(s)
  458. *
  459. * @param {String, Array} topic - topics to unsubscribe from
  460. * @param {Function} [callback] - callback fired on unsuback
  461. * @returns {MqttClient} this - for chaining
  462. * @api public
  463. * @example client.unsubscribe('topic');
  464. * @example client.unsubscribe('topic', console.log);
  465. */
  466. MqttClient.prototype.unsubscribe = function (topic, callback) {
  467. var packet = {
  468. cmd: 'unsubscribe',
  469. qos: 1,
  470. messageId: this._nextId()
  471. }
  472. var that = this
  473. callback = callback || nop
  474. if (this._checkDisconnecting(callback)) {
  475. return this
  476. }
  477. if (typeof topic === 'string') {
  478. packet.unsubscriptions = [topic]
  479. } else if (typeof topic === 'object' && topic.length) {
  480. packet.unsubscriptions = topic
  481. }
  482. if (this.options.resubscribe) {
  483. packet.unsubscriptions.forEach(function (topic) {
  484. delete that._resubscribeTopics[topic]
  485. })
  486. }
  487. this.outgoing[packet.messageId] = callback
  488. this._sendPacket(packet)
  489. return this
  490. }
  491. /**
  492. * end - close connection
  493. *
  494. * @returns {MqttClient} this - for chaining
  495. * @param {Boolean} force - do not wait for all in-flight messages to be acked
  496. * @param {Function} cb - called when the client has been closed
  497. *
  498. * @api public
  499. */
  500. MqttClient.prototype.end = function (force, cb) {
  501. var that = this
  502. if (typeof force === 'function') {
  503. cb = force
  504. force = false
  505. }
  506. function closeStores () {
  507. that.disconnected = true
  508. that.incomingStore.close(function () {
  509. that.outgoingStore.close(function () {
  510. if (cb) {
  511. cb.apply(null, arguments)
  512. }
  513. that.emit('end')
  514. })
  515. })
  516. if (that._deferredReconnect) {
  517. that._deferredReconnect()
  518. }
  519. }
  520. function finish () {
  521. // defer closesStores of an I/O cycle,
  522. // just to make sure things are
  523. // ok for websockets
  524. that._cleanUp(force, setImmediate.bind(null, closeStores))
  525. }
  526. if (this.disconnecting) {
  527. return this
  528. }
  529. this._clearReconnect()
  530. this.disconnecting = true
  531. if (!force && Object.keys(this.outgoing).length > 0) {
  532. // wait 10ms, just to be sure we received all of it
  533. this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
  534. } else {
  535. finish()
  536. }
  537. return this
  538. }
  539. /**
  540. * removeOutgoingMessage - remove a message in outgoing store
  541. * the outgoing callback will be called withe Error('Message removed') if the message is removed
  542. *
  543. * @param {Number} mid - messageId to remove message
  544. * @returns {MqttClient} this - for chaining
  545. * @api public
  546. *
  547. * @example client.removeOutgoingMessage(client.getLastMessageId());
  548. */
  549. MqttClient.prototype.removeOutgoingMessage = function (mid) {
  550. var cb = this.outgoing[mid]
  551. delete this.outgoing[mid]
  552. this.outgoingStore.del({messageId: mid}, function () {
  553. cb(new Error('Message removed'))
  554. })
  555. return this
  556. }
  557. /**
  558. * reconnect - connect again using the same options as connect()
  559. *
  560. * @param {Object} [opts] - optional reconnect options, includes:
  561. * {Store} incomingStore - a store for the incoming packets
  562. * {Store} outgoingStore - a store for the outgoing packets
  563. * if opts is not given, current stores are used
  564. * @returns {MqttClient} this - for chaining
  565. *
  566. * @api public
  567. */
  568. MqttClient.prototype.reconnect = function (opts) {
  569. var that = this
  570. var f = function () {
  571. if (opts) {
  572. that.options.incomingStore = opts.incomingStore
  573. that.options.outgoingStore = opts.outgoingStore
  574. } else {
  575. that.options.incomingStore = null
  576. that.options.outgoingStore = null
  577. }
  578. that.incomingStore = that.options.incomingStore || new Store()
  579. that.outgoingStore = that.options.outgoingStore || new Store()
  580. that.disconnecting = false
  581. that.disconnected = false
  582. that._deferredReconnect = null
  583. that._reconnect()
  584. }
  585. if (this.disconnecting && !this.disconnected) {
  586. this._deferredReconnect = f
  587. } else {
  588. f()
  589. }
  590. return this
  591. }
  592. /**
  593. * _reconnect - implement reconnection
  594. * @api privateish
  595. */
  596. MqttClient.prototype._reconnect = function () {
  597. this.emit('reconnect')
  598. this._setupStream()
  599. }
  600. /**
  601. * _setupReconnect - setup reconnect timer
  602. */
  603. MqttClient.prototype._setupReconnect = function () {
  604. var that = this
  605. if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
  606. if (!this.reconnecting) {
  607. this.emit('offline')
  608. this.reconnecting = true
  609. }
  610. that.reconnectTimer = setInterval(function () {
  611. that._reconnect()
  612. }, that.options.reconnectPeriod)
  613. }
  614. }
  615. /**
  616. * _clearReconnect - clear the reconnect timer
  617. */
  618. MqttClient.prototype._clearReconnect = function () {
  619. if (this.reconnectTimer) {
  620. clearInterval(this.reconnectTimer)
  621. this.reconnectTimer = null
  622. }
  623. }
  624. /**
  625. * _cleanUp - clean up on connection end
  626. * @api private
  627. */
  628. MqttClient.prototype._cleanUp = function (forced, done) {
  629. if (done) {
  630. this.stream.on('close', done)
  631. }
  632. if (forced) {
  633. if ((this.options.reconnectPeriod === 0) && this.options.clean) {
  634. flush(this.outgoing)
  635. }
  636. this.stream.destroy()
  637. } else {
  638. this._sendPacket(
  639. { cmd: 'disconnect' },
  640. setImmediate.bind(
  641. null,
  642. this.stream.end.bind(this.stream)
  643. )
  644. )
  645. }
  646. if (!this.disconnecting) {
  647. this._clearReconnect()
  648. this._setupReconnect()
  649. }
  650. if (this.pingTimer !== null) {
  651. this.pingTimer.clear()
  652. this.pingTimer = null
  653. }
  654. if (done && !this.connected) {
  655. this.stream.removeListener('close', done)
  656. done()
  657. }
  658. }
  659. /**
  660. * _sendPacket - send or queue a packet
  661. * @param {String} type - packet type (see `protocol`)
  662. * @param {Object} packet - packet options
  663. * @param {Function} cb - callback when the packet is sent
  664. * @api private
  665. */
  666. MqttClient.prototype._sendPacket = function (packet, cb) {
  667. if (!this.connected) {
  668. if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !== 'publish') {
  669. this.queue.push({ packet: packet, cb: cb })
  670. } else if (packet.qos > 0) {
  671. cb = this.outgoing[packet.messageId]
  672. this.outgoingStore.put(packet, function (err) {
  673. if (err) {
  674. return cb && cb(err)
  675. }
  676. })
  677. } else if (cb) {
  678. cb(new Error('No connection to broker'))
  679. }
  680. return
  681. }
  682. // When sending a packet, reschedule the ping timer
  683. this._shiftPingInterval()
  684. if (packet.cmd !== 'publish') {
  685. sendPacket(this, packet, cb)
  686. return
  687. }
  688. switch (packet.qos) {
  689. case 2:
  690. case 1:
  691. storeAndSend(this, packet, cb)
  692. break
  693. /**
  694. * no need of case here since it will be caught by default
  695. * and jshint comply that before default it must be a break
  696. * anyway it will result in -1 evaluation
  697. */
  698. case 0:
  699. /* falls through */
  700. default:
  701. sendPacket(this, packet, cb)
  702. break
  703. }
  704. }
  705. /**
  706. * _setupPingTimer - setup the ping timer
  707. *
  708. * @api private
  709. */
  710. MqttClient.prototype._setupPingTimer = function () {
  711. var that = this
  712. if (!this.pingTimer && this.options.keepalive) {
  713. this.pingResp = true
  714. this.pingTimer = reInterval(function () {
  715. that._checkPing()
  716. }, this.options.keepalive * 1000)
  717. }
  718. }
  719. /**
  720. * _shiftPingInterval - reschedule the ping interval
  721. *
  722. * @api private
  723. */
  724. MqttClient.prototype._shiftPingInterval = function () {
  725. if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
  726. this.pingTimer.reschedule(this.options.keepalive * 1000)
  727. }
  728. }
  729. /**
  730. * _checkPing - check if a pingresp has come back, and ping the server again
  731. *
  732. * @api private
  733. */
  734. MqttClient.prototype._checkPing = function () {
  735. if (this.pingResp) {
  736. this.pingResp = false
  737. this._sendPacket({ cmd: 'pingreq' })
  738. } else {
  739. // do a forced cleanup since socket will be in bad shape
  740. this._cleanUp(true)
  741. }
  742. }
  743. /**
  744. * _handlePingresp - handle a pingresp
  745. *
  746. * @api private
  747. */
  748. MqttClient.prototype._handlePingresp = function () {
  749. this.pingResp = true
  750. }
  751. /**
  752. * _handleConnack
  753. *
  754. * @param {Object} packet
  755. * @api private
  756. */
  757. MqttClient.prototype._handleConnack = function (packet) {
  758. var rc = packet.returnCode
  759. var errors = [
  760. '',
  761. 'Unacceptable protocol version',
  762. 'Identifier rejected',
  763. 'Server unavailable',
  764. 'Bad username or password',
  765. 'Not authorized'
  766. ]
  767. clearTimeout(this.connackTimer)
  768. if (rc === 0) {
  769. this.reconnecting = false
  770. this.emit('connect', packet)
  771. } else if (rc > 0) {
  772. var err = new Error('Connection refused: ' + errors[rc])
  773. err.code = rc
  774. this.emit('error', err)
  775. }
  776. }
  777. /**
  778. * _handlePublish
  779. *
  780. * @param {Object} packet
  781. * @api private
  782. */
  783. /*
  784. those late 2 case should be rewrite to comply with coding style:
  785. case 1:
  786. case 0:
  787. // do not wait sending a puback
  788. // no callback passed
  789. if (1 === qos) {
  790. this._sendPacket({
  791. cmd: 'puback',
  792. messageId: mid
  793. });
  794. }
  795. // emit the message event for both qos 1 and 0
  796. this.emit('message', topic, message, packet);
  797. this.handleMessage(packet, done);
  798. break;
  799. default:
  800. // do nothing but every switch mus have a default
  801. // log or throw an error about unknown qos
  802. break;
  803. for now i just suppressed the warnings
  804. */
  805. MqttClient.prototype._handlePublish = function (packet, done) {
  806. var topic = packet.topic.toString()
  807. var message = packet.payload
  808. var qos = packet.qos
  809. var mid = packet.messageId
  810. var that = this
  811. switch (qos) {
  812. case 2:
  813. this.incomingStore.put(packet, function () {
  814. that._sendPacket({cmd: 'pubrec', messageId: mid}, done)
  815. })
  816. break
  817. case 1:
  818. // emit the message event
  819. this.emit('message', topic, message, packet)
  820. this.handleMessage(packet, function (err) {
  821. if (err) {
  822. return done && done(err)
  823. }
  824. // send 'puback' if the above 'handleMessage' method executed
  825. // successfully.
  826. that._sendPacket({cmd: 'puback', messageId: mid}, done)
  827. })
  828. break
  829. case 0:
  830. // emit the message event
  831. this.emit('message', topic, message, packet)
  832. this.handleMessage(packet, done)
  833. break
  834. default:
  835. // do nothing
  836. // log or throw an error about unknown qos
  837. break
  838. }
  839. }
  840. /**
  841. * Handle messages with backpressure support, one at a time.
  842. * Override at will.
  843. *
  844. * @param Packet packet the packet
  845. * @param Function callback call when finished
  846. * @api public
  847. */
  848. MqttClient.prototype.handleMessage = function (packet, callback) {
  849. callback()
  850. }
  851. /**
  852. * _handleAck
  853. *
  854. * @param {Object} packet
  855. * @api private
  856. */
  857. MqttClient.prototype._handleAck = function (packet) {
  858. /* eslint no-fallthrough: "off" */
  859. var mid = packet.messageId
  860. var type = packet.cmd
  861. var response = null
  862. var cb = this.outgoing[mid]
  863. var that = this
  864. if (!cb) {
  865. // Server sent an ack in error, ignore it.
  866. return
  867. }
  868. // Process
  869. switch (type) {
  870. case 'pubcomp':
  871. // same thing as puback for QoS 2
  872. case 'puback':
  873. // Callback - we're done
  874. delete this.outgoing[mid]
  875. this.outgoingStore.del(packet, cb)
  876. break
  877. case 'pubrec':
  878. response = {
  879. cmd: 'pubrel',
  880. qos: 2,
  881. messageId: mid
  882. }
  883. this._sendPacket(response)
  884. break
  885. case 'suback':
  886. delete this.outgoing[mid]
  887. if (packet.granted.length === 1 && (packet.granted[0] & 0x80) !== 0) {
  888. // suback with Failure status
  889. var topics = this.messageIdToTopic[mid]
  890. if (topics) {
  891. topics.forEach(function (topic) {
  892. delete that._resubscribeTopics[topic]
  893. })
  894. }
  895. }
  896. cb(null, packet)
  897. break
  898. case 'unsuback':
  899. delete this.outgoing[mid]
  900. cb(null)
  901. break
  902. default:
  903. that.emit('error', new Error('unrecognized packet type'))
  904. }
  905. if (this.disconnecting &&
  906. Object.keys(this.outgoing).length === 0) {
  907. this.emit('outgoingEmpty')
  908. }
  909. }
  910. /**
  911. * _handlePubrel
  912. *
  913. * @param {Object} packet
  914. * @api private
  915. */
  916. MqttClient.prototype._handlePubrel = function (packet, callback) {
  917. var mid = packet.messageId
  918. var that = this
  919. var comp = {cmd: 'pubcomp', messageId: mid}
  920. that.incomingStore.get(packet, function (err, pub) {
  921. if (!err && pub.cmd !== 'pubrel') {
  922. that.emit('message', pub.topic, pub.payload, pub)
  923. that.incomingStore.put(packet)
  924. that.handleMessage(pub, function (err) {
  925. if (err) {
  926. return callback && callback(err)
  927. }
  928. that._sendPacket(comp, callback)
  929. })
  930. } else {
  931. that._sendPacket(comp, callback)
  932. }
  933. })
  934. }
  935. /**
  936. * _nextId
  937. */
  938. MqttClient.prototype._nextId = function () {
  939. var id = this.nextId++
  940. // Ensure 16 bit unsigned int:
  941. if (id === 65535) {
  942. this.nextId = 1
  943. }
  944. return id
  945. }
  946. /**
  947. * getLastMessageId
  948. */
  949. MqttClient.prototype.getLastMessageId = function () {
  950. return (this.nextId === 1) ? 65535 : (this.nextId - 1)
  951. }
  952. module.exports = MqttClient
  953. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  954. },{"./store":6,"./validations":7,"_process":30,"end-of-stream":16,"events":12,"inherits":18,"mqtt-packet":23,"readable-stream":45,"reinterval":46,"xtend":59}],2:[function(require,module,exports){
  955. 'use strict'
  956. var net = require('net')
  957. /*
  958. variables port and host can be removed since
  959. you have all required information in opts object
  960. */
  961. function buildBuilder (client, opts) {
  962. var port, host
  963. opts.port = opts.port || 1883
  964. opts.hostname = opts.hostname || opts.host || 'localhost'
  965. port = opts.port
  966. host = opts.hostname
  967. return net.createConnection(port, host)
  968. }
  969. module.exports = buildBuilder
  970. },{"net":11}],3:[function(require,module,exports){
  971. 'use strict'
  972. var tls = require('tls')
  973. function buildBuilder (mqttClient, opts) {
  974. var connection
  975. opts.port = opts.port || 8883
  976. opts.host = opts.hostname || opts.host || 'localhost'
  977. opts.rejectUnauthorized = opts.rejectUnauthorized !== false
  978. delete opts.path
  979. connection = tls.connect(opts)
  980. /* eslint no-use-before-define: [2, "nofunc"] */
  981. connection.on('secureConnect', function () {
  982. if (opts.rejectUnauthorized && !connection.authorized) {
  983. connection.emit('error', new Error('TLS not authorized'))
  984. } else {
  985. connection.removeListener('error', handleTLSerrors)
  986. }
  987. })
  988. function handleTLSerrors (err) {
  989. // How can I get verify this error is a tls error?
  990. if (opts.rejectUnauthorized) {
  991. mqttClient.emit('error', err)
  992. }
  993. // close this connection to match the behaviour of net
  994. // otherwise all we get is an error from the connection
  995. // and close event doesn't fire. This is a work around
  996. // to enable the reconnect code to work the same as with
  997. // net.createConnection
  998. connection.end()
  999. }
  1000. connection.on('error', handleTLSerrors)
  1001. return connection
  1002. }
  1003. module.exports = buildBuilder
  1004. },{"tls":11}],4:[function(require,module,exports){
  1005. (function (process){
  1006. 'use strict'
  1007. var websocket = require('websocket-stream')
  1008. var urlModule = require('url')
  1009. var WSS_OPTIONS = [
  1010. 'rejectUnauthorized',
  1011. 'ca',
  1012. 'cert',
  1013. 'key',
  1014. 'pfx',
  1015. 'passphrase'
  1016. ]
  1017. var IS_BROWSER = process.title === 'browser'
  1018. function buildUrl (opts, client) {
  1019. var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1020. if (typeof (opts.transformWsUrl) === 'function') {
  1021. url = opts.transformWsUrl(url, opts, client)
  1022. }
  1023. return url
  1024. }
  1025. function setDefaultOpts (opts) {
  1026. if (!opts.hostname) {
  1027. opts.hostname = 'localhost'
  1028. }
  1029. if (!opts.port) {
  1030. if (opts.protocol === 'wss') {
  1031. opts.port = 443
  1032. } else {
  1033. opts.port = 80
  1034. }
  1035. }
  1036. if (!opts.path) {
  1037. opts.path = '/'
  1038. }
  1039. if (!opts.wsOptions) {
  1040. opts.wsOptions = {}
  1041. }
  1042. if (!IS_BROWSER && opts.protocol === 'wss') {
  1043. // Add cert/key/ca etc options
  1044. WSS_OPTIONS.forEach(function (prop) {
  1045. if (opts.hasOwnProperty(prop) && !opts.wsOptions.hasOwnProperty(prop)) {
  1046. opts.wsOptions[prop] = opts[prop]
  1047. }
  1048. })
  1049. }
  1050. }
  1051. function createWebSocket (client, opts) {
  1052. var websocketSubProtocol =
  1053. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1054. ? 'mqttv3.1'
  1055. : 'mqtt'
  1056. setDefaultOpts(opts)
  1057. var url = buildUrl(opts, client)
  1058. return websocket(url, [websocketSubProtocol], opts.wsOptions)
  1059. }
  1060. function buildBuilder (client, opts) {
  1061. return createWebSocket(client, opts)
  1062. }
  1063. function buildBuilderBrowser (client, opts) {
  1064. if (!opts.hostname) {
  1065. opts.hostname = opts.host
  1066. }
  1067. if (!opts.hostname) {
  1068. // Throwing an error in a Web Worker if no `hostname` is given, because we
  1069. // can not determine the `hostname` automatically. If connecting to
  1070. // localhost, please supply the `hostname` as an argument.
  1071. if (typeof (document) === 'undefined') {
  1072. throw new Error('Could not determine host. Specify host manually.')
  1073. }
  1074. var parsed = urlModule.parse(document.URL)
  1075. opts.hostname = parsed.hostname
  1076. if (!opts.port) {
  1077. opts.port = parsed.port
  1078. }
  1079. }
  1080. return createWebSocket(client, opts)
  1081. }
  1082. if (IS_BROWSER) {
  1083. module.exports = buildBuilderBrowser
  1084. } else {
  1085. module.exports = buildBuilder
  1086. }
  1087. }).call(this,require('_process'))
  1088. },{"_process":30,"url":50,"websocket-stream":56}],5:[function(require,module,exports){
  1089. 'use strict'
  1090. /* global wx */
  1091. var socketOpen = false
  1092. var socketMsgQueue = []
  1093. function sendSocketMessage (msg) {
  1094. if (socketOpen) {
  1095. wx.sendSocketMessage({
  1096. data: msg.buffer || msg
  1097. })
  1098. } else {
  1099. socketMsgQueue.push(msg)
  1100. }
  1101. }
  1102. function WebSocket (url, protocols) {
  1103. var ws = {
  1104. OPEN: 1,
  1105. CLOSING: 2,
  1106. CLOSED: 3,
  1107. readyState: socketOpen ? 1 : 0,
  1108. send: sendSocketMessage,
  1109. close: wx.closeSocket,
  1110. onopen: null,
  1111. onmessage: null,
  1112. onclose: null,
  1113. onerror: null
  1114. }
  1115. wx.connectSocket({
  1116. url: url,
  1117. protocols: protocols
  1118. })
  1119. wx.onSocketOpen(function (res) {
  1120. ws.readyState = ws.OPEN
  1121. socketOpen = true
  1122. for (var i = 0; i < socketMsgQueue.length; i++) {
  1123. sendSocketMessage(socketMsgQueue[i])
  1124. }
  1125. socketMsgQueue = []
  1126. ws.onopen && ws.onopen.apply(ws, arguments)
  1127. })
  1128. wx.onSocketMessage(function (res) {
  1129. ws.onmessage && ws.onmessage.apply(ws, arguments)
  1130. })
  1131. wx.onSocketClose(function () {
  1132. ws.onclose && ws.onclose.apply(ws, arguments)
  1133. ws.readyState = ws.CLOSED
  1134. socketOpen = false
  1135. })
  1136. wx.onSocketError(function () {
  1137. ws.onerror && ws.onerror.apply(ws, arguments)
  1138. ws.readyState = ws.CLOSED
  1139. socketOpen = false
  1140. })
  1141. return ws
  1142. }
  1143. var websocket = require('websocket-stream')
  1144. var urlModule = require('url')
  1145. function buildUrl (opts, client) {
  1146. var protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  1147. var url = protocol + '://' + opts.hostname + opts.path
  1148. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1149. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1150. }
  1151. if (typeof (opts.transformWsUrl) === 'function') {
  1152. url = opts.transformWsUrl(url, opts, client)
  1153. }
  1154. return url
  1155. }
  1156. function setDefaultOpts (opts) {
  1157. if (!opts.hostname) {
  1158. opts.hostname = 'localhost'
  1159. }
  1160. if (!opts.path) {
  1161. opts.path = '/'
  1162. }
  1163. if (!opts.wsOptions) {
  1164. opts.wsOptions = {}
  1165. }
  1166. }
  1167. function createWebSocket (client, opts) {
  1168. var websocketSubProtocol =
  1169. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1170. ? 'mqttv3.1'
  1171. : 'mqtt'
  1172. setDefaultOpts(opts)
  1173. var url = buildUrl(opts, client)
  1174. return websocket(WebSocket(url, [websocketSubProtocol]))
  1175. }
  1176. function buildBuilder (client, opts) {
  1177. if (!opts.hostname) {
  1178. opts.hostname = opts.host
  1179. }
  1180. if (!opts.hostname) {
  1181. // Throwing an error in a Web Worker if no `hostname` is given, because we
  1182. // can not determine the `hostname` automatically. If connecting to
  1183. // localhost, please supply the `hostname` as an argument.
  1184. if (typeof (document) === 'undefined') {
  1185. throw new Error('Could not determine host. Specify host manually.')
  1186. }
  1187. var parsed = urlModule.parse(document.URL)
  1188. opts.hostname = parsed.hostname
  1189. if (!opts.port) {
  1190. opts.port = parsed.port
  1191. }
  1192. }
  1193. return createWebSocket(client, opts)
  1194. }
  1195. module.exports = buildBuilder
  1196. },{"url":50,"websocket-stream":56}],6:[function(require,module,exports){
  1197. (function (process){
  1198. 'use strict'
  1199. /**
  1200. * Module dependencies
  1201. */
  1202. var xtend = require('xtend')
  1203. var Readable = require('readable-stream').Readable
  1204. var streamsOpts = { objectMode: true }
  1205. var defaultStoreOptions = {
  1206. clean: true
  1207. }
  1208. /**
  1209. * In-memory implementation of the message store
  1210. * This can actually be saved into files.
  1211. *
  1212. * @param {Object} [options] - store options
  1213. */
  1214. function Store (options) {
  1215. if (!(this instanceof Store)) {
  1216. return new Store(options)
  1217. }
  1218. this.options = options || {}
  1219. // Defaults
  1220. this.options = xtend(defaultStoreOptions, options)
  1221. this._inflights = {}
  1222. }
  1223. /**
  1224. * Adds a packet to the store, a packet is
  1225. * anything that has a messageId property.
  1226. *
  1227. */
  1228. Store.prototype.put = function (packet, cb) {
  1229. this._inflights[packet.messageId] = packet
  1230. if (cb) {
  1231. cb()
  1232. }
  1233. return this
  1234. }
  1235. /**
  1236. * Creates a stream with all the packets in the store
  1237. *
  1238. */
  1239. Store.prototype.createStream = function () {
  1240. var stream = new Readable(streamsOpts)
  1241. var inflights = this._inflights
  1242. var ids = Object.keys(this._inflights)
  1243. var destroyed = false
  1244. var i = 0
  1245. stream._read = function () {
  1246. if (!destroyed && i < ids.length) {
  1247. this.push(inflights[ids[i++]])
  1248. } else {
  1249. this.push(null)
  1250. }
  1251. }
  1252. stream.destroy = function () {
  1253. if (destroyed) {
  1254. return
  1255. }
  1256. var self = this
  1257. destroyed = true
  1258. process.nextTick(function () {
  1259. self.emit('close')
  1260. })
  1261. }
  1262. return stream
  1263. }
  1264. /**
  1265. * deletes a packet from the store.
  1266. */
  1267. Store.prototype.del = function (packet, cb) {
  1268. packet = this._inflights[packet.messageId]
  1269. if (packet) {
  1270. delete this._inflights[packet.messageId]
  1271. cb(null, packet)
  1272. } else if (cb) {
  1273. cb(new Error('missing packet'))
  1274. }
  1275. return this
  1276. }
  1277. /**
  1278. * get a packet from the store.
  1279. */
  1280. Store.prototype.get = function (packet, cb) {
  1281. packet = this._inflights[packet.messageId]
  1282. if (packet) {
  1283. cb(null, packet)
  1284. } else if (cb) {
  1285. cb(new Error('missing packet'))
  1286. }
  1287. return this
  1288. }
  1289. /**
  1290. * Close the store
  1291. */
  1292. Store.prototype.close = function (cb) {
  1293. if (this.options.clean) {
  1294. this._inflights = null
  1295. }
  1296. if (cb) {
  1297. cb()
  1298. }
  1299. }
  1300. module.exports = Store
  1301. }).call(this,require('_process'))
  1302. },{"_process":30,"readable-stream":45,"xtend":59}],7:[function(require,module,exports){
  1303. 'use strict'
  1304. /**
  1305. * Validate a topic to see if it's valid or not.
  1306. * A topic is valid if it follow below rules:
  1307. * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
  1308. * - Rule #2: Part `#` must be located at the end of the mailbox
  1309. *
  1310. * @param {String} topic - A topic
  1311. * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
  1312. */
  1313. function validateTopic (topic) {
  1314. var parts = topic.split('/')
  1315. for (var i = 0; i < parts.length; i++) {
  1316. if (parts[i] === '+') {
  1317. continue
  1318. }
  1319. if (parts[i] === '#') {
  1320. // for Rule #2
  1321. return i === parts.length - 1
  1322. }
  1323. if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
  1324. return false
  1325. }
  1326. }
  1327. return true
  1328. }
  1329. /**
  1330. * Validate an array of topics to see if any of them is valid or not
  1331. * @param {Array} topics - Array of topics
  1332. * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
  1333. */
  1334. function validateTopics (topics) {
  1335. if (topics.length === 0) {
  1336. return 'empty_topic_list'
  1337. }
  1338. for (var i = 0; i < topics.length; i++) {
  1339. if (!validateTopic(topics[i])) {
  1340. return topics[i]
  1341. }
  1342. }
  1343. return null
  1344. }
  1345. module.exports = {
  1346. validateTopics: validateTopics
  1347. }
  1348. },{}],8:[function(require,module,exports){
  1349. (function (process){
  1350. 'use strict'
  1351. var MqttClient = require('../client')
  1352. var Store = require('../store')
  1353. var url = require('url')
  1354. var xtend = require('xtend')
  1355. var protocols = {}
  1356. if (process.title !== 'browser') {
  1357. protocols.mqtt = require('./tcp')
  1358. protocols.tcp = require('./tcp')
  1359. protocols.ssl = require('./tls')
  1360. protocols.tls = require('./tls')
  1361. protocols.mqtts = require('./tls')
  1362. } else {
  1363. protocols.wx = require('./wx')
  1364. protocols.wxs = require('./wx')
  1365. }
  1366. protocols.ws = require('./ws')
  1367. protocols.wss = require('./ws')
  1368. /**
  1369. * Parse the auth attribute and merge username and password in the options object.
  1370. *
  1371. * @param {Object} [opts] option object
  1372. */
  1373. function parseAuthOptions (opts) {
  1374. var matches
  1375. if (opts.auth) {
  1376. matches = opts.auth.match(/^(.+):(.+)$/)
  1377. if (matches) {
  1378. opts.username = matches[1]
  1379. opts.password = matches[2]
  1380. } else {
  1381. opts.username = opts.auth
  1382. }
  1383. }
  1384. }
  1385. /**
  1386. * connect - connect to an MQTT broker.
  1387. *
  1388. * @param {String} [brokerUrl] - url of the broker, optional
  1389. * @param {Object} opts - see MqttClient#constructor
  1390. */
  1391. function connect (brokerUrl, opts) {
  1392. if ((typeof brokerUrl === 'object') && !opts) {
  1393. opts = brokerUrl
  1394. brokerUrl = null
  1395. }
  1396. opts = opts || {}
  1397. if (brokerUrl) {
  1398. var parsed = url.parse(brokerUrl, true)
  1399. if (parsed.port != null) {
  1400. parsed.port = Number(parsed.port)
  1401. }
  1402. opts = xtend(parsed, opts)
  1403. if (opts.protocol === null) {
  1404. throw new Error('Missing protocol')
  1405. }
  1406. opts.protocol = opts.protocol.replace(/:$/, '')
  1407. }
  1408. // merge in the auth options if supplied
  1409. parseAuthOptions(opts)
  1410. // support clientId passed in the query string of the url
  1411. if (opts.query && typeof opts.query.clientId === 'string') {
  1412. opts.clientId = opts.query.clientId
  1413. }
  1414. if (opts.cert && opts.key) {
  1415. if (opts.protocol) {
  1416. if (['mqtts', 'wss', 'wxs'].indexOf(opts.protocol) === -1) {
  1417. switch (opts.protocol) {
  1418. case 'mqtt':
  1419. opts.protocol = 'mqtts'
  1420. break
  1421. case 'ws':
  1422. opts.protocol = 'wss'
  1423. break
  1424. case 'wx':
  1425. opts.protocol = 'wxs'
  1426. break
  1427. default:
  1428. throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
  1429. }
  1430. }
  1431. } else {
  1432. // don't know what protocol he want to use, mqtts or wss
  1433. throw new Error('Missing secure protocol key')
  1434. }
  1435. }
  1436. if (!protocols[opts.protocol]) {
  1437. var isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
  1438. opts.protocol = [
  1439. 'mqtt',
  1440. 'mqtts',
  1441. 'ws',
  1442. 'wss',
  1443. 'wx',
  1444. 'wxs'
  1445. ].filter(function (key, index) {
  1446. if (isSecure && index % 2 === 0) {
  1447. // Skip insecure protocols when requesting a secure one.
  1448. return false
  1449. }
  1450. return (typeof protocols[key] === 'function')
  1451. })[0]
  1452. }
  1453. if (opts.clean === false && !opts.clientId) {
  1454. throw new Error('Missing clientId for unclean clients')
  1455. }
  1456. function wrapper (client) {
  1457. if (opts.servers) {
  1458. if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
  1459. client._reconnectCount = 0
  1460. }
  1461. opts.host = opts.servers[client._reconnectCount].host
  1462. opts.port = opts.servers[client._reconnectCount].port
  1463. opts.hostname = opts.host
  1464. client._reconnectCount++
  1465. }
  1466. return protocols[opts.protocol](client, opts)
  1467. }
  1468. return new MqttClient(wrapper, opts)
  1469. }
  1470. module.exports = connect
  1471. module.exports.connect = connect
  1472. module.exports.MqttClient = MqttClient
  1473. module.exports.Store = Store
  1474. }).call(this,require('_process'))
  1475. },{"../client":1,"../store":6,"./tcp":2,"./tls":3,"./ws":4,"./wx":5,"_process":30,"url":50,"xtend":59}],9:[function(require,module,exports){
  1476. 'use strict'
  1477. exports.byteLength = byteLength
  1478. exports.toByteArray = toByteArray
  1479. exports.fromByteArray = fromByteArray
  1480. var lookup = []
  1481. var revLookup = []
  1482. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  1483. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  1484. for (var i = 0, len = code.length; i < len; ++i) {
  1485. lookup[i] = code[i]
  1486. revLookup[code.charCodeAt(i)] = i
  1487. }
  1488. revLookup['-'.charCodeAt(0)] = 62
  1489. revLookup['_'.charCodeAt(0)] = 63
  1490. function placeHoldersCount (b64) {
  1491. var len = b64.length
  1492. if (len % 4 > 0) {
  1493. throw new Error('Invalid string. Length must be a multiple of 4')
  1494. }
  1495. // the number of equal signs (place holders)
  1496. // if there are two placeholders, than the two characters before it
  1497. // represent one byte
  1498. // if there is only one, then the three characters before it represent 2 bytes
  1499. // this is just a cheap hack to not do indexOf twice
  1500. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  1501. }
  1502. function byteLength (b64) {
  1503. // base64 is 4/3 + up to two characters of the original data
  1504. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  1505. }
  1506. function toByteArray (b64) {
  1507. var i, l, tmp, placeHolders, arr
  1508. var len = b64.length
  1509. placeHolders = placeHoldersCount(b64)
  1510. arr = new Arr((len * 3 / 4) - placeHolders)
  1511. // if there are placeholders, only get up to the last complete 4 chars
  1512. l = placeHolders > 0 ? len - 4 : len
  1513. var L = 0
  1514. for (i = 0; i < l; i += 4) {
  1515. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  1516. arr[L++] = (tmp >> 16) & 0xFF
  1517. arr[L++] = (tmp >> 8) & 0xFF
  1518. arr[L++] = tmp & 0xFF
  1519. }
  1520. if (placeHolders === 2) {
  1521. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  1522. arr[L++] = tmp & 0xFF
  1523. } else if (placeHolders === 1) {
  1524. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  1525. arr[L++] = (tmp >> 8) & 0xFF
  1526. arr[L++] = tmp & 0xFF
  1527. }
  1528. return arr
  1529. }
  1530. function tripletToBase64 (num) {
  1531. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  1532. }
  1533. function encodeChunk (uint8, start, end) {
  1534. var tmp
  1535. var output = []
  1536. for (var i = start; i < end; i += 3) {
  1537. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  1538. output.push(tripletToBase64(tmp))
  1539. }
  1540. return output.join('')
  1541. }
  1542. function fromByteArray (uint8) {
  1543. var tmp
  1544. var len = uint8.length
  1545. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  1546. var output = ''
  1547. var parts = []
  1548. var maxChunkLength = 16383 // must be multiple of 3
  1549. // go through the array every three bytes, we'll deal with trailing stuff later
  1550. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  1551. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  1552. }
  1553. // pad the end with zeros, but make sure to not forget the extra bytes
  1554. if (extraBytes === 1) {
  1555. tmp = uint8[len - 1]
  1556. output += lookup[tmp >> 2]
  1557. output += lookup[(tmp << 4) & 0x3F]
  1558. output += '=='
  1559. } else if (extraBytes === 2) {
  1560. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  1561. output += lookup[tmp >> 10]
  1562. output += lookup[(tmp >> 4) & 0x3F]
  1563. output += lookup[(tmp << 2) & 0x3F]
  1564. output += '='
  1565. }
  1566. parts.push(output)
  1567. return parts.join('')
  1568. }
  1569. },{}],10:[function(require,module,exports){
  1570. var DuplexStream = require('readable-stream/duplex')
  1571. , util = require('util')
  1572. , Buffer = require('safe-buffer').Buffer
  1573. function BufferList (callback) {
  1574. if (!(this instanceof BufferList))
  1575. return new BufferList(callback)
  1576. this._bufs = []
  1577. this.length = 0
  1578. if (typeof callback == 'function') {
  1579. this._callback = callback
  1580. var piper = function piper (err) {
  1581. if (this._callback) {
  1582. this._callback(err)
  1583. this._callback = null
  1584. }
  1585. }.bind(this)
  1586. this.on('pipe', function onPipe (src) {
  1587. src.on('error', piper)
  1588. })
  1589. this.on('unpipe', function onUnpipe (src) {
  1590. src.removeListener('error', piper)
  1591. })
  1592. } else {
  1593. this.append(callback)
  1594. }
  1595. DuplexStream.call(this)
  1596. }
  1597. util.inherits(BufferList, DuplexStream)
  1598. BufferList.prototype._offset = function _offset (offset) {
  1599. var tot = 0, i = 0, _t
  1600. if (offset === 0) return [ 0, 0 ]
  1601. for (; i < this._bufs.length; i++) {
  1602. _t = tot + this._bufs[i].length
  1603. if (offset < _t || i == this._bufs.length - 1)
  1604. return [ i, offset - tot ]
  1605. tot = _t
  1606. }
  1607. }
  1608. BufferList.prototype.append = function append (buf) {
  1609. var i = 0
  1610. if (Buffer.isBuffer(buf)) {
  1611. this._appendBuffer(buf);
  1612. } else if (Array.isArray(buf)) {
  1613. for (; i < buf.length; i++)
  1614. this.append(buf[i])
  1615. } else if (buf instanceof BufferList) {
  1616. // unwrap argument into individual BufferLists
  1617. for (; i < buf._bufs.length; i++)
  1618. this.append(buf._bufs[i])
  1619. } else if (buf != null) {
  1620. // coerce number arguments to strings, since Buffer(number) does
  1621. // uninitialized memory allocation
  1622. if (typeof buf == 'number')
  1623. buf = buf.toString()
  1624. this._appendBuffer(Buffer.from(buf));
  1625. }
  1626. return this
  1627. }
  1628. BufferList.prototype._appendBuffer = function appendBuffer (buf) {
  1629. this._bufs.push(buf)
  1630. this.length += buf.length
  1631. }
  1632. BufferList.prototype._write = function _write (buf, encoding, callback) {
  1633. this._appendBuffer(buf)
  1634. if (typeof callback == 'function')
  1635. callback()
  1636. }
  1637. BufferList.prototype._read = function _read (size) {
  1638. if (!this.length)
  1639. return this.push(null)
  1640. size = Math.min(size, this.length)
  1641. this.push(this.slice(0, size))
  1642. this.consume(size)
  1643. }
  1644. BufferList.prototype.end = function end (chunk) {
  1645. DuplexStream.prototype.end.call(this, chunk)
  1646. if (this._callback) {
  1647. this._callback(null, this.slice())
  1648. this._callback = null
  1649. }
  1650. }
  1651. BufferList.prototype.get = function get (index) {
  1652. return this.slice(index, index + 1)[0]
  1653. }
  1654. BufferList.prototype.slice = function slice (start, end) {
  1655. if (typeof start == 'number' && start < 0)
  1656. start += this.length
  1657. if (typeof end == 'number' && end < 0)
  1658. end += this.length
  1659. return this.copy(null, 0, start, end)
  1660. }
  1661. BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
  1662. if (typeof srcStart != 'number' || srcStart < 0)
  1663. srcStart = 0
  1664. if (typeof srcEnd != 'number' || srcEnd > this.length)
  1665. srcEnd = this.length
  1666. if (srcStart >= this.length)
  1667. return dst || Buffer.alloc(0)
  1668. if (srcEnd <= 0)
  1669. return dst || Buffer.alloc(0)
  1670. var copy = !!dst
  1671. , off = this._offset(srcStart)
  1672. , len = srcEnd - srcStart
  1673. , bytes = len
  1674. , bufoff = (copy && dstStart) || 0
  1675. , start = off[1]
  1676. , l
  1677. , i
  1678. // copy/slice everything
  1679. if (srcStart === 0 && srcEnd == this.length) {
  1680. if (!copy) { // slice, but full concat if multiple buffers
  1681. return this._bufs.length === 1
  1682. ? this._bufs[0]
  1683. : Buffer.concat(this._bufs, this.length)
  1684. }
  1685. // copy, need to copy individual buffers
  1686. for (i = 0; i < this._bufs.length; i++) {
  1687. this._bufs[i].copy(dst, bufoff)
  1688. bufoff += this._bufs[i].length
  1689. }
  1690. return dst
  1691. }
  1692. // easy, cheap case where it's a subset of one of the buffers
  1693. if (bytes <= this._bufs[off[0]].length - start) {
  1694. return copy
  1695. ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
  1696. : this._bufs[off[0]].slice(start, start + bytes)
  1697. }
  1698. if (!copy) // a slice, we need something to copy in to
  1699. dst = Buffer.allocUnsafe(len)
  1700. for (i = off[0]; i < this._bufs.length; i++) {
  1701. l = this._bufs[i].length - start
  1702. if (bytes > l) {
  1703. this._bufs[i].copy(dst, bufoff, start)
  1704. } else {
  1705. this._bufs[i].copy(dst, bufoff, start, start + bytes)
  1706. break
  1707. }
  1708. bufoff += l
  1709. bytes -= l
  1710. if (start)
  1711. start = 0
  1712. }
  1713. return dst
  1714. }
  1715. BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
  1716. start = start || 0
  1717. end = end || this.length
  1718. if (start < 0)
  1719. start += this.length
  1720. if (end < 0)
  1721. end += this.length
  1722. var startOffset = this._offset(start)
  1723. , endOffset = this._offset(end)
  1724. , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
  1725. if (endOffset[1] == 0)
  1726. buffers.pop()
  1727. else
  1728. buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1])
  1729. if (startOffset[1] != 0)
  1730. buffers[0] = buffers[0].slice(startOffset[1])
  1731. return new BufferList(buffers)
  1732. }
  1733. BufferList.prototype.toString = function toString (encoding, start, end) {
  1734. return this.slice(start, end).toString(encoding)
  1735. }
  1736. BufferList.prototype.consume = function consume (bytes) {
  1737. while (this._bufs.length) {
  1738. if (bytes >= this._bufs[0].length) {
  1739. bytes -= this._bufs[0].length
  1740. this.length -= this._bufs[0].length
  1741. this._bufs.shift()
  1742. } else {
  1743. this._bufs[0] = this._bufs[0].slice(bytes)
  1744. this.length -= bytes
  1745. break
  1746. }
  1747. }
  1748. return this
  1749. }
  1750. BufferList.prototype.duplicate = function duplicate () {
  1751. var i = 0
  1752. , copy = new BufferList()
  1753. for (; i < this._bufs.length; i++)
  1754. copy.append(this._bufs[i])
  1755. return copy
  1756. }
  1757. BufferList.prototype.destroy = function destroy () {
  1758. this._bufs.length = 0
  1759. this.length = 0
  1760. this.push(null)
  1761. }
  1762. ;(function () {
  1763. var methods = {
  1764. 'readDoubleBE' : 8
  1765. , 'readDoubleLE' : 8
  1766. , 'readFloatBE' : 4
  1767. , 'readFloatLE' : 4
  1768. , 'readInt32BE' : 4
  1769. , 'readInt32LE' : 4
  1770. , 'readUInt32BE' : 4
  1771. , 'readUInt32LE' : 4
  1772. , 'readInt16BE' : 2
  1773. , 'readInt16LE' : 2
  1774. , 'readUInt16BE' : 2
  1775. , 'readUInt16LE' : 2
  1776. , 'readInt8' : 1
  1777. , 'readUInt8' : 1
  1778. }
  1779. for (var m in methods) {
  1780. (function (m) {
  1781. BufferList.prototype[m] = function (offset) {
  1782. return this.slice(offset, offset + methods[m])[m](0)
  1783. }
  1784. }(m))
  1785. }
  1786. }())
  1787. module.exports = BufferList
  1788. },{"readable-stream/duplex":35,"safe-buffer":47,"util":55}],11:[function(require,module,exports){
  1789. },{}],12:[function(require,module,exports){
  1790. // Copyright Joyent, Inc. and other Node contributors.
  1791. //
  1792. // Permission is hereby granted, free of charge, to any person obtaining a
  1793. // copy of this software and associated documentation files (the
  1794. // "Software"), to deal in the Software without restriction, including
  1795. // without limitation the rights to use, copy, modify, merge, publish,
  1796. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1797. // persons to whom the Software is furnished to do so, subject to the
  1798. // following conditions:
  1799. //
  1800. // The above copyright notice and this permission notice shall be included
  1801. // in all copies or substantial portions of the Software.
  1802. //
  1803. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1804. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1805. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1806. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1807. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1808. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1809. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1810. var objectCreate = Object.create || objectCreatePolyfill
  1811. var objectKeys = Object.keys || objectKeysPolyfill
  1812. var bind = Function.prototype.bind || functionBindPolyfill
  1813. function EventEmitter() {
  1814. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  1815. this._events = objectCreate(null);
  1816. this._eventsCount = 0;
  1817. }
  1818. this._maxListeners = this._maxListeners || undefined;
  1819. }
  1820. module.exports = EventEmitter;
  1821. // Backwards-compat with node 0.10.x
  1822. EventEmitter.EventEmitter = EventEmitter;
  1823. EventEmitter.prototype._events = undefined;
  1824. EventEmitter.prototype._maxListeners = undefined;
  1825. // By default EventEmitters will print a warning if more than 10 listeners are
  1826. // added to it. This is a useful default which helps finding memory leaks.
  1827. var defaultMaxListeners = 10;
  1828. var hasDefineProperty;
  1829. try {
  1830. var o = {};
  1831. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  1832. hasDefineProperty = o.x === 0;
  1833. } catch (err) { hasDefineProperty = false }
  1834. if (hasDefineProperty) {
  1835. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  1836. enumerable: true,
  1837. get: function() {
  1838. return defaultMaxListeners;
  1839. },
  1840. set: function(arg) {
  1841. // check whether the input is a positive number (whose value is zero or
  1842. // greater and not a NaN).
  1843. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  1844. throw new TypeError('"defaultMaxListeners" must be a positive number');
  1845. defaultMaxListeners = arg;
  1846. }
  1847. });
  1848. } else {
  1849. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  1850. }
  1851. // Obviously not all Emitters should be limited to 10. This function allows
  1852. // that to be increased. Set to zero for unlimited.
  1853. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  1854. if (typeof n !== 'number' || n < 0 || isNaN(n))
  1855. throw new TypeError('"n" argument must be a positive number');
  1856. this._maxListeners = n;
  1857. return this;
  1858. };
  1859. function $getMaxListeners(that) {
  1860. if (that._maxListeners === undefined)
  1861. return EventEmitter.defaultMaxListeners;
  1862. return that._maxListeners;
  1863. }
  1864. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  1865. return $getMaxListeners(this);
  1866. };
  1867. // These standalone emit* functions are used to optimize calling of event
  1868. // handlers for fast cases because emit() itself often has a variable number of
  1869. // arguments and can be deoptimized because of that. These functions always have
  1870. // the same number of arguments and thus do not get deoptimized, so the code
  1871. // inside them can execute faster.
  1872. function emitNone(handler, isFn, self) {
  1873. if (isFn)
  1874. handler.call(self);
  1875. else {
  1876. var len = handler.length;
  1877. var listeners = arrayClone(handler, len);
  1878. for (var i = 0; i < len; ++i)
  1879. listeners[i].call(self);
  1880. }
  1881. }
  1882. function emitOne(handler, isFn, self, arg1) {
  1883. if (isFn)
  1884. handler.call(self, arg1);
  1885. else {
  1886. var len = handler.length;
  1887. var listeners = arrayClone(handler, len);
  1888. for (var i = 0; i < len; ++i)
  1889. listeners[i].call(self, arg1);
  1890. }
  1891. }
  1892. function emitTwo(handler, isFn, self, arg1, arg2) {
  1893. if (isFn)
  1894. handler.call(self, arg1, arg2);
  1895. else {
  1896. var len = handler.length;
  1897. var listeners = arrayClone(handler, len);
  1898. for (var i = 0; i < len; ++i)
  1899. listeners[i].call(self, arg1, arg2);
  1900. }
  1901. }
  1902. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  1903. if (isFn)
  1904. handler.call(self, arg1, arg2, arg3);
  1905. else {
  1906. var len = handler.length;
  1907. var listeners = arrayClone(handler, len);
  1908. for (var i = 0; i < len; ++i)
  1909. listeners[i].call(self, arg1, arg2, arg3);
  1910. }
  1911. }
  1912. function emitMany(handler, isFn, self, args) {
  1913. if (isFn)
  1914. handler.apply(self, args);
  1915. else {
  1916. var len = handler.length;
  1917. var listeners = arrayClone(handler, len);
  1918. for (var i = 0; i < len; ++i)
  1919. listeners[i].apply(self, args);
  1920. }
  1921. }
  1922. EventEmitter.prototype.emit = function emit(type) {
  1923. var er, handler, len, args, i, events;
  1924. var doError = (type === 'error');
  1925. events = this._events;
  1926. if (events)
  1927. doError = (doError && events.error == null);
  1928. else if (!doError)
  1929. return false;
  1930. // If there is no 'error' event listener then throw.
  1931. if (doError) {
  1932. if (arguments.length > 1)
  1933. er = arguments[1];
  1934. if (er instanceof Error) {
  1935. throw er; // Unhandled 'error' event
  1936. } else {
  1937. // At least give some kind of context to the user
  1938. var err = new Error('Unhandled "error" event. (' + er + ')');
  1939. err.context = er;
  1940. throw err;
  1941. }
  1942. return false;
  1943. }
  1944. handler = events[type];
  1945. if (!handler)
  1946. return false;
  1947. var isFn = typeof handler === 'function';
  1948. len = arguments.length;
  1949. switch (len) {
  1950. // fast cases
  1951. case 1:
  1952. emitNone(handler, isFn, this);
  1953. break;
  1954. case 2:
  1955. emitOne(handler, isFn, this, arguments[1]);
  1956. break;
  1957. case 3:
  1958. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  1959. break;
  1960. case 4:
  1961. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  1962. break;
  1963. // slower
  1964. default:
  1965. args = new Array(len - 1);
  1966. for (i = 1; i < len; i++)
  1967. args[i - 1] = arguments[i];
  1968. emitMany(handler, isFn, this, args);
  1969. }
  1970. return true;
  1971. };
  1972. function _addListener(target, type, listener, prepend) {
  1973. var m;
  1974. var events;
  1975. var existing;
  1976. if (typeof listener !== 'function')
  1977. throw new TypeError('"listener" argument must be a function');
  1978. events = target._events;
  1979. if (!events) {
  1980. events = target._events = objectCreate(null);
  1981. target._eventsCount = 0;
  1982. } else {
  1983. // To avoid recursion in the case that type === "newListener"! Before
  1984. // adding it to the listeners, first emit "newListener".
  1985. if (events.newListener) {
  1986. target.emit('newListener', type,
  1987. listener.listener ? listener.listener : listener);
  1988. // Re-assign `events` because a newListener handler could have caused the
  1989. // this._events to be assigned to a new object
  1990. events = target._events;
  1991. }
  1992. existing = events[type];
  1993. }
  1994. if (!existing) {
  1995. // Optimize the case of one listener. Don't need the extra array object.
  1996. existing = events[type] = listener;
  1997. ++target._eventsCount;
  1998. } else {
  1999. if (typeof existing === 'function') {
  2000. // Adding the second element, need to change to array.
  2001. existing = events[type] =
  2002. prepend ? [listener, existing] : [existing, listener];
  2003. } else {
  2004. // If we've already got an array, just append.
  2005. if (prepend) {
  2006. existing.unshift(listener);
  2007. } else {
  2008. existing.push(listener);
  2009. }
  2010. }
  2011. // Check for listener leak
  2012. if (!existing.warned) {
  2013. m = $getMaxListeners(target);
  2014. if (m && m > 0 && existing.length > m) {
  2015. existing.warned = true;
  2016. var w = new Error('Possible EventEmitter memory leak detected. ' +
  2017. existing.length + ' "' + String(type) + '" listeners ' +
  2018. 'added. Use emitter.setMaxListeners() to ' +
  2019. 'increase limit.');
  2020. w.name = 'MaxListenersExceededWarning';
  2021. w.emitter = target;
  2022. w.type = type;
  2023. w.count = existing.length;
  2024. if (typeof console === 'object' && console.warn) {
  2025. console.warn('%s: %s', w.name, w.message);
  2026. }
  2027. }
  2028. }
  2029. }
  2030. return target;
  2031. }
  2032. EventEmitter.prototype.addListener = function addListener(type, listener) {
  2033. return _addListener(this, type, listener, false);
  2034. };
  2035. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  2036. EventEmitter.prototype.prependListener =
  2037. function prependListener(type, listener) {
  2038. return _addListener(this, type, listener, true);
  2039. };
  2040. function onceWrapper() {
  2041. if (!this.fired) {
  2042. this.target.removeListener(this.type, this.wrapFn);
  2043. this.fired = true;
  2044. switch (arguments.length) {
  2045. case 0:
  2046. return this.listener.call(this.target);
  2047. case 1:
  2048. return this.listener.call(this.target, arguments[0]);
  2049. case 2:
  2050. return this.listener.call(this.target, arguments[0], arguments[1]);
  2051. case 3:
  2052. return this.listener.call(this.target, arguments[0], arguments[1],
  2053. arguments[2]);
  2054. default:
  2055. var args = new Array(arguments.length);
  2056. for (var i = 0; i < args.length; ++i)
  2057. args[i] = arguments[i];
  2058. this.listener.apply(this.target, args);
  2059. }
  2060. }
  2061. }
  2062. function _onceWrap(target, type, listener) {
  2063. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  2064. var wrapped = bind.call(onceWrapper, state);
  2065. wrapped.listener = listener;
  2066. state.wrapFn = wrapped;
  2067. return wrapped;
  2068. }
  2069. EventEmitter.prototype.once = function once(type, listener) {
  2070. if (typeof listener !== 'function')
  2071. throw new TypeError('"listener" argument must be a function');
  2072. this.on(type, _onceWrap(this, type, listener));
  2073. return this;
  2074. };
  2075. EventEmitter.prototype.prependOnceListener =
  2076. function prependOnceListener(type, listener) {
  2077. if (typeof listener !== 'function')
  2078. throw new TypeError('"listener" argument must be a function');
  2079. this.prependListener(type, _onceWrap(this, type, listener));
  2080. return this;
  2081. };
  2082. // Emits a 'removeListener' event if and only if the listener was removed.
  2083. EventEmitter.prototype.removeListener =
  2084. function removeListener(type, listener) {
  2085. var list, events, position, i, originalListener;
  2086. if (typeof listener !== 'function')
  2087. throw new TypeError('"listener" argument must be a function');
  2088. events = this._events;
  2089. if (!events)
  2090. return this;
  2091. list = events[type];
  2092. if (!list)
  2093. return this;
  2094. if (list === listener || list.listener === listener) {
  2095. if (--this._eventsCount === 0)
  2096. this._events = objectCreate(null);
  2097. else {
  2098. delete events[type];
  2099. if (events.removeListener)
  2100. this.emit('removeListener', type, list.listener || listener);
  2101. }
  2102. } else if (typeof list !== 'function') {
  2103. position = -1;
  2104. for (i = list.length - 1; i >= 0; i--) {
  2105. if (list[i] === listener || list[i].listener === listener) {
  2106. originalListener = list[i].listener;
  2107. position = i;
  2108. break;
  2109. }
  2110. }
  2111. if (position < 0)
  2112. return this;
  2113. if (position === 0)
  2114. list.shift();
  2115. else
  2116. spliceOne(list, position);
  2117. if (list.length === 1)
  2118. events[type] = list[0];
  2119. if (events.removeListener)
  2120. this.emit('removeListener', type, originalListener || listener);
  2121. }
  2122. return this;
  2123. };
  2124. EventEmitter.prototype.removeAllListeners =
  2125. function removeAllListeners(type) {
  2126. var listeners, events, i;
  2127. events = this._events;
  2128. if (!events)
  2129. return this;
  2130. // not listening for removeListener, no need to emit
  2131. if (!events.removeListener) {
  2132. if (arguments.length === 0) {
  2133. this._events = objectCreate(null);
  2134. this._eventsCount = 0;
  2135. } else if (events[type]) {
  2136. if (--this._eventsCount === 0)
  2137. this._events = objectCreate(null);
  2138. else
  2139. delete events[type];
  2140. }
  2141. return this;
  2142. }
  2143. // emit removeListener for all listeners on all events
  2144. if (arguments.length === 0) {
  2145. var keys = objectKeys(events);
  2146. var key;
  2147. for (i = 0; i < keys.length; ++i) {
  2148. key = keys[i];
  2149. if (key === 'removeListener') continue;
  2150. this.removeAllListeners(key);
  2151. }
  2152. this.removeAllListeners('removeListener');
  2153. this._events = objectCreate(null);
  2154. this._eventsCount = 0;
  2155. return this;
  2156. }
  2157. listeners = events[type];
  2158. if (typeof listeners === 'function') {
  2159. this.removeListener(type, listeners);
  2160. } else if (listeners) {
  2161. // LIFO order
  2162. for (i = listeners.length - 1; i >= 0; i--) {
  2163. this.removeListener(type, listeners[i]);
  2164. }
  2165. }
  2166. return this;
  2167. };
  2168. EventEmitter.prototype.listeners = function listeners(type) {
  2169. var evlistener;
  2170. var ret;
  2171. var events = this._events;
  2172. if (!events)
  2173. ret = [];
  2174. else {
  2175. evlistener = events[type];
  2176. if (!evlistener)
  2177. ret = [];
  2178. else if (typeof evlistener === 'function')
  2179. ret = [evlistener.listener || evlistener];
  2180. else
  2181. ret = unwrapListeners(evlistener);
  2182. }
  2183. return ret;
  2184. };
  2185. EventEmitter.listenerCount = function(emitter, type) {
  2186. if (typeof emitter.listenerCount === 'function') {
  2187. return emitter.listenerCount(type);
  2188. } else {
  2189. return listenerCount.call(emitter, type);
  2190. }
  2191. };
  2192. EventEmitter.prototype.listenerCount = listenerCount;
  2193. function listenerCount(type) {
  2194. var events = this._events;
  2195. if (events) {
  2196. var evlistener = events[type];
  2197. if (typeof evlistener === 'function') {
  2198. return 1;
  2199. } else if (evlistener) {
  2200. return evlistener.length;
  2201. }
  2202. }
  2203. return 0;
  2204. }
  2205. EventEmitter.prototype.eventNames = function eventNames() {
  2206. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  2207. };
  2208. // About 1.5x faster than the two-arg version of Array#splice().
  2209. function spliceOne(list, index) {
  2210. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  2211. list[i] = list[k];
  2212. list.pop();
  2213. }
  2214. function arrayClone(arr, n) {
  2215. var copy = new Array(n);
  2216. for (var i = 0; i < n; ++i)
  2217. copy[i] = arr[i];
  2218. return copy;
  2219. }
  2220. function unwrapListeners(arr) {
  2221. var ret = new Array(arr.length);
  2222. for (var i = 0; i < ret.length; ++i) {
  2223. ret[i] = arr[i].listener || arr[i];
  2224. }
  2225. return ret;
  2226. }
  2227. function objectCreatePolyfill(proto) {
  2228. var F = function() {};
  2229. F.prototype = proto;
  2230. return new F;
  2231. }
  2232. function objectKeysPolyfill(obj) {
  2233. var keys = [];
  2234. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  2235. keys.push(k);
  2236. }
  2237. return k;
  2238. }
  2239. function functionBindPolyfill(context) {
  2240. var fn = this;
  2241. return function () {
  2242. return fn.apply(context, arguments);
  2243. };
  2244. }
  2245. },{}],13:[function(require,module,exports){
  2246. /*!
  2247. * The buffer module from node.js, for the browser.
  2248. *
  2249. * @author Feross Aboukhadijeh <https://feross.org>
  2250. * @license MIT
  2251. */
  2252. /* eslint-disable no-proto */
  2253. 'use strict'
  2254. var base64 = require('base64-js')
  2255. var ieee754 = require('ieee754')
  2256. exports.Buffer = Buffer
  2257. exports.SlowBuffer = SlowBuffer
  2258. exports.INSPECT_MAX_BYTES = 50
  2259. var K_MAX_LENGTH = 0x7fffffff
  2260. exports.kMaxLength = K_MAX_LENGTH
  2261. /**
  2262. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  2263. * === true Use Uint8Array implementation (fastest)
  2264. * === false Print warning and recommend using `buffer` v4.x which has an Object
  2265. * implementation (most compatible, even IE6)
  2266. *
  2267. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  2268. * Opera 11.6+, iOS 4.2+.
  2269. *
  2270. * We report that the browser does not support typed arrays if the are not subclassable
  2271. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  2272. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  2273. * for __proto__ and has a buggy typed array implementation.
  2274. */
  2275. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  2276. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  2277. typeof console.error === 'function') {
  2278. console.error(
  2279. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  2280. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  2281. )
  2282. }
  2283. function typedArraySupport () {
  2284. // Can typed array instances can be augmented?
  2285. try {
  2286. var arr = new Uint8Array(1)
  2287. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  2288. return arr.foo() === 42
  2289. } catch (e) {
  2290. return false
  2291. }
  2292. }
  2293. Object.defineProperty(Buffer.prototype, 'parent', {
  2294. get: function () {
  2295. if (!(this instanceof Buffer)) {
  2296. return undefined
  2297. }
  2298. return this.buffer
  2299. }
  2300. })
  2301. Object.defineProperty(Buffer.prototype, 'offset', {
  2302. get: function () {
  2303. if (!(this instanceof Buffer)) {
  2304. return undefined
  2305. }
  2306. return this.byteOffset
  2307. }
  2308. })
  2309. function createBuffer (length) {
  2310. if (length > K_MAX_LENGTH) {
  2311. throw new RangeError('Invalid typed array length')
  2312. }
  2313. // Return an augmented `Uint8Array` instance
  2314. var buf = new Uint8Array(length)
  2315. buf.__proto__ = Buffer.prototype
  2316. return buf
  2317. }
  2318. /**
  2319. * The Buffer constructor returns instances of `Uint8Array` that have their
  2320. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  2321. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  2322. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  2323. * returns a single octet.
  2324. *
  2325. * The `Uint8Array` prototype remains unmodified.
  2326. */
  2327. function Buffer (arg, encodingOrOffset, length) {
  2328. // Common case.
  2329. if (typeof arg === 'number') {
  2330. if (typeof encodingOrOffset === 'string') {
  2331. throw new Error(
  2332. 'If encoding is specified then the first argument must be a string'
  2333. )
  2334. }
  2335. return allocUnsafe(arg)
  2336. }
  2337. return from(arg, encodingOrOffset, length)
  2338. }
  2339. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2340. if (typeof Symbol !== 'undefined' && Symbol.species &&
  2341. Buffer[Symbol.species] === Buffer) {
  2342. Object.defineProperty(Buffer, Symbol.species, {
  2343. value: null,
  2344. configurable: true,
  2345. enumerable: false,
  2346. writable: false
  2347. })
  2348. }
  2349. Buffer.poolSize = 8192 // not used by this implementation
  2350. function from (value, encodingOrOffset, length) {
  2351. if (typeof value === 'number') {
  2352. throw new TypeError('"value" argument must not be a number')
  2353. }
  2354. if (isArrayBuffer(value) || (value && isArrayBuffer(value.buffer))) {
  2355. return fromArrayBuffer(value, encodingOrOffset, length)
  2356. }
  2357. if (typeof value === 'string') {
  2358. return fromString(value, encodingOrOffset)
  2359. }
  2360. return fromObject(value)
  2361. }
  2362. /**
  2363. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2364. * if value is a number.
  2365. * Buffer.from(str[, encoding])
  2366. * Buffer.from(array)
  2367. * Buffer.from(buffer)
  2368. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2369. **/
  2370. Buffer.from = function (value, encodingOrOffset, length) {
  2371. return from(value, encodingOrOffset, length)
  2372. }
  2373. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  2374. // https://github.com/feross/buffer/pull/148
  2375. Buffer.prototype.__proto__ = Uint8Array.prototype
  2376. Buffer.__proto__ = Uint8Array
  2377. function assertSize (size) {
  2378. if (typeof size !== 'number') {
  2379. throw new TypeError('"size" argument must be of type number')
  2380. } else if (size < 0) {
  2381. throw new RangeError('"size" argument must not be negative')
  2382. }
  2383. }
  2384. function alloc (size, fill, encoding) {
  2385. assertSize(size)
  2386. if (size <= 0) {
  2387. return createBuffer(size)
  2388. }
  2389. if (fill !== undefined) {
  2390. // Only pay attention to encoding if it's a string. This
  2391. // prevents accidentally sending in a number that would
  2392. // be interpretted as a start offset.
  2393. return typeof encoding === 'string'
  2394. ? createBuffer(size).fill(fill, encoding)
  2395. : createBuffer(size).fill(fill)
  2396. }
  2397. return createBuffer(size)
  2398. }
  2399. /**
  2400. * Creates a new filled Buffer instance.
  2401. * alloc(size[, fill[, encoding]])
  2402. **/
  2403. Buffer.alloc = function (size, fill, encoding) {
  2404. return alloc(size, fill, encoding)
  2405. }
  2406. function allocUnsafe (size) {
  2407. assertSize(size)
  2408. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  2409. }
  2410. /**
  2411. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  2412. * */
  2413. Buffer.allocUnsafe = function (size) {
  2414. return allocUnsafe(size)
  2415. }
  2416. /**
  2417. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  2418. */
  2419. Buffer.allocUnsafeSlow = function (size) {
  2420. return allocUnsafe(size)
  2421. }
  2422. function fromString (string, encoding) {
  2423. if (typeof encoding !== 'string' || encoding === '') {
  2424. encoding = 'utf8'
  2425. }
  2426. if (!Buffer.isEncoding(encoding)) {
  2427. throw new TypeError('Unknown encoding: ' + encoding)
  2428. }
  2429. var length = byteLength(string, encoding) | 0
  2430. var buf = createBuffer(length)
  2431. var actual = buf.write(string, encoding)
  2432. if (actual !== length) {
  2433. // Writing a hex string, for example, that contains invalid characters will
  2434. // cause everything after the first invalid character to be ignored. (e.g.
  2435. // 'abxxcd' will be treated as 'ab')
  2436. buf = buf.slice(0, actual)
  2437. }
  2438. return buf
  2439. }
  2440. function fromArrayLike (array) {
  2441. var length = array.length < 0 ? 0 : checked(array.length) | 0
  2442. var buf = createBuffer(length)
  2443. for (var i = 0; i < length; i += 1) {
  2444. buf[i] = array[i] & 255
  2445. }
  2446. return buf
  2447. }
  2448. function fromArrayBuffer (array, byteOffset, length) {
  2449. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2450. throw new RangeError('"offset" is outside of buffer bounds')
  2451. }
  2452. if (array.byteLength < byteOffset + (length || 0)) {
  2453. throw new RangeError('"length" is outside of buffer bounds')
  2454. }
  2455. var buf
  2456. if (byteOffset === undefined && length === undefined) {
  2457. buf = new Uint8Array(array)
  2458. } else if (length === undefined) {
  2459. buf = new Uint8Array(array, byteOffset)
  2460. } else {
  2461. buf = new Uint8Array(array, byteOffset, length)
  2462. }
  2463. // Return an augmented `Uint8Array` instance
  2464. buf.__proto__ = Buffer.prototype
  2465. return buf
  2466. }
  2467. function fromObject (obj) {
  2468. if (Buffer.isBuffer(obj)) {
  2469. var len = checked(obj.length) | 0
  2470. var buf = createBuffer(len)
  2471. if (buf.length === 0) {
  2472. return buf
  2473. }
  2474. obj.copy(buf, 0, 0, len)
  2475. return buf
  2476. }
  2477. if (obj) {
  2478. if (ArrayBuffer.isView(obj) || 'length' in obj) {
  2479. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  2480. return createBuffer(0)
  2481. }
  2482. return fromArrayLike(obj)
  2483. }
  2484. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  2485. return fromArrayLike(obj.data)
  2486. }
  2487. }
  2488. throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object.')
  2489. }
  2490. function checked (length) {
  2491. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  2492. // length is NaN (which is otherwise coerced to zero.)
  2493. if (length >= K_MAX_LENGTH) {
  2494. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2495. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  2496. }
  2497. return length | 0
  2498. }
  2499. function SlowBuffer (length) {
  2500. if (+length != length) { // eslint-disable-line eqeqeq
  2501. length = 0
  2502. }
  2503. return Buffer.alloc(+length)
  2504. }
  2505. Buffer.isBuffer = function isBuffer (b) {
  2506. return b != null && b._isBuffer === true
  2507. }
  2508. Buffer.compare = function compare (a, b) {
  2509. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  2510. throw new TypeError('Arguments must be Buffers')
  2511. }
  2512. if (a === b) return 0
  2513. var x = a.length
  2514. var y = b.length
  2515. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2516. if (a[i] !== b[i]) {
  2517. x = a[i]
  2518. y = b[i]
  2519. break
  2520. }
  2521. }
  2522. if (x < y) return -1
  2523. if (y < x) return 1
  2524. return 0
  2525. }
  2526. Buffer.isEncoding = function isEncoding (encoding) {
  2527. switch (String(encoding).toLowerCase()) {
  2528. case 'hex':
  2529. case 'utf8':
  2530. case 'utf-8':
  2531. case 'ascii':
  2532. case 'latin1':
  2533. case 'binary':
  2534. case 'base64':
  2535. case 'ucs2':
  2536. case 'ucs-2':
  2537. case 'utf16le':
  2538. case 'utf-16le':
  2539. return true
  2540. default:
  2541. return false
  2542. }
  2543. }
  2544. Buffer.concat = function concat (list, length) {
  2545. if (!Array.isArray(list)) {
  2546. throw new TypeError('"list" argument must be an Array of Buffers')
  2547. }
  2548. if (list.length === 0) {
  2549. return Buffer.alloc(0)
  2550. }
  2551. var i
  2552. if (length === undefined) {
  2553. length = 0
  2554. for (i = 0; i < list.length; ++i) {
  2555. length += list[i].length
  2556. }
  2557. }
  2558. var buffer = Buffer.allocUnsafe(length)
  2559. var pos = 0
  2560. for (i = 0; i < list.length; ++i) {
  2561. var buf = list[i]
  2562. if (ArrayBuffer.isView(buf)) {
  2563. buf = Buffer.from(buf)
  2564. }
  2565. if (!Buffer.isBuffer(buf)) {
  2566. throw new TypeError('"list" argument must be an Array of Buffers')
  2567. }
  2568. buf.copy(buffer, pos)
  2569. pos += buf.length
  2570. }
  2571. return buffer
  2572. }
  2573. function byteLength (string, encoding) {
  2574. if (Buffer.isBuffer(string)) {
  2575. return string.length
  2576. }
  2577. if (ArrayBuffer.isView(string) || isArrayBuffer(string)) {
  2578. return string.byteLength
  2579. }
  2580. if (typeof string !== 'string') {
  2581. string = '' + string
  2582. }
  2583. var len = string.length
  2584. if (len === 0) return 0
  2585. // Use a for loop to avoid recursion
  2586. var loweredCase = false
  2587. for (;;) {
  2588. switch (encoding) {
  2589. case 'ascii':
  2590. case 'latin1':
  2591. case 'binary':
  2592. return len
  2593. case 'utf8':
  2594. case 'utf-8':
  2595. case undefined:
  2596. return utf8ToBytes(string).length
  2597. case 'ucs2':
  2598. case 'ucs-2':
  2599. case 'utf16le':
  2600. case 'utf-16le':
  2601. return len * 2
  2602. case 'hex':
  2603. return len >>> 1
  2604. case 'base64':
  2605. return base64ToBytes(string).length
  2606. default:
  2607. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  2608. encoding = ('' + encoding).toLowerCase()
  2609. loweredCase = true
  2610. }
  2611. }
  2612. }
  2613. Buffer.byteLength = byteLength
  2614. function slowToString (encoding, start, end) {
  2615. var loweredCase = false
  2616. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  2617. // property of a typed array.
  2618. // This behaves neither like String nor Uint8Array in that we set start/end
  2619. // to their upper/lower bounds if the value passed is out of range.
  2620. // undefined is handled specially as per ECMA-262 6th Edition,
  2621. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  2622. if (start === undefined || start < 0) {
  2623. start = 0
  2624. }
  2625. // Return early if start > this.length. Done here to prevent potential uint32
  2626. // coercion fail below.
  2627. if (start > this.length) {
  2628. return ''
  2629. }
  2630. if (end === undefined || end > this.length) {
  2631. end = this.length
  2632. }
  2633. if (end <= 0) {
  2634. return ''
  2635. }
  2636. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  2637. end >>>= 0
  2638. start >>>= 0
  2639. if (end <= start) {
  2640. return ''
  2641. }
  2642. if (!encoding) encoding = 'utf8'
  2643. while (true) {
  2644. switch (encoding) {
  2645. case 'hex':
  2646. return hexSlice(this, start, end)
  2647. case 'utf8':
  2648. case 'utf-8':
  2649. return utf8Slice(this, start, end)
  2650. case 'ascii':
  2651. return asciiSlice(this, start, end)
  2652. case 'latin1':
  2653. case 'binary':
  2654. return latin1Slice(this, start, end)
  2655. case 'base64':
  2656. return base64Slice(this, start, end)
  2657. case 'ucs2':
  2658. case 'ucs-2':
  2659. case 'utf16le':
  2660. case 'utf-16le':
  2661. return utf16leSlice(this, start, end)
  2662. default:
  2663. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2664. encoding = (encoding + '').toLowerCase()
  2665. loweredCase = true
  2666. }
  2667. }
  2668. }
  2669. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  2670. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  2671. // reliably in a browserify context because there could be multiple different
  2672. // copies of the 'buffer' package in use. This method works even for Buffer
  2673. // instances that were created from another copy of the `buffer` package.
  2674. // See: https://github.com/feross/buffer/issues/154
  2675. Buffer.prototype._isBuffer = true
  2676. function swap (b, n, m) {
  2677. var i = b[n]
  2678. b[n] = b[m]
  2679. b[m] = i
  2680. }
  2681. Buffer.prototype.swap16 = function swap16 () {
  2682. var len = this.length
  2683. if (len % 2 !== 0) {
  2684. throw new RangeError('Buffer size must be a multiple of 16-bits')
  2685. }
  2686. for (var i = 0; i < len; i += 2) {
  2687. swap(this, i, i + 1)
  2688. }
  2689. return this
  2690. }
  2691. Buffer.prototype.swap32 = function swap32 () {
  2692. var len = this.length
  2693. if (len % 4 !== 0) {
  2694. throw new RangeError('Buffer size must be a multiple of 32-bits')
  2695. }
  2696. for (var i = 0; i < len; i += 4) {
  2697. swap(this, i, i + 3)
  2698. swap(this, i + 1, i + 2)
  2699. }
  2700. return this
  2701. }
  2702. Buffer.prototype.swap64 = function swap64 () {
  2703. var len = this.length
  2704. if (len % 8 !== 0) {
  2705. throw new RangeError('Buffer size must be a multiple of 64-bits')
  2706. }
  2707. for (var i = 0; i < len; i += 8) {
  2708. swap(this, i, i + 7)
  2709. swap(this, i + 1, i + 6)
  2710. swap(this, i + 2, i + 5)
  2711. swap(this, i + 3, i + 4)
  2712. }
  2713. return this
  2714. }
  2715. Buffer.prototype.toString = function toString () {
  2716. var length = this.length
  2717. if (length === 0) return ''
  2718. if (arguments.length === 0) return utf8Slice(this, 0, length)
  2719. return slowToString.apply(this, arguments)
  2720. }
  2721. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  2722. Buffer.prototype.equals = function equals (b) {
  2723. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2724. if (this === b) return true
  2725. return Buffer.compare(this, b) === 0
  2726. }
  2727. Buffer.prototype.inspect = function inspect () {
  2728. var str = ''
  2729. var max = exports.INSPECT_MAX_BYTES
  2730. if (this.length > 0) {
  2731. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  2732. if (this.length > max) str += ' ... '
  2733. }
  2734. return '<Buffer ' + str + '>'
  2735. }
  2736. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  2737. if (!Buffer.isBuffer(target)) {
  2738. throw new TypeError('Argument must be a Buffer')
  2739. }
  2740. if (start === undefined) {
  2741. start = 0
  2742. }
  2743. if (end === undefined) {
  2744. end = target ? target.length : 0
  2745. }
  2746. if (thisStart === undefined) {
  2747. thisStart = 0
  2748. }
  2749. if (thisEnd === undefined) {
  2750. thisEnd = this.length
  2751. }
  2752. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  2753. throw new RangeError('out of range index')
  2754. }
  2755. if (thisStart >= thisEnd && start >= end) {
  2756. return 0
  2757. }
  2758. if (thisStart >= thisEnd) {
  2759. return -1
  2760. }
  2761. if (start >= end) {
  2762. return 1
  2763. }
  2764. start >>>= 0
  2765. end >>>= 0
  2766. thisStart >>>= 0
  2767. thisEnd >>>= 0
  2768. if (this === target) return 0
  2769. var x = thisEnd - thisStart
  2770. var y = end - start
  2771. var len = Math.min(x, y)
  2772. var thisCopy = this.slice(thisStart, thisEnd)
  2773. var targetCopy = target.slice(start, end)
  2774. for (var i = 0; i < len; ++i) {
  2775. if (thisCopy[i] !== targetCopy[i]) {
  2776. x = thisCopy[i]
  2777. y = targetCopy[i]
  2778. break
  2779. }
  2780. }
  2781. if (x < y) return -1
  2782. if (y < x) return 1
  2783. return 0
  2784. }
  2785. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  2786. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  2787. //
  2788. // Arguments:
  2789. // - buffer - a Buffer to search
  2790. // - val - a string, Buffer, or number
  2791. // - byteOffset - an index into `buffer`; will be clamped to an int32
  2792. // - encoding - an optional encoding, relevant is val is a string
  2793. // - dir - true for indexOf, false for lastIndexOf
  2794. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  2795. // Empty buffer means no match
  2796. if (buffer.length === 0) return -1
  2797. // Normalize byteOffset
  2798. if (typeof byteOffset === 'string') {
  2799. encoding = byteOffset
  2800. byteOffset = 0
  2801. } else if (byteOffset > 0x7fffffff) {
  2802. byteOffset = 0x7fffffff
  2803. } else if (byteOffset < -0x80000000) {
  2804. byteOffset = -0x80000000
  2805. }
  2806. byteOffset = +byteOffset // Coerce to Number.
  2807. if (numberIsNaN(byteOffset)) {
  2808. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  2809. byteOffset = dir ? 0 : (buffer.length - 1)
  2810. }
  2811. // Normalize byteOffset: negative offsets start from the end of the buffer
  2812. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  2813. if (byteOffset >= buffer.length) {
  2814. if (dir) return -1
  2815. else byteOffset = buffer.length - 1
  2816. } else if (byteOffset < 0) {
  2817. if (dir) byteOffset = 0
  2818. else return -1
  2819. }
  2820. // Normalize val
  2821. if (typeof val === 'string') {
  2822. val = Buffer.from(val, encoding)
  2823. }
  2824. // Finally, search either indexOf (if dir is true) or lastIndexOf
  2825. if (Buffer.isBuffer(val)) {
  2826. // Special case: looking for empty string/buffer always fails
  2827. if (val.length === 0) {
  2828. return -1
  2829. }
  2830. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  2831. } else if (typeof val === 'number') {
  2832. val = val & 0xFF // Search for a byte value [0-255]
  2833. if (typeof Uint8Array.prototype.indexOf === 'function') {
  2834. if (dir) {
  2835. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  2836. } else {
  2837. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  2838. }
  2839. }
  2840. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  2841. }
  2842. throw new TypeError('val must be string, number or Buffer')
  2843. }
  2844. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  2845. var indexSize = 1
  2846. var arrLength = arr.length
  2847. var valLength = val.length
  2848. if (encoding !== undefined) {
  2849. encoding = String(encoding).toLowerCase()
  2850. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  2851. encoding === 'utf16le' || encoding === 'utf-16le') {
  2852. if (arr.length < 2 || val.length < 2) {
  2853. return -1
  2854. }
  2855. indexSize = 2
  2856. arrLength /= 2
  2857. valLength /= 2
  2858. byteOffset /= 2
  2859. }
  2860. }
  2861. function read (buf, i) {
  2862. if (indexSize === 1) {
  2863. return buf[i]
  2864. } else {
  2865. return buf.readUInt16BE(i * indexSize)
  2866. }
  2867. }
  2868. var i
  2869. if (dir) {
  2870. var foundIndex = -1
  2871. for (i = byteOffset; i < arrLength; i++) {
  2872. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  2873. if (foundIndex === -1) foundIndex = i
  2874. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  2875. } else {
  2876. if (foundIndex !== -1) i -= i - foundIndex
  2877. foundIndex = -1
  2878. }
  2879. }
  2880. } else {
  2881. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  2882. for (i = byteOffset; i >= 0; i--) {
  2883. var found = true
  2884. for (var j = 0; j < valLength; j++) {
  2885. if (read(arr, i + j) !== read(val, j)) {
  2886. found = false
  2887. break
  2888. }
  2889. }
  2890. if (found) return i
  2891. }
  2892. }
  2893. return -1
  2894. }
  2895. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  2896. return this.indexOf(val, byteOffset, encoding) !== -1
  2897. }
  2898. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  2899. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  2900. }
  2901. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  2902. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  2903. }
  2904. function hexWrite (buf, string, offset, length) {
  2905. offset = Number(offset) || 0
  2906. var remaining = buf.length - offset
  2907. if (!length) {
  2908. length = remaining
  2909. } else {
  2910. length = Number(length)
  2911. if (length > remaining) {
  2912. length = remaining
  2913. }
  2914. }
  2915. var strLen = string.length
  2916. if (length > strLen / 2) {
  2917. length = strLen / 2
  2918. }
  2919. for (var i = 0; i < length; ++i) {
  2920. var parsed = parseInt(string.substr(i * 2, 2), 16)
  2921. if (numberIsNaN(parsed)) return i
  2922. buf[offset + i] = parsed
  2923. }
  2924. return i
  2925. }
  2926. function utf8Write (buf, string, offset, length) {
  2927. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  2928. }
  2929. function asciiWrite (buf, string, offset, length) {
  2930. return blitBuffer(asciiToBytes(string), buf, offset, length)
  2931. }
  2932. function latin1Write (buf, string, offset, length) {
  2933. return asciiWrite(buf, string, offset, length)
  2934. }
  2935. function base64Write (buf, string, offset, length) {
  2936. return blitBuffer(base64ToBytes(string), buf, offset, length)
  2937. }
  2938. function ucs2Write (buf, string, offset, length) {
  2939. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  2940. }
  2941. Buffer.prototype.write = function write (string, offset, length, encoding) {
  2942. // Buffer#write(string)
  2943. if (offset === undefined) {
  2944. encoding = 'utf8'
  2945. length = this.length
  2946. offset = 0
  2947. // Buffer#write(string, encoding)
  2948. } else if (length === undefined && typeof offset === 'string') {
  2949. encoding = offset
  2950. length = this.length
  2951. offset = 0
  2952. // Buffer#write(string, offset[, length][, encoding])
  2953. } else if (isFinite(offset)) {
  2954. offset = offset >>> 0
  2955. if (isFinite(length)) {
  2956. length = length >>> 0
  2957. if (encoding === undefined) encoding = 'utf8'
  2958. } else {
  2959. encoding = length
  2960. length = undefined
  2961. }
  2962. } else {
  2963. throw new Error(
  2964. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  2965. )
  2966. }
  2967. var remaining = this.length - offset
  2968. if (length === undefined || length > remaining) length = remaining
  2969. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  2970. throw new RangeError('Attempt to write outside buffer bounds')
  2971. }
  2972. if (!encoding) encoding = 'utf8'
  2973. var loweredCase = false
  2974. for (;;) {
  2975. switch (encoding) {
  2976. case 'hex':
  2977. return hexWrite(this, string, offset, length)
  2978. case 'utf8':
  2979. case 'utf-8':
  2980. return utf8Write(this, string, offset, length)
  2981. case 'ascii':
  2982. return asciiWrite(this, string, offset, length)
  2983. case 'latin1':
  2984. case 'binary':
  2985. return latin1Write(this, string, offset, length)
  2986. case 'base64':
  2987. // Warning: maxLength not taken into account in base64Write
  2988. return base64Write(this, string, offset, length)
  2989. case 'ucs2':
  2990. case 'ucs-2':
  2991. case 'utf16le':
  2992. case 'utf-16le':
  2993. return ucs2Write(this, string, offset, length)
  2994. default:
  2995. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2996. encoding = ('' + encoding).toLowerCase()
  2997. loweredCase = true
  2998. }
  2999. }
  3000. }
  3001. Buffer.prototype.toJSON = function toJSON () {
  3002. return {
  3003. type: 'Buffer',
  3004. data: Array.prototype.slice.call(this._arr || this, 0)
  3005. }
  3006. }
  3007. function base64Slice (buf, start, end) {
  3008. if (start === 0 && end === buf.length) {
  3009. return base64.fromByteArray(buf)
  3010. } else {
  3011. return base64.fromByteArray(buf.slice(start, end))
  3012. }
  3013. }
  3014. function utf8Slice (buf, start, end) {
  3015. end = Math.min(buf.length, end)
  3016. var res = []
  3017. var i = start
  3018. while (i < end) {
  3019. var firstByte = buf[i]
  3020. var codePoint = null
  3021. var bytesPerSequence = (firstByte > 0xEF) ? 4
  3022. : (firstByte > 0xDF) ? 3
  3023. : (firstByte > 0xBF) ? 2
  3024. : 1
  3025. if (i + bytesPerSequence <= end) {
  3026. var secondByte, thirdByte, fourthByte, tempCodePoint
  3027. switch (bytesPerSequence) {
  3028. case 1:
  3029. if (firstByte < 0x80) {
  3030. codePoint = firstByte
  3031. }
  3032. break
  3033. case 2:
  3034. secondByte = buf[i + 1]
  3035. if ((secondByte & 0xC0) === 0x80) {
  3036. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  3037. if (tempCodePoint > 0x7F) {
  3038. codePoint = tempCodePoint
  3039. }
  3040. }
  3041. break
  3042. case 3:
  3043. secondByte = buf[i + 1]
  3044. thirdByte = buf[i + 2]
  3045. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  3046. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  3047. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  3048. codePoint = tempCodePoint
  3049. }
  3050. }
  3051. break
  3052. case 4:
  3053. secondByte = buf[i + 1]
  3054. thirdByte = buf[i + 2]
  3055. fourthByte = buf[i + 3]
  3056. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  3057. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  3058. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  3059. codePoint = tempCodePoint
  3060. }
  3061. }
  3062. }
  3063. }
  3064. if (codePoint === null) {
  3065. // we did not generate a valid codePoint so insert a
  3066. // replacement char (U+FFFD) and advance only 1 byte
  3067. codePoint = 0xFFFD
  3068. bytesPerSequence = 1
  3069. } else if (codePoint > 0xFFFF) {
  3070. // encode to utf16 (surrogate pair dance)
  3071. codePoint -= 0x10000
  3072. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  3073. codePoint = 0xDC00 | codePoint & 0x3FF
  3074. }
  3075. res.push(codePoint)
  3076. i += bytesPerSequence
  3077. }
  3078. return decodeCodePointsArray(res)
  3079. }
  3080. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  3081. // the lowest limit is Chrome, with 0x10000 args.
  3082. // We go 1 magnitude less, for safety
  3083. var MAX_ARGUMENTS_LENGTH = 0x1000
  3084. function decodeCodePointsArray (codePoints) {
  3085. var len = codePoints.length
  3086. if (len <= MAX_ARGUMENTS_LENGTH) {
  3087. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  3088. }
  3089. // Decode in chunks to avoid "call stack size exceeded".
  3090. var res = ''
  3091. var i = 0
  3092. while (i < len) {
  3093. res += String.fromCharCode.apply(
  3094. String,
  3095. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  3096. )
  3097. }
  3098. return res
  3099. }
  3100. function asciiSlice (buf, start, end) {
  3101. var ret = ''
  3102. end = Math.min(buf.length, end)
  3103. for (var i = start; i < end; ++i) {
  3104. ret += String.fromCharCode(buf[i] & 0x7F)
  3105. }
  3106. return ret
  3107. }
  3108. function latin1Slice (buf, start, end) {
  3109. var ret = ''
  3110. end = Math.min(buf.length, end)
  3111. for (var i = start; i < end; ++i) {
  3112. ret += String.fromCharCode(buf[i])
  3113. }
  3114. return ret
  3115. }
  3116. function hexSlice (buf, start, end) {
  3117. var len = buf.length
  3118. if (!start || start < 0) start = 0
  3119. if (!end || end < 0 || end > len) end = len
  3120. var out = ''
  3121. for (var i = start; i < end; ++i) {
  3122. out += toHex(buf[i])
  3123. }
  3124. return out
  3125. }
  3126. function utf16leSlice (buf, start, end) {
  3127. var bytes = buf.slice(start, end)
  3128. var res = ''
  3129. for (var i = 0; i < bytes.length; i += 2) {
  3130. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  3131. }
  3132. return res
  3133. }
  3134. Buffer.prototype.slice = function slice (start, end) {
  3135. var len = this.length
  3136. start = ~~start
  3137. end = end === undefined ? len : ~~end
  3138. if (start < 0) {
  3139. start += len
  3140. if (start < 0) start = 0
  3141. } else if (start > len) {
  3142. start = len
  3143. }
  3144. if (end < 0) {
  3145. end += len
  3146. if (end < 0) end = 0
  3147. } else if (end > len) {
  3148. end = len
  3149. }
  3150. if (end < start) end = start
  3151. var newBuf = this.subarray(start, end)
  3152. // Return an augmented `Uint8Array` instance
  3153. newBuf.__proto__ = Buffer.prototype
  3154. return newBuf
  3155. }
  3156. /*
  3157. * Need to make sure that buffer isn't trying to write out of bounds.
  3158. */
  3159. function checkOffset (offset, ext, length) {
  3160. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  3161. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  3162. }
  3163. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  3164. offset = offset >>> 0
  3165. byteLength = byteLength >>> 0
  3166. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3167. var val = this[offset]
  3168. var mul = 1
  3169. var i = 0
  3170. while (++i < byteLength && (mul *= 0x100)) {
  3171. val += this[offset + i] * mul
  3172. }
  3173. return val
  3174. }
  3175. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  3176. offset = offset >>> 0
  3177. byteLength = byteLength >>> 0
  3178. if (!noAssert) {
  3179. checkOffset(offset, byteLength, this.length)
  3180. }
  3181. var val = this[offset + --byteLength]
  3182. var mul = 1
  3183. while (byteLength > 0 && (mul *= 0x100)) {
  3184. val += this[offset + --byteLength] * mul
  3185. }
  3186. return val
  3187. }
  3188. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  3189. offset = offset >>> 0
  3190. if (!noAssert) checkOffset(offset, 1, this.length)
  3191. return this[offset]
  3192. }
  3193. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  3194. offset = offset >>> 0
  3195. if (!noAssert) checkOffset(offset, 2, this.length)
  3196. return this[offset] | (this[offset + 1] << 8)
  3197. }
  3198. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  3199. offset = offset >>> 0
  3200. if (!noAssert) checkOffset(offset, 2, this.length)
  3201. return (this[offset] << 8) | this[offset + 1]
  3202. }
  3203. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  3204. offset = offset >>> 0
  3205. if (!noAssert) checkOffset(offset, 4, this.length)
  3206. return ((this[offset]) |
  3207. (this[offset + 1] << 8) |
  3208. (this[offset + 2] << 16)) +
  3209. (this[offset + 3] * 0x1000000)
  3210. }
  3211. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  3212. offset = offset >>> 0
  3213. if (!noAssert) checkOffset(offset, 4, this.length)
  3214. return (this[offset] * 0x1000000) +
  3215. ((this[offset + 1] << 16) |
  3216. (this[offset + 2] << 8) |
  3217. this[offset + 3])
  3218. }
  3219. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  3220. offset = offset >>> 0
  3221. byteLength = byteLength >>> 0
  3222. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3223. var val = this[offset]
  3224. var mul = 1
  3225. var i = 0
  3226. while (++i < byteLength && (mul *= 0x100)) {
  3227. val += this[offset + i] * mul
  3228. }
  3229. mul *= 0x80
  3230. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3231. return val
  3232. }
  3233. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  3234. offset = offset >>> 0
  3235. byteLength = byteLength >>> 0
  3236. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3237. var i = byteLength
  3238. var mul = 1
  3239. var val = this[offset + --i]
  3240. while (i > 0 && (mul *= 0x100)) {
  3241. val += this[offset + --i] * mul
  3242. }
  3243. mul *= 0x80
  3244. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3245. return val
  3246. }
  3247. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  3248. offset = offset >>> 0
  3249. if (!noAssert) checkOffset(offset, 1, this.length)
  3250. if (!(this[offset] & 0x80)) return (this[offset])
  3251. return ((0xff - this[offset] + 1) * -1)
  3252. }
  3253. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  3254. offset = offset >>> 0
  3255. if (!noAssert) checkOffset(offset, 2, this.length)
  3256. var val = this[offset] | (this[offset + 1] << 8)
  3257. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3258. }
  3259. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  3260. offset = offset >>> 0
  3261. if (!noAssert) checkOffset(offset, 2, this.length)
  3262. var val = this[offset + 1] | (this[offset] << 8)
  3263. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3264. }
  3265. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  3266. offset = offset >>> 0
  3267. if (!noAssert) checkOffset(offset, 4, this.length)
  3268. return (this[offset]) |
  3269. (this[offset + 1] << 8) |
  3270. (this[offset + 2] << 16) |
  3271. (this[offset + 3] << 24)
  3272. }
  3273. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  3274. offset = offset >>> 0
  3275. if (!noAssert) checkOffset(offset, 4, this.length)
  3276. return (this[offset] << 24) |
  3277. (this[offset + 1] << 16) |
  3278. (this[offset + 2] << 8) |
  3279. (this[offset + 3])
  3280. }
  3281. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  3282. offset = offset >>> 0
  3283. if (!noAssert) checkOffset(offset, 4, this.length)
  3284. return ieee754.read(this, offset, true, 23, 4)
  3285. }
  3286. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  3287. offset = offset >>> 0
  3288. if (!noAssert) checkOffset(offset, 4, this.length)
  3289. return ieee754.read(this, offset, false, 23, 4)
  3290. }
  3291. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  3292. offset = offset >>> 0
  3293. if (!noAssert) checkOffset(offset, 8, this.length)
  3294. return ieee754.read(this, offset, true, 52, 8)
  3295. }
  3296. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  3297. offset = offset >>> 0
  3298. if (!noAssert) checkOffset(offset, 8, this.length)
  3299. return ieee754.read(this, offset, false, 52, 8)
  3300. }
  3301. function checkInt (buf, value, offset, ext, max, min) {
  3302. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  3303. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  3304. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3305. }
  3306. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  3307. value = +value
  3308. offset = offset >>> 0
  3309. byteLength = byteLength >>> 0
  3310. if (!noAssert) {
  3311. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3312. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3313. }
  3314. var mul = 1
  3315. var i = 0
  3316. this[offset] = value & 0xFF
  3317. while (++i < byteLength && (mul *= 0x100)) {
  3318. this[offset + i] = (value / mul) & 0xFF
  3319. }
  3320. return offset + byteLength
  3321. }
  3322. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  3323. value = +value
  3324. offset = offset >>> 0
  3325. byteLength = byteLength >>> 0
  3326. if (!noAssert) {
  3327. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3328. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3329. }
  3330. var i = byteLength - 1
  3331. var mul = 1
  3332. this[offset + i] = value & 0xFF
  3333. while (--i >= 0 && (mul *= 0x100)) {
  3334. this[offset + i] = (value / mul) & 0xFF
  3335. }
  3336. return offset + byteLength
  3337. }
  3338. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  3339. value = +value
  3340. offset = offset >>> 0
  3341. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  3342. this[offset] = (value & 0xff)
  3343. return offset + 1
  3344. }
  3345. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  3346. value = +value
  3347. offset = offset >>> 0
  3348. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3349. this[offset] = (value & 0xff)
  3350. this[offset + 1] = (value >>> 8)
  3351. return offset + 2
  3352. }
  3353. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  3354. value = +value
  3355. offset = offset >>> 0
  3356. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3357. this[offset] = (value >>> 8)
  3358. this[offset + 1] = (value & 0xff)
  3359. return offset + 2
  3360. }
  3361. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  3362. value = +value
  3363. offset = offset >>> 0
  3364. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3365. this[offset + 3] = (value >>> 24)
  3366. this[offset + 2] = (value >>> 16)
  3367. this[offset + 1] = (value >>> 8)
  3368. this[offset] = (value & 0xff)
  3369. return offset + 4
  3370. }
  3371. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  3372. value = +value
  3373. offset = offset >>> 0
  3374. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3375. this[offset] = (value >>> 24)
  3376. this[offset + 1] = (value >>> 16)
  3377. this[offset + 2] = (value >>> 8)
  3378. this[offset + 3] = (value & 0xff)
  3379. return offset + 4
  3380. }
  3381. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  3382. value = +value
  3383. offset = offset >>> 0
  3384. if (!noAssert) {
  3385. var limit = Math.pow(2, (8 * byteLength) - 1)
  3386. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3387. }
  3388. var i = 0
  3389. var mul = 1
  3390. var sub = 0
  3391. this[offset] = value & 0xFF
  3392. while (++i < byteLength && (mul *= 0x100)) {
  3393. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  3394. sub = 1
  3395. }
  3396. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3397. }
  3398. return offset + byteLength
  3399. }
  3400. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  3401. value = +value
  3402. offset = offset >>> 0
  3403. if (!noAssert) {
  3404. var limit = Math.pow(2, (8 * byteLength) - 1)
  3405. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3406. }
  3407. var i = byteLength - 1
  3408. var mul = 1
  3409. var sub = 0
  3410. this[offset + i] = value & 0xFF
  3411. while (--i >= 0 && (mul *= 0x100)) {
  3412. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  3413. sub = 1
  3414. }
  3415. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3416. }
  3417. return offset + byteLength
  3418. }
  3419. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  3420. value = +value
  3421. offset = offset >>> 0
  3422. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  3423. if (value < 0) value = 0xff + value + 1
  3424. this[offset] = (value & 0xff)
  3425. return offset + 1
  3426. }
  3427. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  3428. value = +value
  3429. offset = offset >>> 0
  3430. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3431. this[offset] = (value & 0xff)
  3432. this[offset + 1] = (value >>> 8)
  3433. return offset + 2
  3434. }
  3435. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  3436. value = +value
  3437. offset = offset >>> 0
  3438. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3439. this[offset] = (value >>> 8)
  3440. this[offset + 1] = (value & 0xff)
  3441. return offset + 2
  3442. }
  3443. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  3444. value = +value
  3445. offset = offset >>> 0
  3446. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3447. this[offset] = (value & 0xff)
  3448. this[offset + 1] = (value >>> 8)
  3449. this[offset + 2] = (value >>> 16)
  3450. this[offset + 3] = (value >>> 24)
  3451. return offset + 4
  3452. }
  3453. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  3454. value = +value
  3455. offset = offset >>> 0
  3456. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3457. if (value < 0) value = 0xffffffff + value + 1
  3458. this[offset] = (value >>> 24)
  3459. this[offset + 1] = (value >>> 16)
  3460. this[offset + 2] = (value >>> 8)
  3461. this[offset + 3] = (value & 0xff)
  3462. return offset + 4
  3463. }
  3464. function checkIEEE754 (buf, value, offset, ext, max, min) {
  3465. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3466. if (offset < 0) throw new RangeError('Index out of range')
  3467. }
  3468. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  3469. value = +value
  3470. offset = offset >>> 0
  3471. if (!noAssert) {
  3472. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  3473. }
  3474. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  3475. return offset + 4
  3476. }
  3477. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  3478. return writeFloat(this, value, offset, true, noAssert)
  3479. }
  3480. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  3481. return writeFloat(this, value, offset, false, noAssert)
  3482. }
  3483. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  3484. value = +value
  3485. offset = offset >>> 0
  3486. if (!noAssert) {
  3487. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  3488. }
  3489. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  3490. return offset + 8
  3491. }
  3492. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  3493. return writeDouble(this, value, offset, true, noAssert)
  3494. }
  3495. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  3496. return writeDouble(this, value, offset, false, noAssert)
  3497. }
  3498. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  3499. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  3500. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  3501. if (!start) start = 0
  3502. if (!end && end !== 0) end = this.length
  3503. if (targetStart >= target.length) targetStart = target.length
  3504. if (!targetStart) targetStart = 0
  3505. if (end > 0 && end < start) end = start
  3506. // Copy 0 bytes; we're done
  3507. if (end === start) return 0
  3508. if (target.length === 0 || this.length === 0) return 0
  3509. // Fatal error conditions
  3510. if (targetStart < 0) {
  3511. throw new RangeError('targetStart out of bounds')
  3512. }
  3513. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  3514. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  3515. // Are we oob?
  3516. if (end > this.length) end = this.length
  3517. if (target.length - targetStart < end - start) {
  3518. end = target.length - targetStart + start
  3519. }
  3520. var len = end - start
  3521. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  3522. // Use built-in when available, missing from IE11
  3523. this.copyWithin(targetStart, start, end)
  3524. } else if (this === target && start < targetStart && targetStart < end) {
  3525. // descending copy from end
  3526. for (var i = len - 1; i >= 0; --i) {
  3527. target[i + targetStart] = this[i + start]
  3528. }
  3529. } else {
  3530. Uint8Array.prototype.set.call(
  3531. target,
  3532. this.subarray(start, end),
  3533. targetStart
  3534. )
  3535. }
  3536. return len
  3537. }
  3538. // Usage:
  3539. // buffer.fill(number[, offset[, end]])
  3540. // buffer.fill(buffer[, offset[, end]])
  3541. // buffer.fill(string[, offset[, end]][, encoding])
  3542. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  3543. // Handle string cases:
  3544. if (typeof val === 'string') {
  3545. if (typeof start === 'string') {
  3546. encoding = start
  3547. start = 0
  3548. end = this.length
  3549. } else if (typeof end === 'string') {
  3550. encoding = end
  3551. end = this.length
  3552. }
  3553. if (encoding !== undefined && typeof encoding !== 'string') {
  3554. throw new TypeError('encoding must be a string')
  3555. }
  3556. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  3557. throw new TypeError('Unknown encoding: ' + encoding)
  3558. }
  3559. if (val.length === 1) {
  3560. var code = val.charCodeAt(0)
  3561. if ((encoding === 'utf8' && code < 128) ||
  3562. encoding === 'latin1') {
  3563. // Fast path: If `val` fits into a single byte, use that numeric value.
  3564. val = code
  3565. }
  3566. }
  3567. } else if (typeof val === 'number') {
  3568. val = val & 255
  3569. }
  3570. // Invalid ranges are not set to a default, so can range check early.
  3571. if (start < 0 || this.length < start || this.length < end) {
  3572. throw new RangeError('Out of range index')
  3573. }
  3574. if (end <= start) {
  3575. return this
  3576. }
  3577. start = start >>> 0
  3578. end = end === undefined ? this.length : end >>> 0
  3579. if (!val) val = 0
  3580. var i
  3581. if (typeof val === 'number') {
  3582. for (i = start; i < end; ++i) {
  3583. this[i] = val
  3584. }
  3585. } else {
  3586. var bytes = Buffer.isBuffer(val)
  3587. ? val
  3588. : new Buffer(val, encoding)
  3589. var len = bytes.length
  3590. if (len === 0) {
  3591. throw new TypeError('The value "' + val +
  3592. '" is invalid for argument "value"')
  3593. }
  3594. for (i = 0; i < end - start; ++i) {
  3595. this[i + start] = bytes[i % len]
  3596. }
  3597. }
  3598. return this
  3599. }
  3600. // HELPER FUNCTIONS
  3601. // ================
  3602. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  3603. function base64clean (str) {
  3604. // Node takes equal signs as end of the Base64 encoding
  3605. str = str.split('=')[0]
  3606. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  3607. str = str.trim().replace(INVALID_BASE64_RE, '')
  3608. // Node converts strings with length < 2 to ''
  3609. if (str.length < 2) return ''
  3610. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  3611. while (str.length % 4 !== 0) {
  3612. str = str + '='
  3613. }
  3614. return str
  3615. }
  3616. function toHex (n) {
  3617. if (n < 16) return '0' + n.toString(16)
  3618. return n.toString(16)
  3619. }
  3620. function utf8ToBytes (string, units) {
  3621. units = units || Infinity
  3622. var codePoint
  3623. var length = string.length
  3624. var leadSurrogate = null
  3625. var bytes = []
  3626. for (var i = 0; i < length; ++i) {
  3627. codePoint = string.charCodeAt(i)
  3628. // is surrogate component
  3629. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  3630. // last char was a lead
  3631. if (!leadSurrogate) {
  3632. // no lead yet
  3633. if (codePoint > 0xDBFF) {
  3634. // unexpected trail
  3635. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3636. continue
  3637. } else if (i + 1 === length) {
  3638. // unpaired lead
  3639. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3640. continue
  3641. }
  3642. // valid lead
  3643. leadSurrogate = codePoint
  3644. continue
  3645. }
  3646. // 2 leads in a row
  3647. if (codePoint < 0xDC00) {
  3648. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3649. leadSurrogate = codePoint
  3650. continue
  3651. }
  3652. // valid surrogate pair
  3653. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  3654. } else if (leadSurrogate) {
  3655. // valid bmp char, but last char was a lead
  3656. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3657. }
  3658. leadSurrogate = null
  3659. // encode utf8
  3660. if (codePoint < 0x80) {
  3661. if ((units -= 1) < 0) break
  3662. bytes.push(codePoint)
  3663. } else if (codePoint < 0x800) {
  3664. if ((units -= 2) < 0) break
  3665. bytes.push(
  3666. codePoint >> 0x6 | 0xC0,
  3667. codePoint & 0x3F | 0x80
  3668. )
  3669. } else if (codePoint < 0x10000) {
  3670. if ((units -= 3) < 0) break
  3671. bytes.push(
  3672. codePoint >> 0xC | 0xE0,
  3673. codePoint >> 0x6 & 0x3F | 0x80,
  3674. codePoint & 0x3F | 0x80
  3675. )
  3676. } else if (codePoint < 0x110000) {
  3677. if ((units -= 4) < 0) break
  3678. bytes.push(
  3679. codePoint >> 0x12 | 0xF0,
  3680. codePoint >> 0xC & 0x3F | 0x80,
  3681. codePoint >> 0x6 & 0x3F | 0x80,
  3682. codePoint & 0x3F | 0x80
  3683. )
  3684. } else {
  3685. throw new Error('Invalid code point')
  3686. }
  3687. }
  3688. return bytes
  3689. }
  3690. function asciiToBytes (str) {
  3691. var byteArray = []
  3692. for (var i = 0; i < str.length; ++i) {
  3693. // Node's code seems to be doing this and not & 0x7F..
  3694. byteArray.push(str.charCodeAt(i) & 0xFF)
  3695. }
  3696. return byteArray
  3697. }
  3698. function utf16leToBytes (str, units) {
  3699. var c, hi, lo
  3700. var byteArray = []
  3701. for (var i = 0; i < str.length; ++i) {
  3702. if ((units -= 2) < 0) break
  3703. c = str.charCodeAt(i)
  3704. hi = c >> 8
  3705. lo = c % 256
  3706. byteArray.push(lo)
  3707. byteArray.push(hi)
  3708. }
  3709. return byteArray
  3710. }
  3711. function base64ToBytes (str) {
  3712. return base64.toByteArray(base64clean(str))
  3713. }
  3714. function blitBuffer (src, dst, offset, length) {
  3715. for (var i = 0; i < length; ++i) {
  3716. if ((i + offset >= dst.length) || (i >= src.length)) break
  3717. dst[i + offset] = src[i]
  3718. }
  3719. return i
  3720. }
  3721. // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
  3722. // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
  3723. function isArrayBuffer (obj) {
  3724. return obj instanceof ArrayBuffer ||
  3725. (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
  3726. typeof obj.byteLength === 'number')
  3727. }
  3728. function numberIsNaN (obj) {
  3729. return obj !== obj // eslint-disable-line no-self-compare
  3730. }
  3731. },{"base64-js":9,"ieee754":17}],14:[function(require,module,exports){
  3732. (function (Buffer){
  3733. // Copyright Joyent, Inc. and other Node contributors.
  3734. //
  3735. // Permission is hereby granted, free of charge, to any person obtaining a
  3736. // copy of this software and associated documentation files (the
  3737. // "Software"), to deal in the Software without restriction, including
  3738. // without limitation the rights to use, copy, modify, merge, publish,
  3739. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3740. // persons to whom the Software is furnished to do so, subject to the
  3741. // following conditions:
  3742. //
  3743. // The above copyright notice and this permission notice shall be included
  3744. // in all copies or substantial portions of the Software.
  3745. //
  3746. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3747. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3748. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3749. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3750. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3751. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3752. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3753. // NOTE: These type checking functions intentionally don't use `instanceof`
  3754. // because it is fragile and can be easily faked with `Object.create()`.
  3755. function isArray(arg) {
  3756. if (Array.isArray) {
  3757. return Array.isArray(arg);
  3758. }
  3759. return objectToString(arg) === '[object Array]';
  3760. }
  3761. exports.isArray = isArray;
  3762. function isBoolean(arg) {
  3763. return typeof arg === 'boolean';
  3764. }
  3765. exports.isBoolean = isBoolean;
  3766. function isNull(arg) {
  3767. return arg === null;
  3768. }
  3769. exports.isNull = isNull;
  3770. function isNullOrUndefined(arg) {
  3771. return arg == null;
  3772. }
  3773. exports.isNullOrUndefined = isNullOrUndefined;
  3774. function isNumber(arg) {
  3775. return typeof arg === 'number';
  3776. }
  3777. exports.isNumber = isNumber;
  3778. function isString(arg) {
  3779. return typeof arg === 'string';
  3780. }
  3781. exports.isString = isString;
  3782. function isSymbol(arg) {
  3783. return typeof arg === 'symbol';
  3784. }
  3785. exports.isSymbol = isSymbol;
  3786. function isUndefined(arg) {
  3787. return arg === void 0;
  3788. }
  3789. exports.isUndefined = isUndefined;
  3790. function isRegExp(re) {
  3791. return objectToString(re) === '[object RegExp]';
  3792. }
  3793. exports.isRegExp = isRegExp;
  3794. function isObject(arg) {
  3795. return typeof arg === 'object' && arg !== null;
  3796. }
  3797. exports.isObject = isObject;
  3798. function isDate(d) {
  3799. return objectToString(d) === '[object Date]';
  3800. }
  3801. exports.isDate = isDate;
  3802. function isError(e) {
  3803. return (objectToString(e) === '[object Error]' || e instanceof Error);
  3804. }
  3805. exports.isError = isError;
  3806. function isFunction(arg) {
  3807. return typeof arg === 'function';
  3808. }
  3809. exports.isFunction = isFunction;
  3810. function isPrimitive(arg) {
  3811. return arg === null ||
  3812. typeof arg === 'boolean' ||
  3813. typeof arg === 'number' ||
  3814. typeof arg === 'string' ||
  3815. typeof arg === 'symbol' || // ES6 symbol
  3816. typeof arg === 'undefined';
  3817. }
  3818. exports.isPrimitive = isPrimitive;
  3819. exports.isBuffer = Buffer.isBuffer;
  3820. function objectToString(o) {
  3821. return Object.prototype.toString.call(o);
  3822. }
  3823. }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
  3824. },{"../../is-buffer/index.js":19}],15:[function(require,module,exports){
  3825. (function (process,Buffer){
  3826. var stream = require('readable-stream')
  3827. var eos = require('end-of-stream')
  3828. var inherits = require('inherits')
  3829. var shift = require('stream-shift')
  3830. var SIGNAL_FLUSH = new Buffer([0])
  3831. var onuncork = function(self, fn) {
  3832. if (self._corked) self.once('uncork', fn)
  3833. else fn()
  3834. }
  3835. var destroyer = function(self, end) {
  3836. return function(err) {
  3837. if (err) self.destroy(err.message === 'premature close' ? null : err)
  3838. else if (end && !self._ended) self.end()
  3839. }
  3840. }
  3841. var end = function(ws, fn) {
  3842. if (!ws) return fn()
  3843. if (ws._writableState && ws._writableState.finished) return fn()
  3844. if (ws._writableState) return ws.end(fn)
  3845. ws.end()
  3846. fn()
  3847. }
  3848. var toStreams2 = function(rs) {
  3849. return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
  3850. }
  3851. var Duplexify = function(writable, readable, opts) {
  3852. if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  3853. stream.Duplex.call(this, opts)
  3854. this._writable = null
  3855. this._readable = null
  3856. this._readable2 = null
  3857. this._forwardDestroy = !opts || opts.destroy !== false
  3858. this._forwardEnd = !opts || opts.end !== false
  3859. this._corked = 1 // start corked
  3860. this._ondrain = null
  3861. this._drained = false
  3862. this._forwarding = false
  3863. this._unwrite = null
  3864. this._unread = null
  3865. this._ended = false
  3866. this.destroyed = false
  3867. if (writable) this.setWritable(writable)
  3868. if (readable) this.setReadable(readable)
  3869. }
  3870. inherits(Duplexify, stream.Duplex)
  3871. Duplexify.obj = function(writable, readable, opts) {
  3872. if (!opts) opts = {}
  3873. opts.objectMode = true
  3874. opts.highWaterMark = 16
  3875. return new Duplexify(writable, readable, opts)
  3876. }
  3877. Duplexify.prototype.cork = function() {
  3878. if (++this._corked === 1) this.emit('cork')
  3879. }
  3880. Duplexify.prototype.uncork = function() {
  3881. if (this._corked && --this._corked === 0) this.emit('uncork')
  3882. }
  3883. Duplexify.prototype.setWritable = function(writable) {
  3884. if (this._unwrite) this._unwrite()
  3885. if (this.destroyed) {
  3886. if (writable && writable.destroy) writable.destroy()
  3887. return
  3888. }
  3889. if (writable === null || writable === false) {
  3890. this.end()
  3891. return
  3892. }
  3893. var self = this
  3894. var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
  3895. var ondrain = function() {
  3896. var ondrain = self._ondrain
  3897. self._ondrain = null
  3898. if (ondrain) ondrain()
  3899. }
  3900. var clear = function() {
  3901. self._writable.removeListener('drain', ondrain)
  3902. unend()
  3903. }
  3904. if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
  3905. this._writable = writable
  3906. this._writable.on('drain', ondrain)
  3907. this._unwrite = clear
  3908. this.uncork() // always uncork setWritable
  3909. }
  3910. Duplexify.prototype.setReadable = function(readable) {
  3911. if (this._unread) this._unread()
  3912. if (this.destroyed) {
  3913. if (readable && readable.destroy) readable.destroy()
  3914. return
  3915. }
  3916. if (readable === null || readable === false) {
  3917. this.push(null)
  3918. this.resume()
  3919. return
  3920. }
  3921. var self = this
  3922. var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
  3923. var onreadable = function() {
  3924. self._forward()
  3925. }
  3926. var onend = function() {
  3927. self.push(null)
  3928. }
  3929. var clear = function() {
  3930. self._readable2.removeListener('readable', onreadable)
  3931. self._readable2.removeListener('end', onend)
  3932. unend()
  3933. }
  3934. this._drained = true
  3935. this._readable = readable
  3936. this._readable2 = readable._readableState ? readable : toStreams2(readable)
  3937. this._readable2.on('readable', onreadable)
  3938. this._readable2.on('end', onend)
  3939. this._unread = clear
  3940. this._forward()
  3941. }
  3942. Duplexify.prototype._read = function() {
  3943. this._drained = true
  3944. this._forward()
  3945. }
  3946. Duplexify.prototype._forward = function() {
  3947. if (this._forwarding || !this._readable2 || !this._drained) return
  3948. this._forwarding = true
  3949. var data
  3950. while (this._drained && (data = shift(this._readable2)) !== null) {
  3951. if (this.destroyed) continue
  3952. this._drained = this.push(data)
  3953. }
  3954. this._forwarding = false
  3955. }
  3956. Duplexify.prototype.destroy = function(err) {
  3957. if (this.destroyed) return
  3958. this.destroyed = true
  3959. var self = this
  3960. process.nextTick(function() {
  3961. self._destroy(err)
  3962. })
  3963. }
  3964. Duplexify.prototype._destroy = function(err) {
  3965. if (err) {
  3966. var ondrain = this._ondrain
  3967. this._ondrain = null
  3968. if (ondrain) ondrain(err)
  3969. else this.emit('error', err)
  3970. }
  3971. if (this._forwardDestroy) {
  3972. if (this._readable && this._readable.destroy) this._readable.destroy()
  3973. if (this._writable && this._writable.destroy) this._writable.destroy()
  3974. }
  3975. this.emit('close')
  3976. }
  3977. Duplexify.prototype._write = function(data, enc, cb) {
  3978. if (this.destroyed) return cb()
  3979. if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
  3980. if (data === SIGNAL_FLUSH) return this._finish(cb)
  3981. if (!this._writable) return cb()
  3982. if (this._writable.write(data) === false) this._ondrain = cb
  3983. else cb()
  3984. }
  3985. Duplexify.prototype._finish = function(cb) {
  3986. var self = this
  3987. this.emit('preend')
  3988. onuncork(this, function() {
  3989. end(self._forwardEnd && self._writable, function() {
  3990. // haxx to not emit prefinish twice
  3991. if (self._writableState.prefinished === false) self._writableState.prefinished = true
  3992. self.emit('prefinish')
  3993. onuncork(self, cb)
  3994. })
  3995. })
  3996. }
  3997. Duplexify.prototype.end = function(data, enc, cb) {
  3998. if (typeof data === 'function') return this.end(null, null, data)
  3999. if (typeof enc === 'function') return this.end(data, null, enc)
  4000. this._ended = true
  4001. if (data) this.write(data)
  4002. if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  4003. return stream.Writable.prototype.end.call(this, cb)
  4004. }
  4005. module.exports = Duplexify
  4006. }).call(this,require('_process'),require("buffer").Buffer)
  4007. },{"_process":30,"buffer":13,"end-of-stream":16,"inherits":18,"readable-stream":45,"stream-shift":48}],16:[function(require,module,exports){
  4008. var once = require('once');
  4009. var noop = function() {};
  4010. var isRequest = function(stream) {
  4011. return stream.setHeader && typeof stream.abort === 'function';
  4012. };
  4013. var isChildProcess = function(stream) {
  4014. return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
  4015. };
  4016. var eos = function(stream, opts, callback) {
  4017. if (typeof opts === 'function') return eos(stream, null, opts);
  4018. if (!opts) opts = {};
  4019. callback = once(callback || noop);
  4020. var ws = stream._writableState;
  4021. var rs = stream._readableState;
  4022. var readable = opts.readable || (opts.readable !== false && stream.readable);
  4023. var writable = opts.writable || (opts.writable !== false && stream.writable);
  4024. var onlegacyfinish = function() {
  4025. if (!stream.writable) onfinish();
  4026. };
  4027. var onfinish = function() {
  4028. writable = false;
  4029. if (!readable) callback.call(stream);
  4030. };
  4031. var onend = function() {
  4032. readable = false;
  4033. if (!writable) callback.call(stream);
  4034. };
  4035. var onexit = function(exitCode) {
  4036. callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
  4037. };
  4038. var onerror = function(err) {
  4039. callback.call(stream, err);
  4040. };
  4041. var onclose = function() {
  4042. if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
  4043. if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
  4044. };
  4045. var onrequest = function() {
  4046. stream.req.on('finish', onfinish);
  4047. };
  4048. if (isRequest(stream)) {
  4049. stream.on('complete', onfinish);
  4050. stream.on('abort', onclose);
  4051. if (stream.req) onrequest();
  4052. else stream.on('request', onrequest);
  4053. } else if (writable && !ws) { // legacy streams
  4054. stream.on('end', onlegacyfinish);
  4055. stream.on('close', onlegacyfinish);
  4056. }
  4057. if (isChildProcess(stream)) stream.on('exit', onexit);
  4058. stream.on('end', onend);
  4059. stream.on('finish', onfinish);
  4060. if (opts.error !== false) stream.on('error', onerror);
  4061. stream.on('close', onclose);
  4062. return function() {
  4063. stream.removeListener('complete', onfinish);
  4064. stream.removeListener('abort', onclose);
  4065. stream.removeListener('request', onrequest);
  4066. if (stream.req) stream.req.removeListener('finish', onfinish);
  4067. stream.removeListener('end', onlegacyfinish);
  4068. stream.removeListener('close', onlegacyfinish);
  4069. stream.removeListener('finish', onfinish);
  4070. stream.removeListener('exit', onexit);
  4071. stream.removeListener('end', onend);
  4072. stream.removeListener('error', onerror);
  4073. stream.removeListener('close', onclose);
  4074. };
  4075. };
  4076. module.exports = eos;
  4077. },{"once":29}],17:[function(require,module,exports){
  4078. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  4079. var e, m
  4080. var eLen = nBytes * 8 - mLen - 1
  4081. var eMax = (1 << eLen) - 1
  4082. var eBias = eMax >> 1
  4083. var nBits = -7
  4084. var i = isLE ? (nBytes - 1) : 0
  4085. var d = isLE ? -1 : 1
  4086. var s = buffer[offset + i]
  4087. i += d
  4088. e = s & ((1 << (-nBits)) - 1)
  4089. s >>= (-nBits)
  4090. nBits += eLen
  4091. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  4092. m = e & ((1 << (-nBits)) - 1)
  4093. e >>= (-nBits)
  4094. nBits += mLen
  4095. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  4096. if (e === 0) {
  4097. e = 1 - eBias
  4098. } else if (e === eMax) {
  4099. return m ? NaN : ((s ? -1 : 1) * Infinity)
  4100. } else {
  4101. m = m + Math.pow(2, mLen)
  4102. e = e - eBias
  4103. }
  4104. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  4105. }
  4106. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  4107. var e, m, c
  4108. var eLen = nBytes * 8 - mLen - 1
  4109. var eMax = (1 << eLen) - 1
  4110. var eBias = eMax >> 1
  4111. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  4112. var i = isLE ? 0 : (nBytes - 1)
  4113. var d = isLE ? 1 : -1
  4114. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  4115. value = Math.abs(value)
  4116. if (isNaN(value) || value === Infinity) {
  4117. m = isNaN(value) ? 1 : 0
  4118. e = eMax
  4119. } else {
  4120. e = Math.floor(Math.log(value) / Math.LN2)
  4121. if (value * (c = Math.pow(2, -e)) < 1) {
  4122. e--
  4123. c *= 2
  4124. }
  4125. if (e + eBias >= 1) {
  4126. value += rt / c
  4127. } else {
  4128. value += rt * Math.pow(2, 1 - eBias)
  4129. }
  4130. if (value * c >= 2) {
  4131. e++
  4132. c /= 2
  4133. }
  4134. if (e + eBias >= eMax) {
  4135. m = 0
  4136. e = eMax
  4137. } else if (e + eBias >= 1) {
  4138. m = (value * c - 1) * Math.pow(2, mLen)
  4139. e = e + eBias
  4140. } else {
  4141. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  4142. e = 0
  4143. }
  4144. }
  4145. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  4146. e = (e << mLen) | m
  4147. eLen += mLen
  4148. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  4149. buffer[offset + i - d] |= s * 128
  4150. }
  4151. },{}],18:[function(require,module,exports){
  4152. if (typeof Object.create === 'function') {
  4153. // implementation from standard node.js 'util' module
  4154. module.exports = function inherits(ctor, superCtor) {
  4155. ctor.super_ = superCtor
  4156. ctor.prototype = Object.create(superCtor.prototype, {
  4157. constructor: {
  4158. value: ctor,
  4159. enumerable: false,
  4160. writable: true,
  4161. configurable: true
  4162. }
  4163. });
  4164. };
  4165. } else {
  4166. // old school shim for old browsers
  4167. module.exports = function inherits(ctor, superCtor) {
  4168. ctor.super_ = superCtor
  4169. var TempCtor = function () {}
  4170. TempCtor.prototype = superCtor.prototype
  4171. ctor.prototype = new TempCtor()
  4172. ctor.prototype.constructor = ctor
  4173. }
  4174. }
  4175. },{}],19:[function(require,module,exports){
  4176. /*!
  4177. * Determine if an object is a Buffer
  4178. *
  4179. * @author Feross Aboukhadijeh <https://feross.org>
  4180. * @license MIT
  4181. */
  4182. // The _isBuffer check is for Safari 5-7 support, because it's missing
  4183. // Object.prototype.constructor. Remove this eventually
  4184. module.exports = function (obj) {
  4185. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  4186. }
  4187. function isBuffer (obj) {
  4188. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  4189. }
  4190. // For Node v0.10 support. Remove this eventually.
  4191. function isSlowBuffer (obj) {
  4192. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  4193. }
  4194. },{}],20:[function(require,module,exports){
  4195. var toString = {}.toString;
  4196. module.exports = Array.isArray || function (arr) {
  4197. return toString.call(arr) == '[object Array]';
  4198. };
  4199. },{}],21:[function(require,module,exports){
  4200. 'use strict'
  4201. var Buffer = require('safe-buffer').Buffer
  4202. /* Protocol - protocol constants */
  4203. var protocol = module.exports
  4204. /* Command code => mnemonic */
  4205. protocol.types = {
  4206. 0: 'reserved',
  4207. 1: 'connect',
  4208. 2: 'connack',
  4209. 3: 'publish',
  4210. 4: 'puback',
  4211. 5: 'pubrec',
  4212. 6: 'pubrel',
  4213. 7: 'pubcomp',
  4214. 8: 'subscribe',
  4215. 9: 'suback',
  4216. 10: 'unsubscribe',
  4217. 11: 'unsuback',
  4218. 12: 'pingreq',
  4219. 13: 'pingresp',
  4220. 14: 'disconnect',
  4221. 15: 'reserved'
  4222. }
  4223. /* Mnemonic => Command code */
  4224. protocol.codes = {}
  4225. for (var k in protocol.types) {
  4226. var v = protocol.types[k]
  4227. protocol.codes[v] = k
  4228. }
  4229. /* Header */
  4230. protocol.CMD_SHIFT = 4
  4231. protocol.CMD_MASK = 0xF0
  4232. protocol.DUP_MASK = 0x08
  4233. protocol.QOS_MASK = 0x03
  4234. protocol.QOS_SHIFT = 1
  4235. protocol.RETAIN_MASK = 0x01
  4236. /* Length */
  4237. protocol.LENGTH_MASK = 0x7F
  4238. protocol.LENGTH_FIN_MASK = 0x80
  4239. /* Connack */
  4240. protocol.SESSIONPRESENT_MASK = 0x01
  4241. protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])
  4242. protocol.CONNACK_HEADER = Buffer.from([protocol.codes['connack'] << protocol.CMD_SHIFT])
  4243. /* Connect */
  4244. protocol.USERNAME_MASK = 0x80
  4245. protocol.PASSWORD_MASK = 0x40
  4246. protocol.WILL_RETAIN_MASK = 0x20
  4247. protocol.WILL_QOS_MASK = 0x18
  4248. protocol.WILL_QOS_SHIFT = 3
  4249. protocol.WILL_FLAG_MASK = 0x04
  4250. protocol.CLEAN_SESSION_MASK = 0x02
  4251. protocol.CONNECT_HEADER = Buffer.from([protocol.codes['connect'] << protocol.CMD_SHIFT])
  4252. function genHeader (type) {
  4253. return [0, 1, 2].map(function (qos) {
  4254. return [0, 1].map(function (dup) {
  4255. return [0, 1].map(function (retain) {
  4256. var buf = new Buffer(1)
  4257. buf.writeUInt8(
  4258. protocol.codes[type] << protocol.CMD_SHIFT |
  4259. (dup ? protocol.DUP_MASK : 0) |
  4260. qos << protocol.QOS_SHIFT | retain, 0, true)
  4261. return buf
  4262. })
  4263. })
  4264. })
  4265. }
  4266. /* Publish */
  4267. protocol.PUBLISH_HEADER = genHeader('publish')
  4268. /* Subscribe */
  4269. protocol.SUBSCRIBE_HEADER = genHeader('subscribe')
  4270. /* Unsubscribe */
  4271. protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')
  4272. /* Confirmations */
  4273. protocol.ACKS = {
  4274. unsuback: genHeader('unsuback'),
  4275. puback: genHeader('puback'),
  4276. pubcomp: genHeader('pubcomp'),
  4277. pubrel: genHeader('pubrel'),
  4278. pubrec: genHeader('pubrec')
  4279. }
  4280. protocol.SUBACK_HEADER = Buffer.from([protocol.codes['suback'] << protocol.CMD_SHIFT])
  4281. /* Protocol versions */
  4282. protocol.VERSION3 = Buffer.from([3])
  4283. protocol.VERSION4 = Buffer.from([4])
  4284. /* QoS */
  4285. protocol.QOS = [0, 1, 2].map(function (qos) {
  4286. return Buffer.from([qos])
  4287. })
  4288. /* Empty packets */
  4289. protocol.EMPTY = {
  4290. pingreq: Buffer.from([protocol.codes['pingreq'] << 4, 0]),
  4291. pingresp: Buffer.from([protocol.codes['pingresp'] << 4, 0]),
  4292. disconnect: Buffer.from([protocol.codes['disconnect'] << 4, 0])
  4293. }
  4294. },{"safe-buffer":47}],22:[function(require,module,exports){
  4295. 'use strict'
  4296. var Buffer = require('safe-buffer').Buffer
  4297. var writeToStream = require('./writeToStream')
  4298. var EE = require('events').EventEmitter
  4299. var inherits = require('inherits')
  4300. function generate (packet) {
  4301. var stream = new Accumulator()
  4302. writeToStream(packet, stream)
  4303. return stream.concat()
  4304. }
  4305. function Accumulator () {
  4306. this._array = new Array(20)
  4307. this._i = 0
  4308. }
  4309. inherits(Accumulator, EE)
  4310. Accumulator.prototype.write = function (chunk) {
  4311. this._array[this._i++] = chunk
  4312. return true
  4313. }
  4314. Accumulator.prototype.concat = function () {
  4315. var length = 0
  4316. var lengths = new Array(this._array.length)
  4317. var list = this._array
  4318. var pos = 0
  4319. var i
  4320. var result
  4321. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  4322. if (typeof list[i] !== 'string') lengths[i] = list[i].length
  4323. else lengths[i] = Buffer.byteLength(list[i])
  4324. length += lengths[i]
  4325. }
  4326. result = Buffer.allocUnsafe(length)
  4327. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  4328. if (typeof list[i] !== 'string') {
  4329. list[i].copy(result, pos)
  4330. pos += lengths[i]
  4331. } else {
  4332. result.write(list[i], pos)
  4333. pos += lengths[i]
  4334. }
  4335. }
  4336. return result
  4337. }
  4338. module.exports = generate
  4339. },{"./writeToStream":28,"events":12,"inherits":18,"safe-buffer":47}],23:[function(require,module,exports){
  4340. 'use strict'
  4341. exports.parser = require('./parser')
  4342. exports.generate = require('./generate')
  4343. exports.writeToStream = require('./writeToStream')
  4344. },{"./generate":22,"./parser":27,"./writeToStream":28}],24:[function(require,module,exports){
  4345. (function (process){
  4346. 'use strict';
  4347. if (!process.version ||
  4348. process.version.indexOf('v0.') === 0 ||
  4349. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  4350. module.exports = { nextTick: nextTick };
  4351. } else {
  4352. module.exports = process
  4353. }
  4354. function nextTick(fn, arg1, arg2, arg3) {
  4355. if (typeof fn !== 'function') {
  4356. throw new TypeError('"callback" argument must be a function');
  4357. }
  4358. var len = arguments.length;
  4359. var args, i;
  4360. switch (len) {
  4361. case 0:
  4362. case 1:
  4363. return process.nextTick(fn);
  4364. case 2:
  4365. return process.nextTick(function afterTickOne() {
  4366. fn.call(null, arg1);
  4367. });
  4368. case 3:
  4369. return process.nextTick(function afterTickTwo() {
  4370. fn.call(null, arg1, arg2);
  4371. });
  4372. case 4:
  4373. return process.nextTick(function afterTickThree() {
  4374. fn.call(null, arg1, arg2, arg3);
  4375. });
  4376. default:
  4377. args = new Array(len - 1);
  4378. i = 0;
  4379. while (i < args.length) {
  4380. args[i++] = arguments[i];
  4381. }
  4382. return process.nextTick(function afterTick() {
  4383. fn.apply(null, args);
  4384. });
  4385. }
  4386. }
  4387. }).call(this,require('_process'))
  4388. },{"_process":30}],25:[function(require,module,exports){
  4389. 'use strict'
  4390. var Buffer = require('safe-buffer').Buffer
  4391. var max = 65536
  4392. var cache = {}
  4393. function generateBuffer (i) {
  4394. var buffer = Buffer.allocUnsafe(2)
  4395. buffer.writeUInt8(i >> 8, 0)
  4396. buffer.writeUInt8(i & 0x00FF, 0 + 1)
  4397. return buffer
  4398. }
  4399. function generateCache () {
  4400. for (var i = 0; i < max; i++) {
  4401. cache[i] = generateBuffer(i)
  4402. }
  4403. }
  4404. module.exports = {
  4405. cache: cache,
  4406. generateCache: generateCache,
  4407. generateNumber: generateBuffer
  4408. }
  4409. },{"safe-buffer":47}],26:[function(require,module,exports){
  4410. function Packet () {
  4411. this.cmd = null
  4412. this.retain = false
  4413. this.qos = 0
  4414. this.dup = false
  4415. this.length = -1
  4416. this.topic = null
  4417. this.payload = null
  4418. }
  4419. module.exports = Packet
  4420. },{}],27:[function(require,module,exports){
  4421. 'use strict'
  4422. var bl = require('bl')
  4423. var inherits = require('inherits')
  4424. var EE = require('events').EventEmitter
  4425. var Packet = require('./packet')
  4426. var constants = require('./constants')
  4427. function Parser () {
  4428. if (!(this instanceof Parser)) return new Parser()
  4429. this._states = [
  4430. '_parseHeader',
  4431. '_parseLength',
  4432. '_parsePayload',
  4433. '_newPacket'
  4434. ]
  4435. this._resetState()
  4436. }
  4437. inherits(Parser, EE)
  4438. Parser.prototype._resetState = function () {
  4439. this.packet = new Packet()
  4440. this.error = null
  4441. this._list = bl()
  4442. this._stateCounter = 0
  4443. }
  4444. Parser.prototype.parse = function (buf) {
  4445. if (this.error) this._resetState()
  4446. this._list.append(buf)
  4447. while ((this.packet.length !== -1 || this._list.length > 0) &&
  4448. this[this._states[this._stateCounter]]() &&
  4449. !this.error) {
  4450. this._stateCounter++
  4451. if (this._stateCounter >= this._states.length) this._stateCounter = 0
  4452. }
  4453. return this._list.length
  4454. }
  4455. Parser.prototype._parseHeader = function () {
  4456. // There is at least one byte in the buffer
  4457. var zero = this._list.readUInt8(0)
  4458. this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]
  4459. this.packet.retain = (zero & constants.RETAIN_MASK) !== 0
  4460. this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK
  4461. this.packet.dup = (zero & constants.DUP_MASK) !== 0
  4462. this._list.consume(1)
  4463. return true
  4464. }
  4465. Parser.prototype._parseLength = function () {
  4466. // There is at least one byte in the list
  4467. var bytes = 0
  4468. var mul = 1
  4469. var length = 0
  4470. var result = true
  4471. var current
  4472. while (bytes < 5) {
  4473. current = this._list.readUInt8(bytes++)
  4474. length += mul * (current & constants.LENGTH_MASK)
  4475. mul *= 0x80
  4476. if ((current & constants.LENGTH_FIN_MASK) === 0) break
  4477. if (this._list.length <= bytes) {
  4478. result = false
  4479. break
  4480. }
  4481. }
  4482. if (result) {
  4483. this.packet.length = length
  4484. this._list.consume(bytes)
  4485. }
  4486. return result
  4487. }
  4488. Parser.prototype._parsePayload = function () {
  4489. var result = false
  4490. // Do we have a payload? Do we have enough data to complete the payload?
  4491. // PINGs have no payload
  4492. if (this.packet.length === 0 || this._list.length >= this.packet.length) {
  4493. this._pos = 0
  4494. switch (this.packet.cmd) {
  4495. case 'connect':
  4496. this._parseConnect()
  4497. break
  4498. case 'connack':
  4499. this._parseConnack()
  4500. break
  4501. case 'publish':
  4502. this._parsePublish()
  4503. break
  4504. case 'puback':
  4505. case 'pubrec':
  4506. case 'pubrel':
  4507. case 'pubcomp':
  4508. this._parseMessageId()
  4509. break
  4510. case 'subscribe':
  4511. this._parseSubscribe()
  4512. break
  4513. case 'suback':
  4514. this._parseSuback()
  4515. break
  4516. case 'unsubscribe':
  4517. this._parseUnsubscribe()
  4518. break
  4519. case 'unsuback':
  4520. this._parseUnsuback()
  4521. break
  4522. case 'pingreq':
  4523. case 'pingresp':
  4524. case 'disconnect':
  4525. // These are empty, nothing to do
  4526. break
  4527. default:
  4528. this._emitError(new Error('Not supported'))
  4529. }
  4530. result = true
  4531. }
  4532. return result
  4533. }
  4534. Parser.prototype._parseConnect = function () {
  4535. var protocolId // Protocol ID
  4536. var clientId // Client ID
  4537. var topic // Will topic
  4538. var payload // Will payload
  4539. var password // Password
  4540. var username // Username
  4541. var flags = {}
  4542. var packet = this.packet
  4543. // Parse protocolId
  4544. protocolId = this._parseString()
  4545. if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId'))
  4546. if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {
  4547. return this._emitError(new Error('Invalid protocolId'))
  4548. }
  4549. packet.protocolId = protocolId
  4550. // Parse constants version number
  4551. if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short'))
  4552. packet.protocolVersion = this._list.readUInt8(this._pos)
  4553. if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4) {
  4554. return this._emitError(new Error('Invalid protocol version'))
  4555. }
  4556. this._pos++
  4557. if (this._pos >= this._list.length) {
  4558. return this._emitError(new Error('Packet too short'))
  4559. }
  4560. // Parse connect flags
  4561. flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)
  4562. flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)
  4563. flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)
  4564. if (flags.will) {
  4565. packet.will = {}
  4566. packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0
  4567. packet.will.qos = (this._list.readUInt8(this._pos) &
  4568. constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT
  4569. }
  4570. packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0
  4571. this._pos++
  4572. // Parse keepalive
  4573. packet.keepalive = this._parseNum()
  4574. if (packet.keepalive === -1) return this._emitError(new Error('Packet too short'))
  4575. // Parse clientId
  4576. clientId = this._parseString()
  4577. if (clientId === null) return this._emitError(new Error('Packet too short'))
  4578. packet.clientId = clientId
  4579. if (flags.will) {
  4580. // Parse will topic
  4581. topic = this._parseString()
  4582. if (topic === null) return this._emitError(new Error('Cannot parse will topic'))
  4583. packet.will.topic = topic
  4584. // Parse will payload
  4585. payload = this._parseBuffer()
  4586. if (payload === null) return this._emitError(new Error('Cannot parse will payload'))
  4587. packet.will.payload = payload
  4588. }
  4589. // Parse username
  4590. if (flags.username) {
  4591. username = this._parseString()
  4592. if (username === null) return this._emitError(new Error('Cannot parse username'))
  4593. packet.username = username
  4594. }
  4595. // Parse password
  4596. if (flags.password) {
  4597. password = this._parseBuffer()
  4598. if (password === null) return this._emitError(new Error('Cannot parse password'))
  4599. packet.password = password
  4600. }
  4601. return packet
  4602. }
  4603. Parser.prototype._parseConnack = function () {
  4604. var packet = this.packet
  4605. if (this._list.length < 2) return null
  4606. packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)
  4607. packet.returnCode = this._list.readUInt8(this._pos)
  4608. if (packet.returnCode === -1) return this._emitError(new Error('Cannot parse return code'))
  4609. }
  4610. Parser.prototype._parsePublish = function () {
  4611. var packet = this.packet
  4612. packet.topic = this._parseString()
  4613. if (packet.topic === null) return this._emitError(new Error('Cannot parse topic'))
  4614. // Parse messageId
  4615. if (packet.qos > 0) if (!this._parseMessageId()) { return }
  4616. packet.payload = this._list.slice(this._pos, packet.length)
  4617. }
  4618. Parser.prototype._parseSubscribe = function () {
  4619. var packet = this.packet
  4620. var topic
  4621. var qos
  4622. if (packet.qos !== 1) {
  4623. return this._emitError(new Error('Wrong subscribe header'))
  4624. }
  4625. packet.subscriptions = []
  4626. if (!this._parseMessageId()) { return }
  4627. while (this._pos < packet.length) {
  4628. // Parse topic
  4629. topic = this._parseString()
  4630. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  4631. qos = this._list.readUInt8(this._pos++)
  4632. // Push pair to subscriptions
  4633. packet.subscriptions.push({ topic: topic, qos: qos })
  4634. }
  4635. }
  4636. Parser.prototype._parseSuback = function () {
  4637. this.packet.granted = []
  4638. if (!this._parseMessageId()) { return }
  4639. // Parse granted QoSes
  4640. while (this._pos < this.packet.length) {
  4641. this.packet.granted.push(this._list.readUInt8(this._pos++))
  4642. }
  4643. }
  4644. Parser.prototype._parseUnsubscribe = function () {
  4645. var packet = this.packet
  4646. packet.unsubscriptions = []
  4647. // Parse messageId
  4648. if (!this._parseMessageId()) { return }
  4649. while (this._pos < packet.length) {
  4650. var topic
  4651. // Parse topic
  4652. topic = this._parseString()
  4653. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  4654. // Push topic to unsubscriptions
  4655. packet.unsubscriptions.push(topic)
  4656. }
  4657. }
  4658. Parser.prototype._parseUnsuback = function () {
  4659. if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId'))
  4660. }
  4661. Parser.prototype._parseMessageId = function () {
  4662. var packet = this.packet
  4663. packet.messageId = this._parseNum()
  4664. if (packet.messageId === null) {
  4665. this._emitError(new Error('Cannot parse messageId'))
  4666. return false
  4667. }
  4668. return true
  4669. }
  4670. Parser.prototype._parseString = function (maybeBuffer) {
  4671. var length = this._parseNum()
  4672. var result
  4673. var end = length + this._pos
  4674. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  4675. result = this._list.toString('utf8', this._pos, end)
  4676. this._pos += length
  4677. return result
  4678. }
  4679. Parser.prototype._parseBuffer = function () {
  4680. var length = this._parseNum()
  4681. var result
  4682. var end = length + this._pos
  4683. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  4684. result = this._list.slice(this._pos, end)
  4685. this._pos += length
  4686. return result
  4687. }
  4688. Parser.prototype._parseNum = function () {
  4689. if (this._list.length - this._pos < 2) return -1
  4690. var result = this._list.readUInt16BE(this._pos)
  4691. this._pos += 2
  4692. return result
  4693. }
  4694. Parser.prototype._newPacket = function () {
  4695. if (this.packet) {
  4696. this._list.consume(this.packet.length)
  4697. this.emit('packet', this.packet)
  4698. }
  4699. this.packet = new Packet()
  4700. return true
  4701. }
  4702. Parser.prototype._emitError = function (err) {
  4703. this.error = err
  4704. this.emit('error', err)
  4705. }
  4706. module.exports = Parser
  4707. },{"./constants":21,"./packet":26,"bl":10,"events":12,"inherits":18}],28:[function(require,module,exports){
  4708. 'use strict'
  4709. var protocol = require('./constants')
  4710. var Buffer = require('safe-buffer').Buffer
  4711. var empty = Buffer.allocUnsafe(0)
  4712. var zeroBuf = Buffer.from([0])
  4713. var numbers = require('./numbers')
  4714. var nextTick = require('process-nextick-args').nextTick
  4715. var numCache = numbers.cache
  4716. var generateNumber = numbers.generateNumber
  4717. var generateCache = numbers.generateCache
  4718. var writeNumber = writeNumberCached
  4719. var toGenerate = true
  4720. function generate (packet, stream) {
  4721. if (stream.cork) {
  4722. stream.cork()
  4723. nextTick(uncork, stream)
  4724. }
  4725. if (toGenerate) {
  4726. toGenerate = false
  4727. generateCache()
  4728. }
  4729. switch (packet.cmd) {
  4730. case 'connect':
  4731. return connect(packet, stream)
  4732. case 'connack':
  4733. return connack(packet, stream)
  4734. case 'publish':
  4735. return publish(packet, stream)
  4736. case 'puback':
  4737. case 'pubrec':
  4738. case 'pubrel':
  4739. case 'pubcomp':
  4740. case 'unsuback':
  4741. return confirmation(packet, stream)
  4742. case 'subscribe':
  4743. return subscribe(packet, stream)
  4744. case 'suback':
  4745. return suback(packet, stream)
  4746. case 'unsubscribe':
  4747. return unsubscribe(packet, stream)
  4748. case 'pingreq':
  4749. case 'pingresp':
  4750. case 'disconnect':
  4751. return emptyPacket(packet, stream)
  4752. default:
  4753. stream.emit('error', new Error('Unknown command'))
  4754. return false
  4755. }
  4756. }
  4757. /**
  4758. * Controls numbers cache.
  4759. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache
  4760. */
  4761. Object.defineProperty(generate, 'cacheNumbers', {
  4762. get: function () {
  4763. return writeNumber === writeNumberCached
  4764. },
  4765. set: function (value) {
  4766. if (value) {
  4767. if (!numCache || Object.keys(numCache).length === 0) toGenerate = true
  4768. writeNumber = writeNumberCached
  4769. } else {
  4770. toGenerate = false
  4771. writeNumber = writeNumberGenerated
  4772. }
  4773. }
  4774. })
  4775. function uncork (stream) {
  4776. stream.uncork()
  4777. }
  4778. function connect (opts, stream) {
  4779. var settings = opts || {}
  4780. var protocolId = settings.protocolId || 'MQTT'
  4781. var protocolVersion = settings.protocolVersion || 4
  4782. var will = settings.will
  4783. var clean = settings.clean
  4784. var keepalive = settings.keepalive || 0
  4785. var clientId = settings.clientId || ''
  4786. var username = settings.username
  4787. var password = settings.password
  4788. if (clean === undefined) clean = true
  4789. var length = 0
  4790. // Must be a string and non-falsy
  4791. if (!protocolId ||
  4792. (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {
  4793. stream.emit('error', new Error('Invalid protocolId'))
  4794. return false
  4795. } else length += protocolId.length + 2
  4796. // Must be 3 or 4
  4797. if (protocolVersion !== 3 && protocolVersion !== 4) {
  4798. stream.emit('error', new Error('Invalid protocol version'))
  4799. return false
  4800. } else length += 1
  4801. // ClientId might be omitted in 3.1.1, but only if cleanSession is set to 1
  4802. if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&
  4803. (clientId || protocolVersion === 4) && (clientId || clean)) {
  4804. length += clientId.length + 2
  4805. } else {
  4806. if (protocolVersion < 4) {
  4807. stream.emit('error', new Error('clientId must be supplied before 3.1.1'))
  4808. return false
  4809. }
  4810. if ((clean * 1) === 0) {
  4811. stream.emit('error', new Error('clientId must be given if cleanSession set to 0'))
  4812. return false
  4813. }
  4814. }
  4815. // Must be a two byte number
  4816. if (typeof keepalive !== 'number' ||
  4817. keepalive < 0 ||
  4818. keepalive > 65535 ||
  4819. keepalive % 1 !== 0) {
  4820. stream.emit('error', new Error('Invalid keepalive'))
  4821. return false
  4822. } else length += 2
  4823. // Connect flags
  4824. length += 1
  4825. // If will exists...
  4826. if (will) {
  4827. // It must be an object
  4828. if (typeof will !== 'object') {
  4829. stream.emit('error', new Error('Invalid will'))
  4830. return false
  4831. }
  4832. // It must have topic typeof string
  4833. if (!will.topic || typeof will.topic !== 'string') {
  4834. stream.emit('error', new Error('Invalid will topic'))
  4835. return false
  4836. } else {
  4837. length += Buffer.byteLength(will.topic) + 2
  4838. }
  4839. // Payload
  4840. if (will.payload && will.payload) {
  4841. if (will.payload.length >= 0) {
  4842. if (typeof will.payload === 'string') {
  4843. length += Buffer.byteLength(will.payload) + 2
  4844. } else {
  4845. length += will.payload.length + 2
  4846. }
  4847. } else {
  4848. stream.emit('error', new Error('Invalid will payload'))
  4849. return false
  4850. }
  4851. } else {
  4852. length += 2
  4853. }
  4854. }
  4855. // Username
  4856. var providedUsername = false
  4857. if (username != null) {
  4858. if (isStringOrBuffer(username)) {
  4859. providedUsername = true
  4860. length += Buffer.byteLength(username) + 2
  4861. } else {
  4862. stream.emit('error', new Error('Invalid username'))
  4863. return false
  4864. }
  4865. }
  4866. // Password
  4867. if (password != null) {
  4868. if (!providedUsername) {
  4869. stream.emit('error', new Error('Username is required to use password'))
  4870. return false
  4871. }
  4872. if (isStringOrBuffer(password)) {
  4873. length += byteLength(password) + 2
  4874. } else {
  4875. stream.emit('error', new Error('Invalid password'))
  4876. return false
  4877. }
  4878. }
  4879. // Generate header
  4880. stream.write(protocol.CONNECT_HEADER)
  4881. // Generate length
  4882. writeLength(stream, length)
  4883. // Generate protocol ID
  4884. writeStringOrBuffer(stream, protocolId)
  4885. stream.write(
  4886. protocolVersion === 4 ? protocol.VERSION4 : protocol.VERSION3
  4887. )
  4888. // Connect flags
  4889. var flags = 0
  4890. flags |= (username != null) ? protocol.USERNAME_MASK : 0
  4891. flags |= (password != null) ? protocol.PASSWORD_MASK : 0
  4892. flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0
  4893. flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0
  4894. flags |= will ? protocol.WILL_FLAG_MASK : 0
  4895. flags |= clean ? protocol.CLEAN_SESSION_MASK : 0
  4896. stream.write(Buffer.from([flags]))
  4897. // Keepalive
  4898. writeNumber(stream, keepalive)
  4899. // Client ID
  4900. writeStringOrBuffer(stream, clientId)
  4901. // Will
  4902. if (will) {
  4903. writeString(stream, will.topic)
  4904. writeStringOrBuffer(stream, will.payload)
  4905. }
  4906. // Username and password
  4907. if (username != null) {
  4908. writeStringOrBuffer(stream, username)
  4909. }
  4910. if (password != null) {
  4911. writeStringOrBuffer(stream, password)
  4912. }
  4913. // This is a small packet that happens only once on a stream
  4914. // We assume the stream is always free to receive more data after this
  4915. return true
  4916. }
  4917. function connack (opts, stream) {
  4918. var settings = opts || {}
  4919. var rc = settings.returnCode
  4920. // Check return code
  4921. if (typeof rc !== 'number') {
  4922. stream.emit('error', new Error('Invalid return code'))
  4923. return false
  4924. }
  4925. stream.write(protocol.CONNACK_HEADER)
  4926. writeLength(stream, 2)
  4927. stream.write(opts.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)
  4928. return stream.write(Buffer.from([rc]))
  4929. }
  4930. function publish (opts, stream) {
  4931. var settings = opts || {}
  4932. var qos = settings.qos || 0
  4933. var retain = settings.retain ? protocol.RETAIN_MASK : 0
  4934. var topic = settings.topic
  4935. var payload = settings.payload || empty
  4936. var id = settings.messageId
  4937. var length = 0
  4938. // Topic must be a non-empty string or Buffer
  4939. if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2
  4940. else if (Buffer.isBuffer(topic)) length += topic.length + 2
  4941. else {
  4942. stream.emit('error', new Error('Invalid topic'))
  4943. return false
  4944. }
  4945. // Get the payload length
  4946. if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)
  4947. else length += payload.length
  4948. // Message ID must a number if qos > 0
  4949. if (qos && typeof id !== 'number') {
  4950. stream.emit('error', new Error('Invalid messageId'))
  4951. return false
  4952. } else if (qos) length += 2
  4953. // Header
  4954. stream.write(protocol.PUBLISH_HEADER[qos][opts.dup ? 1 : 0][retain ? 1 : 0])
  4955. // Remaining length
  4956. writeLength(stream, length)
  4957. // Topic
  4958. writeNumber(stream, byteLength(topic))
  4959. stream.write(topic)
  4960. // Message ID
  4961. if (qos > 0) writeNumber(stream, id)
  4962. // Payload
  4963. return stream.write(payload)
  4964. }
  4965. /* Puback, pubrec, pubrel and pubcomp */
  4966. function confirmation (opts, stream) {
  4967. var settings = opts || {}
  4968. var type = settings.cmd || 'puback'
  4969. var id = settings.messageId
  4970. var dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0
  4971. var qos = 0
  4972. if (type === 'pubrel') qos = 1
  4973. // Check message ID
  4974. if (typeof id !== 'number') {
  4975. stream.emit('error', new Error('Invalid messageId'))
  4976. return false
  4977. }
  4978. // Header
  4979. stream.write(protocol.ACKS[type][qos][dup][0])
  4980. // Length
  4981. writeLength(stream, 2)
  4982. // Message ID
  4983. return writeNumber(stream, id)
  4984. }
  4985. function subscribe (opts, stream) {
  4986. var settings = opts || {}
  4987. var dup = settings.dup ? protocol.DUP_MASK : 0
  4988. var id = settings.messageId
  4989. var subs = settings.subscriptions
  4990. var length = 0
  4991. // Check message ID
  4992. if (typeof id !== 'number') {
  4993. stream.emit('error', new Error('Invalid messageId'))
  4994. return false
  4995. } else length += 2
  4996. // Check subscriptions
  4997. if (typeof subs === 'object' && subs.length) {
  4998. for (var i = 0; i < subs.length; i += 1) {
  4999. var itopic = subs[i].topic
  5000. var iqos = subs[i].qos
  5001. if (typeof itopic !== 'string') {
  5002. stream.emit('error', new Error('Invalid subscriptions - invalid topic'))
  5003. return false
  5004. }
  5005. if (typeof iqos !== 'number') {
  5006. stream.emit('error', new Error('Invalid subscriptions - invalid qos'))
  5007. return false
  5008. }
  5009. length += Buffer.byteLength(itopic) + 2 + 1
  5010. }
  5011. } else {
  5012. stream.emit('error', new Error('Invalid subscriptions'))
  5013. return false
  5014. }
  5015. // Generate header
  5016. stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  5017. // Generate length
  5018. writeLength(stream, length)
  5019. // Generate message ID
  5020. writeNumber(stream, id)
  5021. var result = true
  5022. // Generate subs
  5023. for (var j = 0; j < subs.length; j++) {
  5024. var sub = subs[j]
  5025. var jtopic = sub.topic
  5026. var jqos = sub.qos
  5027. // Write topic string
  5028. writeString(stream, jtopic)
  5029. // Write qos
  5030. result = stream.write(protocol.QOS[jqos])
  5031. }
  5032. return result
  5033. }
  5034. function suback (opts, stream) {
  5035. var settings = opts || {}
  5036. var id = settings.messageId
  5037. var granted = settings.granted
  5038. var length = 0
  5039. // Check message ID
  5040. if (typeof id !== 'number') {
  5041. stream.emit('error', new Error('Invalid messageId'))
  5042. return false
  5043. } else length += 2
  5044. // Check granted qos vector
  5045. if (typeof granted === 'object' && granted.length) {
  5046. for (var i = 0; i < granted.length; i += 1) {
  5047. if (typeof granted[i] !== 'number') {
  5048. stream.emit('error', new Error('Invalid qos vector'))
  5049. return false
  5050. }
  5051. length += 1
  5052. }
  5053. } else {
  5054. stream.emit('error', new Error('Invalid qos vector'))
  5055. return false
  5056. }
  5057. // header
  5058. stream.write(protocol.SUBACK_HEADER)
  5059. // Length
  5060. writeLength(stream, length)
  5061. // Message ID
  5062. writeNumber(stream, id)
  5063. return stream.write(Buffer.from(granted))
  5064. }
  5065. function unsubscribe (opts, stream) {
  5066. var settings = opts || {}
  5067. var id = settings.messageId
  5068. var dup = settings.dup ? protocol.DUP_MASK : 0
  5069. var unsubs = settings.unsubscriptions
  5070. var length = 0
  5071. // Check message ID
  5072. if (typeof id !== 'number') {
  5073. stream.emit('error', new Error('Invalid messageId'))
  5074. return false
  5075. } else {
  5076. length += 2
  5077. }
  5078. // Check unsubs
  5079. if (typeof unsubs === 'object' && unsubs.length) {
  5080. for (var i = 0; i < unsubs.length; i += 1) {
  5081. if (typeof unsubs[i] !== 'string') {
  5082. stream.emit('error', new Error('Invalid unsubscriptions'))
  5083. return false
  5084. }
  5085. length += Buffer.byteLength(unsubs[i]) + 2
  5086. }
  5087. } else {
  5088. stream.emit('error', new Error('Invalid unsubscriptions'))
  5089. return false
  5090. }
  5091. // Header
  5092. stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  5093. // Length
  5094. writeLength(stream, length)
  5095. // Message ID
  5096. writeNumber(stream, id)
  5097. // Unsubs
  5098. var result = true
  5099. for (var j = 0; j < unsubs.length; j++) {
  5100. result = writeString(stream, unsubs[j])
  5101. }
  5102. return result
  5103. }
  5104. function emptyPacket (opts, stream) {
  5105. return stream.write(protocol.EMPTY[opts.cmd])
  5106. }
  5107. /**
  5108. * calcLengthLength - calculate the length of the remaining
  5109. * length field
  5110. *
  5111. * @api private
  5112. */
  5113. function calcLengthLength (length) {
  5114. if (length >= 0 && length < 128) return 1
  5115. else if (length >= 128 && length < 16384) return 2
  5116. else if (length >= 16384 && length < 2097152) return 3
  5117. else if (length >= 2097152 && length < 268435456) return 4
  5118. else return 0
  5119. }
  5120. function genBufLength (length) {
  5121. var digit = 0
  5122. var pos = 0
  5123. var buffer = Buffer.allocUnsafe(calcLengthLength(length))
  5124. do {
  5125. digit = length % 128 | 0
  5126. length = length / 128 | 0
  5127. if (length > 0) digit = digit | 0x80
  5128. buffer.writeUInt8(digit, pos++)
  5129. } while (length > 0)
  5130. return buffer
  5131. }
  5132. /**
  5133. * writeLength - write an MQTT style length field to the buffer
  5134. *
  5135. * @param <Buffer> buffer - destination
  5136. * @param <Number> pos - offset
  5137. * @param <Number> length - length (>0)
  5138. * @returns <Number> number of bytes written
  5139. *
  5140. * @api private
  5141. */
  5142. var lengthCache = {}
  5143. function writeLength (stream, length) {
  5144. var buffer = lengthCache[length]
  5145. if (!buffer) {
  5146. buffer = genBufLength(length)
  5147. if (length < 16384) lengthCache[length] = buffer
  5148. }
  5149. stream.write(buffer)
  5150. }
  5151. /**
  5152. * writeString - write a utf8 string to the buffer
  5153. *
  5154. * @param <Buffer> buffer - destination
  5155. * @param <Number> pos - offset
  5156. * @param <String> string - string to write
  5157. * @return <Number> number of bytes written
  5158. *
  5159. * @api private
  5160. */
  5161. function writeString (stream, string) {
  5162. var strlen = Buffer.byteLength(string)
  5163. writeNumber(stream, strlen)
  5164. stream.write(string, 'utf8')
  5165. }
  5166. /**
  5167. * writeNumber - write a two byte number to the buffer
  5168. *
  5169. * @param <Buffer> buffer - destination
  5170. * @param <Number> pos - offset
  5171. * @param <String> number - number to write
  5172. * @return <Number> number of bytes written
  5173. *
  5174. * @api private
  5175. */
  5176. function writeNumberCached (stream, number) {
  5177. return stream.write(numCache[number])
  5178. }
  5179. function writeNumberGenerated (stream, number) {
  5180. return stream.write(generateNumber(number))
  5181. }
  5182. /**
  5183. * writeStringOrBuffer - write a String or Buffer with the its length prefix
  5184. *
  5185. * @param <Buffer> buffer - destination
  5186. * @param <Number> pos - offset
  5187. * @param <String> toWrite - String or Buffer
  5188. * @return <Number> number of bytes written
  5189. */
  5190. function writeStringOrBuffer (stream, toWrite) {
  5191. if (typeof toWrite === 'string') {
  5192. writeString(stream, toWrite)
  5193. } else if (toWrite) {
  5194. writeNumber(stream, toWrite.length)
  5195. stream.write(toWrite)
  5196. } else writeNumber(stream, 0)
  5197. }
  5198. function byteLength (bufOrString) {
  5199. if (!bufOrString) return 0
  5200. else if (bufOrString instanceof Buffer) return bufOrString.length
  5201. else return Buffer.byteLength(bufOrString)
  5202. }
  5203. function isStringOrBuffer (field) {
  5204. return typeof field === 'string' || field instanceof Buffer
  5205. }
  5206. module.exports = generate
  5207. },{"./constants":21,"./numbers":25,"process-nextick-args":24,"safe-buffer":47}],29:[function(require,module,exports){
  5208. var wrappy = require('wrappy')
  5209. module.exports = wrappy(once)
  5210. module.exports.strict = wrappy(onceStrict)
  5211. once.proto = once(function () {
  5212. Object.defineProperty(Function.prototype, 'once', {
  5213. value: function () {
  5214. return once(this)
  5215. },
  5216. configurable: true
  5217. })
  5218. Object.defineProperty(Function.prototype, 'onceStrict', {
  5219. value: function () {
  5220. return onceStrict(this)
  5221. },
  5222. configurable: true
  5223. })
  5224. })
  5225. function once (fn) {
  5226. var f = function () {
  5227. if (f.called) return f.value
  5228. f.called = true
  5229. return f.value = fn.apply(this, arguments)
  5230. }
  5231. f.called = false
  5232. return f
  5233. }
  5234. function onceStrict (fn) {
  5235. var f = function () {
  5236. if (f.called)
  5237. throw new Error(f.onceError)
  5238. f.called = true
  5239. return f.value = fn.apply(this, arguments)
  5240. }
  5241. var name = fn.name || 'Function wrapped with `once`'
  5242. f.onceError = name + " shouldn't be called more than once"
  5243. f.called = false
  5244. return f
  5245. }
  5246. },{"wrappy":58}],30:[function(require,module,exports){
  5247. // shim for using process in browser
  5248. var process = module.exports = {};
  5249. // cached from whatever global is present so that test runners that stub it
  5250. // don't break things. But we need to wrap it in a try catch in case it is
  5251. // wrapped in strict mode code which doesn't define any globals. It's inside a
  5252. // function because try/catches deoptimize in certain engines.
  5253. var cachedSetTimeout;
  5254. var cachedClearTimeout;
  5255. function defaultSetTimout() {
  5256. throw new Error('setTimeout has not been defined');
  5257. }
  5258. function defaultClearTimeout () {
  5259. throw new Error('clearTimeout has not been defined');
  5260. }
  5261. (function () {
  5262. try {
  5263. if (typeof setTimeout === 'function') {
  5264. cachedSetTimeout = setTimeout;
  5265. } else {
  5266. cachedSetTimeout = defaultSetTimout;
  5267. }
  5268. } catch (e) {
  5269. cachedSetTimeout = defaultSetTimout;
  5270. }
  5271. try {
  5272. if (typeof clearTimeout === 'function') {
  5273. cachedClearTimeout = clearTimeout;
  5274. } else {
  5275. cachedClearTimeout = defaultClearTimeout;
  5276. }
  5277. } catch (e) {
  5278. cachedClearTimeout = defaultClearTimeout;
  5279. }
  5280. } ())
  5281. function runTimeout(fun) {
  5282. if (cachedSetTimeout === setTimeout) {
  5283. //normal enviroments in sane situations
  5284. return setTimeout(fun, 0);
  5285. }
  5286. // if setTimeout wasn't available but was latter defined
  5287. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  5288. cachedSetTimeout = setTimeout;
  5289. return setTimeout(fun, 0);
  5290. }
  5291. try {
  5292. // when when somebody has screwed with setTimeout but no I.E. maddness
  5293. return cachedSetTimeout(fun, 0);
  5294. } catch(e){
  5295. try {
  5296. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  5297. return cachedSetTimeout.call(null, fun, 0);
  5298. } catch(e){
  5299. // 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
  5300. return cachedSetTimeout.call(this, fun, 0);
  5301. }
  5302. }
  5303. }
  5304. function runClearTimeout(marker) {
  5305. if (cachedClearTimeout === clearTimeout) {
  5306. //normal enviroments in sane situations
  5307. return clearTimeout(marker);
  5308. }
  5309. // if clearTimeout wasn't available but was latter defined
  5310. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  5311. cachedClearTimeout = clearTimeout;
  5312. return clearTimeout(marker);
  5313. }
  5314. try {
  5315. // when when somebody has screwed with setTimeout but no I.E. maddness
  5316. return cachedClearTimeout(marker);
  5317. } catch (e){
  5318. try {
  5319. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  5320. return cachedClearTimeout.call(null, marker);
  5321. } catch (e){
  5322. // 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.
  5323. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  5324. return cachedClearTimeout.call(this, marker);
  5325. }
  5326. }
  5327. }
  5328. var queue = [];
  5329. var draining = false;
  5330. var currentQueue;
  5331. var queueIndex = -1;
  5332. function cleanUpNextTick() {
  5333. if (!draining || !currentQueue) {
  5334. return;
  5335. }
  5336. draining = false;
  5337. if (currentQueue.length) {
  5338. queue = currentQueue.concat(queue);
  5339. } else {
  5340. queueIndex = -1;
  5341. }
  5342. if (queue.length) {
  5343. drainQueue();
  5344. }
  5345. }
  5346. function drainQueue() {
  5347. if (draining) {
  5348. return;
  5349. }
  5350. var timeout = runTimeout(cleanUpNextTick);
  5351. draining = true;
  5352. var len = queue.length;
  5353. while(len) {
  5354. currentQueue = queue;
  5355. queue = [];
  5356. while (++queueIndex < len) {
  5357. if (currentQueue) {
  5358. currentQueue[queueIndex].run();
  5359. }
  5360. }
  5361. queueIndex = -1;
  5362. len = queue.length;
  5363. }
  5364. currentQueue = null;
  5365. draining = false;
  5366. runClearTimeout(timeout);
  5367. }
  5368. process.nextTick = function (fun) {
  5369. var args = new Array(arguments.length - 1);
  5370. if (arguments.length > 1) {
  5371. for (var i = 1; i < arguments.length; i++) {
  5372. args[i - 1] = arguments[i];
  5373. }
  5374. }
  5375. queue.push(new Item(fun, args));
  5376. if (queue.length === 1 && !draining) {
  5377. runTimeout(drainQueue);
  5378. }
  5379. };
  5380. // v8 likes predictible objects
  5381. function Item(fun, array) {
  5382. this.fun = fun;
  5383. this.array = array;
  5384. }
  5385. Item.prototype.run = function () {
  5386. this.fun.apply(null, this.array);
  5387. };
  5388. process.title = 'browser';
  5389. process.browser = true;
  5390. process.env = {};
  5391. process.argv = [];
  5392. process.version = ''; // empty string to avoid regexp issues
  5393. process.versions = {};
  5394. function noop() {}
  5395. process.on = noop;
  5396. process.addListener = noop;
  5397. process.once = noop;
  5398. process.off = noop;
  5399. process.removeListener = noop;
  5400. process.removeAllListeners = noop;
  5401. process.emit = noop;
  5402. process.prependListener = noop;
  5403. process.prependOnceListener = noop;
  5404. process.listeners = function (name) { return [] }
  5405. process.binding = function (name) {
  5406. throw new Error('process.binding is not supported');
  5407. };
  5408. process.cwd = function () { return '/' };
  5409. process.chdir = function (dir) {
  5410. throw new Error('process.chdir is not supported');
  5411. };
  5412. process.umask = function() { return 0; };
  5413. },{}],31:[function(require,module,exports){
  5414. (function (global){
  5415. /*! https://mths.be/punycode v1.4.1 by @mathias */
  5416. ;(function(root) {
  5417. /** Detect free variables */
  5418. var freeExports = typeof exports == 'object' && exports &&
  5419. !exports.nodeType && exports;
  5420. var freeModule = typeof module == 'object' && module &&
  5421. !module.nodeType && module;
  5422. var freeGlobal = typeof global == 'object' && global;
  5423. if (
  5424. freeGlobal.global === freeGlobal ||
  5425. freeGlobal.window === freeGlobal ||
  5426. freeGlobal.self === freeGlobal
  5427. ) {
  5428. root = freeGlobal;
  5429. }
  5430. /**
  5431. * The `punycode` object.
  5432. * @name punycode
  5433. * @type Object
  5434. */
  5435. var punycode,
  5436. /** Highest positive signed 32-bit float value */
  5437. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  5438. /** Bootstring parameters */
  5439. base = 36,
  5440. tMin = 1,
  5441. tMax = 26,
  5442. skew = 38,
  5443. damp = 700,
  5444. initialBias = 72,
  5445. initialN = 128, // 0x80
  5446. delimiter = '-', // '\x2D'
  5447. /** Regular expressions */
  5448. regexPunycode = /^xn--/,
  5449. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  5450. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  5451. /** Error messages */
  5452. errors = {
  5453. 'overflow': 'Overflow: input needs wider integers to process',
  5454. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  5455. 'invalid-input': 'Invalid input'
  5456. },
  5457. /** Convenience shortcuts */
  5458. baseMinusTMin = base - tMin,
  5459. floor = Math.floor,
  5460. stringFromCharCode = String.fromCharCode,
  5461. /** Temporary variable */
  5462. key;
  5463. /*--------------------------------------------------------------------------*/
  5464. /**
  5465. * A generic error utility function.
  5466. * @private
  5467. * @param {String} type The error type.
  5468. * @returns {Error} Throws a `RangeError` with the applicable error message.
  5469. */
  5470. function error(type) {
  5471. throw new RangeError(errors[type]);
  5472. }
  5473. /**
  5474. * A generic `Array#map` utility function.
  5475. * @private
  5476. * @param {Array} array The array to iterate over.
  5477. * @param {Function} callback The function that gets called for every array
  5478. * item.
  5479. * @returns {Array} A new array of values returned by the callback function.
  5480. */
  5481. function map(array, fn) {
  5482. var length = array.length;
  5483. var result = [];
  5484. while (length--) {
  5485. result[length] = fn(array[length]);
  5486. }
  5487. return result;
  5488. }
  5489. /**
  5490. * A simple `Array#map`-like wrapper to work with domain name strings or email
  5491. * addresses.
  5492. * @private
  5493. * @param {String} domain The domain name or email address.
  5494. * @param {Function} callback The function that gets called for every
  5495. * character.
  5496. * @returns {Array} A new string of characters returned by the callback
  5497. * function.
  5498. */
  5499. function mapDomain(string, fn) {
  5500. var parts = string.split('@');
  5501. var result = '';
  5502. if (parts.length > 1) {
  5503. // In email addresses, only the domain name should be punycoded. Leave
  5504. // the local part (i.e. everything up to `@`) intact.
  5505. result = parts[0] + '@';
  5506. string = parts[1];
  5507. }
  5508. // Avoid `split(regex)` for IE8 compatibility. See #17.
  5509. string = string.replace(regexSeparators, '\x2E');
  5510. var labels = string.split('.');
  5511. var encoded = map(labels, fn).join('.');
  5512. return result + encoded;
  5513. }
  5514. /**
  5515. * Creates an array containing the numeric code points of each Unicode
  5516. * character in the string. While JavaScript uses UCS-2 internally,
  5517. * this function will convert a pair of surrogate halves (each of which
  5518. * UCS-2 exposes as separate characters) into a single code point,
  5519. * matching UTF-16.
  5520. * @see `punycode.ucs2.encode`
  5521. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  5522. * @memberOf punycode.ucs2
  5523. * @name decode
  5524. * @param {String} string The Unicode input string (UCS-2).
  5525. * @returns {Array} The new array of code points.
  5526. */
  5527. function ucs2decode(string) {
  5528. var output = [],
  5529. counter = 0,
  5530. length = string.length,
  5531. value,
  5532. extra;
  5533. while (counter < length) {
  5534. value = string.charCodeAt(counter++);
  5535. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  5536. // high surrogate, and there is a next character
  5537. extra = string.charCodeAt(counter++);
  5538. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  5539. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  5540. } else {
  5541. // unmatched surrogate; only append this code unit, in case the next
  5542. // code unit is the high surrogate of a surrogate pair
  5543. output.push(value);
  5544. counter--;
  5545. }
  5546. } else {
  5547. output.push(value);
  5548. }
  5549. }
  5550. return output;
  5551. }
  5552. /**
  5553. * Creates a string based on an array of numeric code points.
  5554. * @see `punycode.ucs2.decode`
  5555. * @memberOf punycode.ucs2
  5556. * @name encode
  5557. * @param {Array} codePoints The array of numeric code points.
  5558. * @returns {String} The new Unicode string (UCS-2).
  5559. */
  5560. function ucs2encode(array) {
  5561. return map(array, function(value) {
  5562. var output = '';
  5563. if (value > 0xFFFF) {
  5564. value -= 0x10000;
  5565. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  5566. value = 0xDC00 | value & 0x3FF;
  5567. }
  5568. output += stringFromCharCode(value);
  5569. return output;
  5570. }).join('');
  5571. }
  5572. /**
  5573. * Converts a basic code point into a digit/integer.
  5574. * @see `digitToBasic()`
  5575. * @private
  5576. * @param {Number} codePoint The basic numeric code point value.
  5577. * @returns {Number} The numeric value of a basic code point (for use in
  5578. * representing integers) in the range `0` to `base - 1`, or `base` if
  5579. * the code point does not represent a value.
  5580. */
  5581. function basicToDigit(codePoint) {
  5582. if (codePoint - 48 < 10) {
  5583. return codePoint - 22;
  5584. }
  5585. if (codePoint - 65 < 26) {
  5586. return codePoint - 65;
  5587. }
  5588. if (codePoint - 97 < 26) {
  5589. return codePoint - 97;
  5590. }
  5591. return base;
  5592. }
  5593. /**
  5594. * Converts a digit/integer into a basic code point.
  5595. * @see `basicToDigit()`
  5596. * @private
  5597. * @param {Number} digit The numeric value of a basic code point.
  5598. * @returns {Number} The basic code point whose value (when used for
  5599. * representing integers) is `digit`, which needs to be in the range
  5600. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  5601. * used; else, the lowercase form is used. The behavior is undefined
  5602. * if `flag` is non-zero and `digit` has no uppercase form.
  5603. */
  5604. function digitToBasic(digit, flag) {
  5605. // 0..25 map to ASCII a..z or A..Z
  5606. // 26..35 map to ASCII 0..9
  5607. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  5608. }
  5609. /**
  5610. * Bias adaptation function as per section 3.4 of RFC 3492.
  5611. * https://tools.ietf.org/html/rfc3492#section-3.4
  5612. * @private
  5613. */
  5614. function adapt(delta, numPoints, firstTime) {
  5615. var k = 0;
  5616. delta = firstTime ? floor(delta / damp) : delta >> 1;
  5617. delta += floor(delta / numPoints);
  5618. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  5619. delta = floor(delta / baseMinusTMin);
  5620. }
  5621. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  5622. }
  5623. /**
  5624. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  5625. * symbols.
  5626. * @memberOf punycode
  5627. * @param {String} input The Punycode string of ASCII-only symbols.
  5628. * @returns {String} The resulting string of Unicode symbols.
  5629. */
  5630. function decode(input) {
  5631. // Don't use UCS-2
  5632. var output = [],
  5633. inputLength = input.length,
  5634. out,
  5635. i = 0,
  5636. n = initialN,
  5637. bias = initialBias,
  5638. basic,
  5639. j,
  5640. index,
  5641. oldi,
  5642. w,
  5643. k,
  5644. digit,
  5645. t,
  5646. /** Cached calculation results */
  5647. baseMinusT;
  5648. // Handle the basic code points: let `basic` be the number of input code
  5649. // points before the last delimiter, or `0` if there is none, then copy
  5650. // the first basic code points to the output.
  5651. basic = input.lastIndexOf(delimiter);
  5652. if (basic < 0) {
  5653. basic = 0;
  5654. }
  5655. for (j = 0; j < basic; ++j) {
  5656. // if it's not a basic code point
  5657. if (input.charCodeAt(j) >= 0x80) {
  5658. error('not-basic');
  5659. }
  5660. output.push(input.charCodeAt(j));
  5661. }
  5662. // Main decoding loop: start just after the last delimiter if any basic code
  5663. // points were copied; start at the beginning otherwise.
  5664. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  5665. // `index` is the index of the next character to be consumed.
  5666. // Decode a generalized variable-length integer into `delta`,
  5667. // which gets added to `i`. The overflow checking is easier
  5668. // if we increase `i` as we go, then subtract off its starting
  5669. // value at the end to obtain `delta`.
  5670. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  5671. if (index >= inputLength) {
  5672. error('invalid-input');
  5673. }
  5674. digit = basicToDigit(input.charCodeAt(index++));
  5675. if (digit >= base || digit > floor((maxInt - i) / w)) {
  5676. error('overflow');
  5677. }
  5678. i += digit * w;
  5679. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  5680. if (digit < t) {
  5681. break;
  5682. }
  5683. baseMinusT = base - t;
  5684. if (w > floor(maxInt / baseMinusT)) {
  5685. error('overflow');
  5686. }
  5687. w *= baseMinusT;
  5688. }
  5689. out = output.length + 1;
  5690. bias = adapt(i - oldi, out, oldi == 0);
  5691. // `i` was supposed to wrap around from `out` to `0`,
  5692. // incrementing `n` each time, so we'll fix that now:
  5693. if (floor(i / out) > maxInt - n) {
  5694. error('overflow');
  5695. }
  5696. n += floor(i / out);
  5697. i %= out;
  5698. // Insert `n` at position `i` of the output
  5699. output.splice(i++, 0, n);
  5700. }
  5701. return ucs2encode(output);
  5702. }
  5703. /**
  5704. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  5705. * Punycode string of ASCII-only symbols.
  5706. * @memberOf punycode
  5707. * @param {String} input The string of Unicode symbols.
  5708. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  5709. */
  5710. function encode(input) {
  5711. var n,
  5712. delta,
  5713. handledCPCount,
  5714. basicLength,
  5715. bias,
  5716. j,
  5717. m,
  5718. q,
  5719. k,
  5720. t,
  5721. currentValue,
  5722. output = [],
  5723. /** `inputLength` will hold the number of code points in `input`. */
  5724. inputLength,
  5725. /** Cached calculation results */
  5726. handledCPCountPlusOne,
  5727. baseMinusT,
  5728. qMinusT;
  5729. // Convert the input in UCS-2 to Unicode
  5730. input = ucs2decode(input);
  5731. // Cache the length
  5732. inputLength = input.length;
  5733. // Initialize the state
  5734. n = initialN;
  5735. delta = 0;
  5736. bias = initialBias;
  5737. // Handle the basic code points
  5738. for (j = 0; j < inputLength; ++j) {
  5739. currentValue = input[j];
  5740. if (currentValue < 0x80) {
  5741. output.push(stringFromCharCode(currentValue));
  5742. }
  5743. }
  5744. handledCPCount = basicLength = output.length;
  5745. // `handledCPCount` is the number of code points that have been handled;
  5746. // `basicLength` is the number of basic code points.
  5747. // Finish the basic string - if it is not empty - with a delimiter
  5748. if (basicLength) {
  5749. output.push(delimiter);
  5750. }
  5751. // Main encoding loop:
  5752. while (handledCPCount < inputLength) {
  5753. // All non-basic code points < n have been handled already. Find the next
  5754. // larger one:
  5755. for (m = maxInt, j = 0; j < inputLength; ++j) {
  5756. currentValue = input[j];
  5757. if (currentValue >= n && currentValue < m) {
  5758. m = currentValue;
  5759. }
  5760. }
  5761. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  5762. // but guard against overflow
  5763. handledCPCountPlusOne = handledCPCount + 1;
  5764. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  5765. error('overflow');
  5766. }
  5767. delta += (m - n) * handledCPCountPlusOne;
  5768. n = m;
  5769. for (j = 0; j < inputLength; ++j) {
  5770. currentValue = input[j];
  5771. if (currentValue < n && ++delta > maxInt) {
  5772. error('overflow');
  5773. }
  5774. if (currentValue == n) {
  5775. // Represent delta as a generalized variable-length integer
  5776. for (q = delta, k = base; /* no condition */; k += base) {
  5777. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  5778. if (q < t) {
  5779. break;
  5780. }
  5781. qMinusT = q - t;
  5782. baseMinusT = base - t;
  5783. output.push(
  5784. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  5785. );
  5786. q = floor(qMinusT / baseMinusT);
  5787. }
  5788. output.push(stringFromCharCode(digitToBasic(q, 0)));
  5789. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  5790. delta = 0;
  5791. ++handledCPCount;
  5792. }
  5793. }
  5794. ++delta;
  5795. ++n;
  5796. }
  5797. return output.join('');
  5798. }
  5799. /**
  5800. * Converts a Punycode string representing a domain name or an email address
  5801. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  5802. * it doesn't matter if you call it on a string that has already been
  5803. * converted to Unicode.
  5804. * @memberOf punycode
  5805. * @param {String} input The Punycoded domain name or email address to
  5806. * convert to Unicode.
  5807. * @returns {String} The Unicode representation of the given Punycode
  5808. * string.
  5809. */
  5810. function toUnicode(input) {
  5811. return mapDomain(input, function(string) {
  5812. return regexPunycode.test(string)
  5813. ? decode(string.slice(4).toLowerCase())
  5814. : string;
  5815. });
  5816. }
  5817. /**
  5818. * Converts a Unicode string representing a domain name or an email address to
  5819. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  5820. * i.e. it doesn't matter if you call it with a domain that's already in
  5821. * ASCII.
  5822. * @memberOf punycode
  5823. * @param {String} input The domain name or email address to convert, as a
  5824. * Unicode string.
  5825. * @returns {String} The Punycode representation of the given domain name or
  5826. * email address.
  5827. */
  5828. function toASCII(input) {
  5829. return mapDomain(input, function(string) {
  5830. return regexNonASCII.test(string)
  5831. ? 'xn--' + encode(string)
  5832. : string;
  5833. });
  5834. }
  5835. /*--------------------------------------------------------------------------*/
  5836. /** Define the public API */
  5837. punycode = {
  5838. /**
  5839. * A string representing the current Punycode.js version number.
  5840. * @memberOf punycode
  5841. * @type String
  5842. */
  5843. 'version': '1.4.1',
  5844. /**
  5845. * An object of methods to convert from JavaScript's internal character
  5846. * representation (UCS-2) to Unicode code points, and back.
  5847. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  5848. * @memberOf punycode
  5849. * @type Object
  5850. */
  5851. 'ucs2': {
  5852. 'decode': ucs2decode,
  5853. 'encode': ucs2encode
  5854. },
  5855. 'decode': decode,
  5856. 'encode': encode,
  5857. 'toASCII': toASCII,
  5858. 'toUnicode': toUnicode
  5859. };
  5860. /** Expose `punycode` */
  5861. // Some AMD build optimizers, like r.js, check for specific condition patterns
  5862. // like the following:
  5863. if (
  5864. typeof define == 'function' &&
  5865. typeof define.amd == 'object' &&
  5866. define.amd
  5867. ) {
  5868. define('punycode', function() {
  5869. return punycode;
  5870. });
  5871. } else if (freeExports && freeModule) {
  5872. if (module.exports == freeExports) {
  5873. // in Node.js, io.js, or RingoJS v0.8.0+
  5874. freeModule.exports = punycode;
  5875. } else {
  5876. // in Narwhal or RingoJS v0.7.0-
  5877. for (key in punycode) {
  5878. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  5879. }
  5880. }
  5881. } else {
  5882. // in Rhino or a web browser
  5883. root.punycode = punycode;
  5884. }
  5885. }(this));
  5886. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5887. },{}],32:[function(require,module,exports){
  5888. // Copyright Joyent, Inc. and other Node contributors.
  5889. //
  5890. // Permission is hereby granted, free of charge, to any person obtaining a
  5891. // copy of this software and associated documentation files (the
  5892. // "Software"), to deal in the Software without restriction, including
  5893. // without limitation the rights to use, copy, modify, merge, publish,
  5894. // distribute, sublicense, and/or sell copies of the Software, and to permit
  5895. // persons to whom the Software is furnished to do so, subject to the
  5896. // following conditions:
  5897. //
  5898. // The above copyright notice and this permission notice shall be included
  5899. // in all copies or substantial portions of the Software.
  5900. //
  5901. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  5902. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  5903. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  5904. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  5905. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  5906. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  5907. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  5908. 'use strict';
  5909. // If obj.hasOwnProperty has been overridden, then calling
  5910. // obj.hasOwnProperty(prop) will break.
  5911. // See: https://github.com/joyent/node/issues/1707
  5912. function hasOwnProperty(obj, prop) {
  5913. return Object.prototype.hasOwnProperty.call(obj, prop);
  5914. }
  5915. module.exports = function(qs, sep, eq, options) {
  5916. sep = sep || '&';
  5917. eq = eq || '=';
  5918. var obj = {};
  5919. if (typeof qs !== 'string' || qs.length === 0) {
  5920. return obj;
  5921. }
  5922. var regexp = /\+/g;
  5923. qs = qs.split(sep);
  5924. var maxKeys = 1000;
  5925. if (options && typeof options.maxKeys === 'number') {
  5926. maxKeys = options.maxKeys;
  5927. }
  5928. var len = qs.length;
  5929. // maxKeys <= 0 means that we should not limit keys count
  5930. if (maxKeys > 0 && len > maxKeys) {
  5931. len = maxKeys;
  5932. }
  5933. for (var i = 0; i < len; ++i) {
  5934. var x = qs[i].replace(regexp, '%20'),
  5935. idx = x.indexOf(eq),
  5936. kstr, vstr, k, v;
  5937. if (idx >= 0) {
  5938. kstr = x.substr(0, idx);
  5939. vstr = x.substr(idx + 1);
  5940. } else {
  5941. kstr = x;
  5942. vstr = '';
  5943. }
  5944. k = decodeURIComponent(kstr);
  5945. v = decodeURIComponent(vstr);
  5946. if (!hasOwnProperty(obj, k)) {
  5947. obj[k] = v;
  5948. } else if (isArray(obj[k])) {
  5949. obj[k].push(v);
  5950. } else {
  5951. obj[k] = [obj[k], v];
  5952. }
  5953. }
  5954. return obj;
  5955. };
  5956. var isArray = Array.isArray || function (xs) {
  5957. return Object.prototype.toString.call(xs) === '[object Array]';
  5958. };
  5959. },{}],33:[function(require,module,exports){
  5960. // Copyright Joyent, Inc. and other Node contributors.
  5961. //
  5962. // Permission is hereby granted, free of charge, to any person obtaining a
  5963. // copy of this software and associated documentation files (the
  5964. // "Software"), to deal in the Software without restriction, including
  5965. // without limitation the rights to use, copy, modify, merge, publish,
  5966. // distribute, sublicense, and/or sell copies of the Software, and to permit
  5967. // persons to whom the Software is furnished to do so, subject to the
  5968. // following conditions:
  5969. //
  5970. // The above copyright notice and this permission notice shall be included
  5971. // in all copies or substantial portions of the Software.
  5972. //
  5973. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  5974. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  5975. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  5976. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  5977. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  5978. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  5979. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  5980. 'use strict';
  5981. var stringifyPrimitive = function(v) {
  5982. switch (typeof v) {
  5983. case 'string':
  5984. return v;
  5985. case 'boolean':
  5986. return v ? 'true' : 'false';
  5987. case 'number':
  5988. return isFinite(v) ? v : '';
  5989. default:
  5990. return '';
  5991. }
  5992. };
  5993. module.exports = function(obj, sep, eq, name) {
  5994. sep = sep || '&';
  5995. eq = eq || '=';
  5996. if (obj === null) {
  5997. obj = undefined;
  5998. }
  5999. if (typeof obj === 'object') {
  6000. return map(objectKeys(obj), function(k) {
  6001. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  6002. if (isArray(obj[k])) {
  6003. return map(obj[k], function(v) {
  6004. return ks + encodeURIComponent(stringifyPrimitive(v));
  6005. }).join(sep);
  6006. } else {
  6007. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  6008. }
  6009. }).join(sep);
  6010. }
  6011. if (!name) return '';
  6012. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  6013. encodeURIComponent(stringifyPrimitive(obj));
  6014. };
  6015. var isArray = Array.isArray || function (xs) {
  6016. return Object.prototype.toString.call(xs) === '[object Array]';
  6017. };
  6018. function map (xs, f) {
  6019. if (xs.map) return xs.map(f);
  6020. var res = [];
  6021. for (var i = 0; i < xs.length; i++) {
  6022. res.push(f(xs[i], i));
  6023. }
  6024. return res;
  6025. }
  6026. var objectKeys = Object.keys || function (obj) {
  6027. var res = [];
  6028. for (var key in obj) {
  6029. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  6030. }
  6031. return res;
  6032. };
  6033. },{}],34:[function(require,module,exports){
  6034. 'use strict';
  6035. exports.decode = exports.parse = require('./decode');
  6036. exports.encode = exports.stringify = require('./encode');
  6037. },{"./decode":32,"./encode":33}],35:[function(require,module,exports){
  6038. module.exports = require('./lib/_stream_duplex.js');
  6039. },{"./lib/_stream_duplex.js":36}],36:[function(require,module,exports){
  6040. // Copyright Joyent, Inc. and other Node contributors.
  6041. //
  6042. // Permission is hereby granted, free of charge, to any person obtaining a
  6043. // copy of this software and associated documentation files (the
  6044. // "Software"), to deal in the Software without restriction, including
  6045. // without limitation the rights to use, copy, modify, merge, publish,
  6046. // distribute, sublicense, and/or sell copies of the Software, and to permit
  6047. // persons to whom the Software is furnished to do so, subject to the
  6048. // following conditions:
  6049. //
  6050. // The above copyright notice and this permission notice shall be included
  6051. // in all copies or substantial portions of the Software.
  6052. //
  6053. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  6054. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6055. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  6056. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  6057. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  6058. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  6059. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  6060. // a duplex stream is just a stream that is both readable and writable.
  6061. // Since JS doesn't have multiple prototypal inheritance, this class
  6062. // prototypally inherits from Readable, and then parasitically from
  6063. // Writable.
  6064. 'use strict';
  6065. /*<replacement>*/
  6066. var pna = require('process-nextick-args');
  6067. /*</replacement>*/
  6068. /*<replacement>*/
  6069. var objectKeys = Object.keys || function (obj) {
  6070. var keys = [];
  6071. for (var key in obj) {
  6072. keys.push(key);
  6073. }return keys;
  6074. };
  6075. /*</replacement>*/
  6076. module.exports = Duplex;
  6077. /*<replacement>*/
  6078. var util = require('core-util-is');
  6079. util.inherits = require('inherits');
  6080. /*</replacement>*/
  6081. var Readable = require('./_stream_readable');
  6082. var Writable = require('./_stream_writable');
  6083. util.inherits(Duplex, Readable);
  6084. {
  6085. // avoid scope creep, the keys array can then be collected
  6086. var keys = objectKeys(Writable.prototype);
  6087. for (var v = 0; v < keys.length; v++) {
  6088. var method = keys[v];
  6089. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  6090. }
  6091. }
  6092. function Duplex(options) {
  6093. if (!(this instanceof Duplex)) return new Duplex(options);
  6094. Readable.call(this, options);
  6095. Writable.call(this, options);
  6096. if (options && options.readable === false) this.readable = false;
  6097. if (options && options.writable === false) this.writable = false;
  6098. this.allowHalfOpen = true;
  6099. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  6100. this.once('end', onend);
  6101. }
  6102. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  6103. // making it explicit this property is not enumerable
  6104. // because otherwise some prototype manipulation in
  6105. // userland will fail
  6106. enumerable: false,
  6107. get: function () {
  6108. return this._writableState.highWaterMark;
  6109. }
  6110. });
  6111. // the no-half-open enforcer
  6112. function onend() {
  6113. // if we allow half-open state, or if the writable side ended,
  6114. // then we're ok.
  6115. if (this.allowHalfOpen || this._writableState.ended) return;
  6116. // no more data can be written.
  6117. // But allow more writes to happen in this tick.
  6118. pna.nextTick(onEndNT, this);
  6119. }
  6120. function onEndNT(self) {
  6121. self.end();
  6122. }
  6123. Object.defineProperty(Duplex.prototype, 'destroyed', {
  6124. get: function () {
  6125. if (this._readableState === undefined || this._writableState === undefined) {
  6126. return false;
  6127. }
  6128. return this._readableState.destroyed && this._writableState.destroyed;
  6129. },
  6130. set: function (value) {
  6131. // we ignore the value if the stream
  6132. // has not been initialized yet
  6133. if (this._readableState === undefined || this._writableState === undefined) {
  6134. return;
  6135. }
  6136. // backward compatibility, the user is explicitly
  6137. // managing destroyed
  6138. this._readableState.destroyed = value;
  6139. this._writableState.destroyed = value;
  6140. }
  6141. });
  6142. Duplex.prototype._destroy = function (err, cb) {
  6143. this.push(null);
  6144. this.end();
  6145. pna.nextTick(cb, err);
  6146. };
  6147. },{"./_stream_readable":38,"./_stream_writable":40,"core-util-is":14,"inherits":18,"process-nextick-args":44}],37:[function(require,module,exports){
  6148. // Copyright Joyent, Inc. and other Node contributors.
  6149. //
  6150. // Permission is hereby granted, free of charge, to any person obtaining a
  6151. // copy of this software and associated documentation files (the
  6152. // "Software"), to deal in the Software without restriction, including
  6153. // without limitation the rights to use, copy, modify, merge, publish,
  6154. // distribute, sublicense, and/or sell copies of the Software, and to permit
  6155. // persons to whom the Software is furnished to do so, subject to the
  6156. // following conditions:
  6157. //
  6158. // The above copyright notice and this permission notice shall be included
  6159. // in all copies or substantial portions of the Software.
  6160. //
  6161. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  6162. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6163. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  6164. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  6165. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  6166. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  6167. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  6168. // a passthrough stream.
  6169. // basically just the most minimal sort of Transform stream.
  6170. // Every written chunk gets output as-is.
  6171. 'use strict';
  6172. module.exports = PassThrough;
  6173. var Transform = require('./_stream_transform');
  6174. /*<replacement>*/
  6175. var util = require('core-util-is');
  6176. util.inherits = require('inherits');
  6177. /*</replacement>*/
  6178. util.inherits(PassThrough, Transform);
  6179. function PassThrough(options) {
  6180. if (!(this instanceof PassThrough)) return new PassThrough(options);
  6181. Transform.call(this, options);
  6182. }
  6183. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  6184. cb(null, chunk);
  6185. };
  6186. },{"./_stream_transform":39,"core-util-is":14,"inherits":18}],38:[function(require,module,exports){
  6187. (function (process,global){
  6188. // Copyright Joyent, Inc. and other Node contributors.
  6189. //
  6190. // Permission is hereby granted, free of charge, to any person obtaining a
  6191. // copy of this software and associated documentation files (the
  6192. // "Software"), to deal in the Software without restriction, including
  6193. // without limitation the rights to use, copy, modify, merge, publish,
  6194. // distribute, sublicense, and/or sell copies of the Software, and to permit
  6195. // persons to whom the Software is furnished to do so, subject to the
  6196. // following conditions:
  6197. //
  6198. // The above copyright notice and this permission notice shall be included
  6199. // in all copies or substantial portions of the Software.
  6200. //
  6201. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  6202. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6203. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  6204. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  6205. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  6206. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  6207. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  6208. 'use strict';
  6209. /*<replacement>*/
  6210. var pna = require('process-nextick-args');
  6211. /*</replacement>*/
  6212. module.exports = Readable;
  6213. /*<replacement>*/
  6214. var isArray = require('isarray');
  6215. /*</replacement>*/
  6216. /*<replacement>*/
  6217. var Duplex;
  6218. /*</replacement>*/
  6219. Readable.ReadableState = ReadableState;
  6220. /*<replacement>*/
  6221. var EE = require('events').EventEmitter;
  6222. var EElistenerCount = function (emitter, type) {
  6223. return emitter.listeners(type).length;
  6224. };
  6225. /*</replacement>*/
  6226. /*<replacement>*/
  6227. var Stream = require('./internal/streams/stream');
  6228. /*</replacement>*/
  6229. /*<replacement>*/
  6230. var Buffer = require('safe-buffer').Buffer;
  6231. var OurUint8Array = global.Uint8Array || function () {};
  6232. function _uint8ArrayToBuffer(chunk) {
  6233. return Buffer.from(chunk);
  6234. }
  6235. function _isUint8Array(obj) {
  6236. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  6237. }
  6238. /*</replacement>*/
  6239. /*<replacement>*/
  6240. var util = require('core-util-is');
  6241. util.inherits = require('inherits');
  6242. /*</replacement>*/
  6243. /*<replacement>*/
  6244. var debugUtil = require('util');
  6245. var debug = void 0;
  6246. if (debugUtil && debugUtil.debuglog) {
  6247. debug = debugUtil.debuglog('stream');
  6248. } else {
  6249. debug = function () {};
  6250. }
  6251. /*</replacement>*/
  6252. var BufferList = require('./internal/streams/BufferList');
  6253. var destroyImpl = require('./internal/streams/destroy');
  6254. var StringDecoder;
  6255. util.inherits(Readable, Stream);
  6256. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  6257. function prependListener(emitter, event, fn) {
  6258. // Sadly this is not cacheable as some libraries bundle their own
  6259. // event emitter implementation with them.
  6260. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  6261. // This is a hack to make sure that our error handler is attached before any
  6262. // userland ones. NEVER DO THIS. This is here only because this code needs
  6263. // to continue to work with older versions of Node.js that do not include
  6264. // the prependListener() method. The goal is to eventually remove this hack.
  6265. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  6266. }
  6267. function ReadableState(options, stream) {
  6268. Duplex = Duplex || require('./_stream_duplex');
  6269. options = options || {};
  6270. // Duplex streams are both readable and writable, but share
  6271. // the same options object.
  6272. // However, some cases require setting options to different
  6273. // values for the readable and the writable sides of the duplex stream.
  6274. // These options can be provided separately as readableXXX and writableXXX.
  6275. var isDuplex = stream instanceof Duplex;
  6276. // object stream flag. Used to make read(n) ignore n and to
  6277. // make all the buffer merging and length checks go away
  6278. this.objectMode = !!options.objectMode;
  6279. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  6280. // the point at which it stops calling _read() to fill the buffer
  6281. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  6282. var hwm = options.highWaterMark;
  6283. var readableHwm = options.readableHighWaterMark;
  6284. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  6285. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
  6286. // cast to ints.
  6287. this.highWaterMark = Math.floor(this.highWaterMark);
  6288. // A linked list is used to store data chunks instead of an array because the
  6289. // linked list can remove elements from the beginning faster than
  6290. // array.shift()
  6291. this.buffer = new BufferList();
  6292. this.length = 0;
  6293. this.pipes = null;
  6294. this.pipesCount = 0;
  6295. this.flowing = null;
  6296. this.ended = false;
  6297. this.endEmitted = false;
  6298. this.reading = false;
  6299. // a flag to be able to tell if the event 'readable'/'data' is emitted
  6300. // immediately, or on a later tick. We set this to true at first, because
  6301. // any actions that shouldn't happen until "later" should generally also
  6302. // not happen before the first read call.
  6303. this.sync = true;
  6304. // whenever we return null, then we set a flag to say
  6305. // that we're awaiting a 'readable' event emission.
  6306. this.needReadable = false;
  6307. this.emittedReadable = false;
  6308. this.readableListening = false;
  6309. this.resumeScheduled = false;
  6310. // has it been destroyed
  6311. this.destroyed = false;
  6312. // Crypto is kind of old and crusty. Historically, its default string
  6313. // encoding is 'binary' so we have to make this configurable.
  6314. // Everything else in the universe uses 'utf8', though.
  6315. this.defaultEncoding = options.defaultEncoding || 'utf8';
  6316. // the number of writers that are awaiting a drain event in .pipe()s
  6317. this.awaitDrain = 0;
  6318. // if true, a maybeReadMore has been scheduled
  6319. this.readingMore = false;
  6320. this.decoder = null;
  6321. this.encoding = null;
  6322. if (options.encoding) {
  6323. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  6324. this.decoder = new StringDecoder(options.encoding);
  6325. this.encoding = options.encoding;
  6326. }
  6327. }
  6328. function Readable(options) {
  6329. Duplex = Duplex || require('./_stream_duplex');
  6330. if (!(this instanceof Readable)) return new Readable(options);
  6331. this._readableState = new ReadableState(options, this);
  6332. // legacy
  6333. this.readable = true;
  6334. if (options) {
  6335. if (typeof options.read === 'function') this._read = options.read;
  6336. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  6337. }
  6338. Stream.call(this);
  6339. }
  6340. Object.defineProperty(Readable.prototype, 'destroyed', {
  6341. get: function () {
  6342. if (this._readableState === undefined) {
  6343. return false;
  6344. }
  6345. return this._readableState.destroyed;
  6346. },
  6347. set: function (value) {
  6348. // we ignore the value if the stream
  6349. // has not been initialized yet
  6350. if (!this._readableState) {
  6351. return;
  6352. }
  6353. // backward compatibility, the user is explicitly
  6354. // managing destroyed
  6355. this._readableState.destroyed = value;
  6356. }
  6357. });
  6358. Readable.prototype.destroy = destroyImpl.destroy;
  6359. Readable.prototype._undestroy = destroyImpl.undestroy;
  6360. Readable.prototype._destroy = function (err, cb) {
  6361. this.push(null);
  6362. cb(err);
  6363. };
  6364. // Manually shove something into the read() buffer.
  6365. // This returns true if the highWaterMark has not been hit yet,
  6366. // similar to how Writable.write() returns true if you should
  6367. // write() some more.
  6368. Readable.prototype.push = function (chunk, encoding) {
  6369. var state = this._readableState;
  6370. var skipChunkCheck;
  6371. if (!state.objectMode) {
  6372. if (typeof chunk === 'string') {
  6373. encoding = encoding || state.defaultEncoding;
  6374. if (encoding !== state.encoding) {
  6375. chunk = Buffer.from(chunk, encoding);
  6376. encoding = '';
  6377. }
  6378. skipChunkCheck = true;
  6379. }
  6380. } else {
  6381. skipChunkCheck = true;
  6382. }
  6383. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  6384. };
  6385. // Unshift should *always* be something directly out of read()
  6386. Readable.prototype.unshift = function (chunk) {
  6387. return readableAddChunk(this, chunk, null, true, false);
  6388. };
  6389. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  6390. var state = stream._readableState;
  6391. if (chunk === null) {
  6392. state.reading = false;
  6393. onEofChunk(stream, state);
  6394. } else {
  6395. var er;
  6396. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  6397. if (er) {
  6398. stream.emit('error', er);
  6399. } else if (state.objectMode || chunk && chunk.length > 0) {
  6400. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  6401. chunk = _uint8ArrayToBuffer(chunk);
  6402. }
  6403. if (addToFront) {
  6404. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  6405. } else if (state.ended) {
  6406. stream.emit('error', new Error('stream.push() after EOF'));
  6407. } else {
  6408. state.reading = false;
  6409. if (state.decoder && !encoding) {
  6410. chunk = state.decoder.write(chunk);
  6411. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  6412. } else {
  6413. addChunk(stream, state, chunk, false);
  6414. }
  6415. }
  6416. } else if (!addToFront) {
  6417. state.reading = false;
  6418. }
  6419. }
  6420. return needMoreData(state);
  6421. }
  6422. function addChunk(stream, state, chunk, addToFront) {
  6423. if (state.flowing && state.length === 0 && !state.sync) {
  6424. stream.emit('data', chunk);
  6425. stream.read(0);
  6426. } else {
  6427. // update the buffer info.
  6428. state.length += state.objectMode ? 1 : chunk.length;
  6429. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  6430. if (state.needReadable) emitReadable(stream);
  6431. }
  6432. maybeReadMore(stream, state);
  6433. }
  6434. function chunkInvalid(state, chunk) {
  6435. var er;
  6436. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  6437. er = new TypeError('Invalid non-string/buffer chunk');
  6438. }
  6439. return er;
  6440. }
  6441. // if it's past the high water mark, we can push in some more.
  6442. // Also, if we have no data yet, we can stand some
  6443. // more bytes. This is to work around cases where hwm=0,
  6444. // such as the repl. Also, if the push() triggered a
  6445. // readable event, and the user called read(largeNumber) such that
  6446. // needReadable was set, then we ought to push more, so that another
  6447. // 'readable' event will be triggered.
  6448. function needMoreData(state) {
  6449. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  6450. }
  6451. Readable.prototype.isPaused = function () {
  6452. return this._readableState.flowing === false;
  6453. };
  6454. // backwards compatibility.
  6455. Readable.prototype.setEncoding = function (enc) {
  6456. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  6457. this._readableState.decoder = new StringDecoder(enc);
  6458. this._readableState.encoding = enc;
  6459. return this;
  6460. };
  6461. // Don't raise the hwm > 8MB
  6462. var MAX_HWM = 0x800000;
  6463. function computeNewHighWaterMark(n) {
  6464. if (n >= MAX_HWM) {
  6465. n = MAX_HWM;
  6466. } else {
  6467. // Get the next highest power of 2 to prevent increasing hwm excessively in
  6468. // tiny amounts
  6469. n--;
  6470. n |= n >>> 1;
  6471. n |= n >>> 2;
  6472. n |= n >>> 4;
  6473. n |= n >>> 8;
  6474. n |= n >>> 16;
  6475. n++;
  6476. }
  6477. return n;
  6478. }
  6479. // This function is designed to be inlinable, so please take care when making
  6480. // changes to the function body.
  6481. function howMuchToRead(n, state) {
  6482. if (n <= 0 || state.length === 0 && state.ended) return 0;
  6483. if (state.objectMode) return 1;
  6484. if (n !== n) {
  6485. // Only flow one buffer at a time
  6486. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  6487. }
  6488. // If we're asking for more than the current hwm, then raise the hwm.
  6489. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  6490. if (n <= state.length) return n;
  6491. // Don't have enough
  6492. if (!state.ended) {
  6493. state.needReadable = true;
  6494. return 0;
  6495. }
  6496. return state.length;
  6497. }
  6498. // you can override either this method, or the async _read(n) below.
  6499. Readable.prototype.read = function (n) {
  6500. debug('read', n);
  6501. n = parseInt(n, 10);
  6502. var state = this._readableState;
  6503. var nOrig = n;
  6504. if (n !== 0) state.emittedReadable = false;
  6505. // if we're doing read(0) to trigger a readable event, but we
  6506. // already have a bunch of data in the buffer, then just trigger
  6507. // the 'readable' event and move on.
  6508. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  6509. debug('read: emitReadable', state.length, state.ended);
  6510. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  6511. return null;
  6512. }
  6513. n = howMuchToRead(n, state);
  6514. // if we've ended, and we're now clear, then finish it up.
  6515. if (n === 0 && state.ended) {
  6516. if (state.length === 0) endReadable(this);
  6517. return null;
  6518. }
  6519. // All the actual chunk generation logic needs to be
  6520. // *below* the call to _read. The reason is that in certain
  6521. // synthetic stream cases, such as passthrough streams, _read
  6522. // may be a completely synchronous operation which may change
  6523. // the state of the read buffer, providing enough data when
  6524. // before there was *not* enough.
  6525. //
  6526. // So, the steps are:
  6527. // 1. Figure out what the state of things will be after we do
  6528. // a read from the buffer.
  6529. //
  6530. // 2. If that resulting state will trigger a _read, then call _read.
  6531. // Note that this may be asynchronous, or synchronous. Yes, it is
  6532. // deeply ugly to write APIs this way, but that still doesn't mean
  6533. // that the Readable class should behave improperly, as streams are
  6534. // designed to be sync/async agnostic.
  6535. // Take note if the _read call is sync or async (ie, if the read call
  6536. // has returned yet), so that we know whether or not it's safe to emit
  6537. // 'readable' etc.
  6538. //
  6539. // 3. Actually pull the requested chunks out of the buffer and return.
  6540. // if we need a readable event, then we need to do some reading.
  6541. var doRead = state.needReadable;
  6542. debug('need readable', doRead);
  6543. // if we currently have less than the highWaterMark, then also read some
  6544. if (state.length === 0 || state.length - n < state.highWaterMark) {
  6545. doRead = true;
  6546. debug('length less than watermark', doRead);
  6547. }
  6548. // however, if we've ended, then there's no point, and if we're already
  6549. // reading, then it's unnecessary.
  6550. if (state.ended || state.reading) {
  6551. doRead = false;
  6552. debug('reading or ended', doRead);
  6553. } else if (doRead) {
  6554. debug('do read');
  6555. state.reading = true;
  6556. state.sync = true;
  6557. // if the length is currently zero, then we *need* a readable event.
  6558. if (state.length === 0) state.needReadable = true;
  6559. // call internal read method
  6560. this._read(state.highWaterMark);
  6561. state.sync = false;
  6562. // If _read pushed data synchronously, then `reading` will be false,
  6563. // and we need to re-evaluate how much data we can return to the user.
  6564. if (!state.reading) n = howMuchToRead(nOrig, state);
  6565. }
  6566. var ret;
  6567. if (n > 0) ret = fromList(n, state);else ret = null;
  6568. if (ret === null) {
  6569. state.needReadable = true;
  6570. n = 0;
  6571. } else {
  6572. state.length -= n;
  6573. }
  6574. if (state.length === 0) {
  6575. // If we have nothing in the buffer, then we want to know
  6576. // as soon as we *do* get something into the buffer.
  6577. if (!state.ended) state.needReadable = true;
  6578. // If we tried to read() past the EOF, then emit end on the next tick.
  6579. if (nOrig !== n && state.ended) endReadable(this);
  6580. }
  6581. if (ret !== null) this.emit('data', ret);
  6582. return ret;
  6583. };
  6584. function onEofChunk(stream, state) {
  6585. if (state.ended) return;
  6586. if (state.decoder) {
  6587. var chunk = state.decoder.end();
  6588. if (chunk && chunk.length) {
  6589. state.buffer.push(chunk);
  6590. state.length += state.objectMode ? 1 : chunk.length;
  6591. }
  6592. }
  6593. state.ended = true;
  6594. // emit 'readable' now to make sure it gets picked up.
  6595. emitReadable(stream);
  6596. }
  6597. // Don't emit readable right away in sync mode, because this can trigger
  6598. // another read() call => stack overflow. This way, it might trigger
  6599. // a nextTick recursion warning, but that's not so bad.
  6600. function emitReadable(stream) {
  6601. var state = stream._readableState;
  6602. state.needReadable = false;
  6603. if (!state.emittedReadable) {
  6604. debug('emitReadable', state.flowing);
  6605. state.emittedReadable = true;
  6606. if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  6607. }
  6608. }
  6609. function emitReadable_(stream) {
  6610. debug('emit readable');
  6611. stream.emit('readable');
  6612. flow(stream);
  6613. }
  6614. // at this point, the user has presumably seen the 'readable' event,
  6615. // and called read() to consume some data. that may have triggered
  6616. // in turn another _read(n) call, in which case reading = true if
  6617. // it's in progress.
  6618. // However, if we're not ended, or reading, and the length < hwm,
  6619. // then go ahead and try to read some more preemptively.
  6620. function maybeReadMore(stream, state) {
  6621. if (!state.readingMore) {
  6622. state.readingMore = true;
  6623. pna.nextTick(maybeReadMore_, stream, state);
  6624. }
  6625. }
  6626. function maybeReadMore_(stream, state) {
  6627. var len = state.length;
  6628. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  6629. debug('maybeReadMore read 0');
  6630. stream.read(0);
  6631. if (len === state.length)
  6632. // didn't get any data, stop spinning.
  6633. break;else len = state.length;
  6634. }
  6635. state.readingMore = false;
  6636. }
  6637. // abstract method. to be overridden in specific implementation classes.
  6638. // call cb(er, data) where data is <= n in length.
  6639. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  6640. // arbitrary, and perhaps not very meaningful.
  6641. Readable.prototype._read = function (n) {
  6642. this.emit('error', new Error('_read() is not implemented'));
  6643. };
  6644. Readable.prototype.pipe = function (dest, pipeOpts) {
  6645. var src = this;
  6646. var state = this._readableState;
  6647. switch (state.pipesCount) {
  6648. case 0:
  6649. state.pipes = dest;
  6650. break;
  6651. case 1:
  6652. state.pipes = [state.pipes, dest];
  6653. break;
  6654. default:
  6655. state.pipes.push(dest);
  6656. break;
  6657. }
  6658. state.pipesCount += 1;
  6659. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  6660. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  6661. var endFn = doEnd ? onend : unpipe;
  6662. if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
  6663. dest.on('unpipe', onunpipe);
  6664. function onunpipe(readable, unpipeInfo) {
  6665. debug('onunpipe');
  6666. if (readable === src) {
  6667. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  6668. unpipeInfo.hasUnpiped = true;
  6669. cleanup();
  6670. }
  6671. }
  6672. }
  6673. function onend() {
  6674. debug('onend');
  6675. dest.end();
  6676. }
  6677. // when the dest drains, it reduces the awaitDrain counter
  6678. // on the source. This would be more elegant with a .once()
  6679. // handler in flow(), but adding and removing repeatedly is
  6680. // too slow.
  6681. var ondrain = pipeOnDrain(src);
  6682. dest.on('drain', ondrain);
  6683. var cleanedUp = false;
  6684. function cleanup() {
  6685. debug('cleanup');
  6686. // cleanup event handlers once the pipe is broken
  6687. dest.removeListener('close', onclose);
  6688. dest.removeListener('finish', onfinish);
  6689. dest.removeListener('drain', ondrain);
  6690. dest.removeListener('error', onerror);
  6691. dest.removeListener('unpipe', onunpipe);
  6692. src.removeListener('end', onend);
  6693. src.removeListener('end', unpipe);
  6694. src.removeListener('data', ondata);
  6695. cleanedUp = true;
  6696. // if the reader is waiting for a drain event from this
  6697. // specific writer, then it would cause it to never start
  6698. // flowing again.
  6699. // So, if this is awaiting a drain, then we just call it now.
  6700. // If we don't know, then assume that we are waiting for one.
  6701. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  6702. }
  6703. // If the user pushes more data while we're writing to dest then we'll end up
  6704. // in ondata again. However, we only want to increase awaitDrain once because
  6705. // dest will only emit one 'drain' event for the multiple writes.
  6706. // => Introduce a guard on increasing awaitDrain.
  6707. var increasedAwaitDrain = false;
  6708. src.on('data', ondata);
  6709. function ondata(chunk) {
  6710. debug('ondata');
  6711. increasedAwaitDrain = false;
  6712. var ret = dest.write(chunk);
  6713. if (false === ret && !increasedAwaitDrain) {
  6714. // If the user unpiped during `dest.write()`, it is possible
  6715. // to get stuck in a permanently paused state if that write
  6716. // also returned false.
  6717. // => Check whether `dest` is still a piping destination.
  6718. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  6719. debug('false write response, pause', src._readableState.awaitDrain);
  6720. src._readableState.awaitDrain++;
  6721. increasedAwaitDrain = true;
  6722. }
  6723. src.pause();
  6724. }
  6725. }
  6726. // if the dest has an error, then stop piping into it.
  6727. // however, don't suppress the throwing behavior for this.
  6728. function onerror(er) {
  6729. debug('onerror', er);
  6730. unpipe();
  6731. dest.removeListener('error', onerror);
  6732. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  6733. }
  6734. // Make sure our error handler is attached before userland ones.
  6735. prependListener(dest, 'error', onerror);
  6736. // Both close and finish should trigger unpipe, but only once.
  6737. function onclose() {
  6738. dest.removeListener('finish', onfinish);
  6739. unpipe();
  6740. }
  6741. dest.once('close', onclose);
  6742. function onfinish() {
  6743. debug('onfinish');
  6744. dest.removeListener('close', onclose);
  6745. unpipe();
  6746. }
  6747. dest.once('finish', onfinish);
  6748. function unpipe() {
  6749. debug('unpipe');
  6750. src.unpipe(dest);
  6751. }
  6752. // tell the dest that it's being piped to
  6753. dest.emit('pipe', src);
  6754. // start the flow if it hasn't been started already.
  6755. if (!state.flowing) {
  6756. debug('pipe resume');
  6757. src.resume();
  6758. }
  6759. return dest;
  6760. };
  6761. function pipeOnDrain(src) {
  6762. return function () {
  6763. var state = src._readableState;
  6764. debug('pipeOnDrain', state.awaitDrain);
  6765. if (state.awaitDrain) state.awaitDrain--;
  6766. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  6767. state.flowing = true;
  6768. flow(src);
  6769. }
  6770. };
  6771. }
  6772. Readable.prototype.unpipe = function (dest) {
  6773. var state = this._readableState;
  6774. var unpipeInfo = { hasUnpiped: false };
  6775. // if we're not piping anywhere, then do nothing.
  6776. if (state.pipesCount === 0) return this;
  6777. // just one destination. most common case.
  6778. if (state.pipesCount === 1) {
  6779. // passed in one, but it's not the right one.
  6780. if (dest && dest !== state.pipes) return this;
  6781. if (!dest) dest = state.pipes;
  6782. // got a match.
  6783. state.pipes = null;
  6784. state.pipesCount = 0;
  6785. state.flowing = false;
  6786. if (dest) dest.emit('unpipe', this, unpipeInfo);
  6787. return this;
  6788. }
  6789. // slow case. multiple pipe destinations.
  6790. if (!dest) {
  6791. // remove all.
  6792. var dests = state.pipes;
  6793. var len = state.pipesCount;
  6794. state.pipes = null;
  6795. state.pipesCount = 0;
  6796. state.flowing = false;
  6797. for (var i = 0; i < len; i++) {
  6798. dests[i].emit('unpipe', this, unpipeInfo);
  6799. }return this;
  6800. }
  6801. // try to find the right one.
  6802. var index = indexOf(state.pipes, dest);
  6803. if (index === -1) return this;
  6804. state.pipes.splice(index, 1);
  6805. state.pipesCount -= 1;
  6806. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  6807. dest.emit('unpipe', this, unpipeInfo);
  6808. return this;
  6809. };
  6810. // set up data events if they are asked for
  6811. // Ensure readable listeners eventually get something
  6812. Readable.prototype.on = function (ev, fn) {
  6813. var res = Stream.prototype.on.call(this, ev, fn);
  6814. if (ev === 'data') {
  6815. // Start flowing on next tick if stream isn't explicitly paused
  6816. if (this._readableState.flowing !== false) this.resume();
  6817. } else if (ev === 'readable') {
  6818. var state = this._readableState;
  6819. if (!state.endEmitted && !state.readableListening) {
  6820. state.readableListening = state.needReadable = true;
  6821. state.emittedReadable = false;
  6822. if (!state.reading) {
  6823. pna.nextTick(nReadingNextTick, this);
  6824. } else if (state.length) {
  6825. emitReadable(this);
  6826. }
  6827. }
  6828. }
  6829. return res;
  6830. };
  6831. Readable.prototype.addListener = Readable.prototype.on;
  6832. function nReadingNextTick(self) {
  6833. debug('readable nexttick read 0');
  6834. self.read(0);
  6835. }
  6836. // pause() and resume() are remnants of the legacy readable stream API
  6837. // If the user uses them, then switch into old mode.
  6838. Readable.prototype.resume = function () {
  6839. var state = this._readableState;
  6840. if (!state.flowing) {
  6841. debug('resume');
  6842. state.flowing = true;
  6843. resume(this, state);
  6844. }
  6845. return this;
  6846. };
  6847. function resume(stream, state) {
  6848. if (!state.resumeScheduled) {
  6849. state.resumeScheduled = true;
  6850. pna.nextTick(resume_, stream, state);
  6851. }
  6852. }
  6853. function resume_(stream, state) {
  6854. if (!state.reading) {
  6855. debug('resume read 0');
  6856. stream.read(0);
  6857. }
  6858. state.resumeScheduled = false;
  6859. state.awaitDrain = 0;
  6860. stream.emit('resume');
  6861. flow(stream);
  6862. if (state.flowing && !state.reading) stream.read(0);
  6863. }
  6864. Readable.prototype.pause = function () {
  6865. debug('call pause flowing=%j', this._readableState.flowing);
  6866. if (false !== this._readableState.flowing) {
  6867. debug('pause');
  6868. this._readableState.flowing = false;
  6869. this.emit('pause');
  6870. }
  6871. return this;
  6872. };
  6873. function flow(stream) {
  6874. var state = stream._readableState;
  6875. debug('flow', state.flowing);
  6876. while (state.flowing && stream.read() !== null) {}
  6877. }
  6878. // wrap an old-style stream as the async data source.
  6879. // This is *not* part of the readable stream interface.
  6880. // It is an ugly unfortunate mess of history.
  6881. Readable.prototype.wrap = function (stream) {
  6882. var _this = this;
  6883. var state = this._readableState;
  6884. var paused = false;
  6885. stream.on('end', function () {
  6886. debug('wrapped end');
  6887. if (state.decoder && !state.ended) {
  6888. var chunk = state.decoder.end();
  6889. if (chunk && chunk.length) _this.push(chunk);
  6890. }
  6891. _this.push(null);
  6892. });
  6893. stream.on('data', function (chunk) {
  6894. debug('wrapped data');
  6895. if (state.decoder) chunk = state.decoder.write(chunk);
  6896. // don't skip over falsy values in objectMode
  6897. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  6898. var ret = _this.push(chunk);
  6899. if (!ret) {
  6900. paused = true;
  6901. stream.pause();
  6902. }
  6903. });
  6904. // proxy all the other methods.
  6905. // important when wrapping filters and duplexes.
  6906. for (var i in stream) {
  6907. if (this[i] === undefined && typeof stream[i] === 'function') {
  6908. this[i] = function (method) {
  6909. return function () {
  6910. return stream[method].apply(stream, arguments);
  6911. };
  6912. }(i);
  6913. }
  6914. }
  6915. // proxy certain important events.
  6916. for (var n = 0; n < kProxyEvents.length; n++) {
  6917. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  6918. }
  6919. // when we try to consume some more bytes, simply unpause the
  6920. // underlying stream.
  6921. this._read = function (n) {
  6922. debug('wrapped _read', n);
  6923. if (paused) {
  6924. paused = false;
  6925. stream.resume();
  6926. }
  6927. };
  6928. return this;
  6929. };
  6930. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  6931. // making it explicit this property is not enumerable
  6932. // because otherwise some prototype manipulation in
  6933. // userland will fail
  6934. enumerable: false,
  6935. get: function () {
  6936. return this._readableState.highWaterMark;
  6937. }
  6938. });
  6939. // exposed for testing purposes only.
  6940. Readable._fromList = fromList;
  6941. // Pluck off n bytes from an array of buffers.
  6942. // Length is the combined lengths of all the buffers in the list.
  6943. // This function is designed to be inlinable, so please take care when making
  6944. // changes to the function body.
  6945. function fromList(n, state) {
  6946. // nothing buffered
  6947. if (state.length === 0) return null;
  6948. var ret;
  6949. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  6950. // read it all, truncate the list
  6951. 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);
  6952. state.buffer.clear();
  6953. } else {
  6954. // read part of list
  6955. ret = fromListPartial(n, state.buffer, state.decoder);
  6956. }
  6957. return ret;
  6958. }
  6959. // Extracts only enough buffered data to satisfy the amount requested.
  6960. // This function is designed to be inlinable, so please take care when making
  6961. // changes to the function body.
  6962. function fromListPartial(n, list, hasStrings) {
  6963. var ret;
  6964. if (n < list.head.data.length) {
  6965. // slice is the same for buffers and strings
  6966. ret = list.head.data.slice(0, n);
  6967. list.head.data = list.head.data.slice(n);
  6968. } else if (n === list.head.data.length) {
  6969. // first chunk is a perfect match
  6970. ret = list.shift();
  6971. } else {
  6972. // result spans more than one buffer
  6973. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  6974. }
  6975. return ret;
  6976. }
  6977. // Copies a specified amount of characters from the list of buffered data
  6978. // chunks.
  6979. // This function is designed to be inlinable, so please take care when making
  6980. // changes to the function body.
  6981. function copyFromBufferString(n, list) {
  6982. var p = list.head;
  6983. var c = 1;
  6984. var ret = p.data;
  6985. n -= ret.length;
  6986. while (p = p.next) {
  6987. var str = p.data;
  6988. var nb = n > str.length ? str.length : n;
  6989. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  6990. n -= nb;
  6991. if (n === 0) {
  6992. if (nb === str.length) {
  6993. ++c;
  6994. if (p.next) list.head = p.next;else list.head = list.tail = null;
  6995. } else {
  6996. list.head = p;
  6997. p.data = str.slice(nb);
  6998. }
  6999. break;
  7000. }
  7001. ++c;
  7002. }
  7003. list.length -= c;
  7004. return ret;
  7005. }
  7006. // Copies a specified amount of bytes from the list of buffered data chunks.
  7007. // This function is designed to be inlinable, so please take care when making
  7008. // changes to the function body.
  7009. function copyFromBuffer(n, list) {
  7010. var ret = Buffer.allocUnsafe(n);
  7011. var p = list.head;
  7012. var c = 1;
  7013. p.data.copy(ret);
  7014. n -= p.data.length;
  7015. while (p = p.next) {
  7016. var buf = p.data;
  7017. var nb = n > buf.length ? buf.length : n;
  7018. buf.copy(ret, ret.length - n, 0, nb);
  7019. n -= nb;
  7020. if (n === 0) {
  7021. if (nb === buf.length) {
  7022. ++c;
  7023. if (p.next) list.head = p.next;else list.head = list.tail = null;
  7024. } else {
  7025. list.head = p;
  7026. p.data = buf.slice(nb);
  7027. }
  7028. break;
  7029. }
  7030. ++c;
  7031. }
  7032. list.length -= c;
  7033. return ret;
  7034. }
  7035. function endReadable(stream) {
  7036. var state = stream._readableState;
  7037. // If we get here before consuming all the bytes, then that is a
  7038. // bug in node. Should never happen.
  7039. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  7040. if (!state.endEmitted) {
  7041. state.ended = true;
  7042. pna.nextTick(endReadableNT, state, stream);
  7043. }
  7044. }
  7045. function endReadableNT(state, stream) {
  7046. // Check that we didn't get one last unshift.
  7047. if (!state.endEmitted && state.length === 0) {
  7048. state.endEmitted = true;
  7049. stream.readable = false;
  7050. stream.emit('end');
  7051. }
  7052. }
  7053. function indexOf(xs, x) {
  7054. for (var i = 0, l = xs.length; i < l; i++) {
  7055. if (xs[i] === x) return i;
  7056. }
  7057. return -1;
  7058. }
  7059. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  7060. },{"./_stream_duplex":36,"./internal/streams/BufferList":41,"./internal/streams/destroy":42,"./internal/streams/stream":43,"_process":30,"core-util-is":14,"events":12,"inherits":18,"isarray":20,"process-nextick-args":44,"safe-buffer":47,"string_decoder/":49,"util":11}],39:[function(require,module,exports){
  7061. // Copyright Joyent, Inc. and other Node contributors.
  7062. //
  7063. // Permission is hereby granted, free of charge, to any person obtaining a
  7064. // copy of this software and associated documentation files (the
  7065. // "Software"), to deal in the Software without restriction, including
  7066. // without limitation the rights to use, copy, modify, merge, publish,
  7067. // distribute, sublicense, and/or sell copies of the Software, and to permit
  7068. // persons to whom the Software is furnished to do so, subject to the
  7069. // following conditions:
  7070. //
  7071. // The above copyright notice and this permission notice shall be included
  7072. // in all copies or substantial portions of the Software.
  7073. //
  7074. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  7075. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7076. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  7077. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  7078. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  7079. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  7080. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  7081. // a transform stream is a readable/writable stream where you do
  7082. // something with the data. Sometimes it's called a "filter",
  7083. // but that's not a great name for it, since that implies a thing where
  7084. // some bits pass through, and others are simply ignored. (That would
  7085. // be a valid example of a transform, of course.)
  7086. //
  7087. // While the output is causally related to the input, it's not a
  7088. // necessarily symmetric or synchronous transformation. For example,
  7089. // a zlib stream might take multiple plain-text writes(), and then
  7090. // emit a single compressed chunk some time in the future.
  7091. //
  7092. // Here's how this works:
  7093. //
  7094. // The Transform stream has all the aspects of the readable and writable
  7095. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  7096. // internally, and returns false if there's a lot of pending writes
  7097. // buffered up. When you call read(), that calls _read(n) until
  7098. // there's enough pending readable data buffered up.
  7099. //
  7100. // In a transform stream, the written data is placed in a buffer. When
  7101. // _read(n) is called, it transforms the queued up data, calling the
  7102. // buffered _write cb's as it consumes chunks. If consuming a single
  7103. // written chunk would result in multiple output chunks, then the first
  7104. // outputted bit calls the readcb, and subsequent chunks just go into
  7105. // the read buffer, and will cause it to emit 'readable' if necessary.
  7106. //
  7107. // This way, back-pressure is actually determined by the reading side,
  7108. // since _read has to be called to start processing a new chunk. However,
  7109. // a pathological inflate type of transform can cause excessive buffering
  7110. // here. For example, imagine a stream where every byte of input is
  7111. // interpreted as an integer from 0-255, and then results in that many
  7112. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  7113. // 1kb of data being output. In this case, you could write a very small
  7114. // amount of input, and end up with a very large amount of output. In
  7115. // such a pathological inflating mechanism, there'd be no way to tell
  7116. // the system to stop doing the transform. A single 4MB write could
  7117. // cause the system to run out of memory.
  7118. //
  7119. // However, even in such a pathological case, only a single written chunk
  7120. // would be consumed, and then the rest would wait (un-transformed) until
  7121. // the results of the previous transformed chunk were consumed.
  7122. 'use strict';
  7123. module.exports = Transform;
  7124. var Duplex = require('./_stream_duplex');
  7125. /*<replacement>*/
  7126. var util = require('core-util-is');
  7127. util.inherits = require('inherits');
  7128. /*</replacement>*/
  7129. util.inherits(Transform, Duplex);
  7130. function afterTransform(er, data) {
  7131. var ts = this._transformState;
  7132. ts.transforming = false;
  7133. var cb = ts.writecb;
  7134. if (!cb) {
  7135. return this.emit('error', new Error('write callback called multiple times'));
  7136. }
  7137. ts.writechunk = null;
  7138. ts.writecb = null;
  7139. if (data != null) // single equals check for both `null` and `undefined`
  7140. this.push(data);
  7141. cb(er);
  7142. var rs = this._readableState;
  7143. rs.reading = false;
  7144. if (rs.needReadable || rs.length < rs.highWaterMark) {
  7145. this._read(rs.highWaterMark);
  7146. }
  7147. }
  7148. function Transform(options) {
  7149. if (!(this instanceof Transform)) return new Transform(options);
  7150. Duplex.call(this, options);
  7151. this._transformState = {
  7152. afterTransform: afterTransform.bind(this),
  7153. needTransform: false,
  7154. transforming: false,
  7155. writecb: null,
  7156. writechunk: null,
  7157. writeencoding: null
  7158. };
  7159. // start out asking for a readable event once data is transformed.
  7160. this._readableState.needReadable = true;
  7161. // we have implemented the _read method, and done the other things
  7162. // that Readable wants before the first _read call, so unset the
  7163. // sync guard flag.
  7164. this._readableState.sync = false;
  7165. if (options) {
  7166. if (typeof options.transform === 'function') this._transform = options.transform;
  7167. if (typeof options.flush === 'function') this._flush = options.flush;
  7168. }
  7169. // When the writable side finishes, then flush out anything remaining.
  7170. this.on('prefinish', prefinish);
  7171. }
  7172. function prefinish() {
  7173. var _this = this;
  7174. if (typeof this._flush === 'function') {
  7175. this._flush(function (er, data) {
  7176. done(_this, er, data);
  7177. });
  7178. } else {
  7179. done(this, null, null);
  7180. }
  7181. }
  7182. Transform.prototype.push = function (chunk, encoding) {
  7183. this._transformState.needTransform = false;
  7184. return Duplex.prototype.push.call(this, chunk, encoding);
  7185. };
  7186. // This is the part where you do stuff!
  7187. // override this function in implementation classes.
  7188. // 'chunk' is an input chunk.
  7189. //
  7190. // Call `push(newChunk)` to pass along transformed output
  7191. // to the readable side. You may call 'push' zero or more times.
  7192. //
  7193. // Call `cb(err)` when you are done with this chunk. If you pass
  7194. // an error, then that'll put the hurt on the whole operation. If you
  7195. // never call cb(), then you'll never get another chunk.
  7196. Transform.prototype._transform = function (chunk, encoding, cb) {
  7197. throw new Error('_transform() is not implemented');
  7198. };
  7199. Transform.prototype._write = function (chunk, encoding, cb) {
  7200. var ts = this._transformState;
  7201. ts.writecb = cb;
  7202. ts.writechunk = chunk;
  7203. ts.writeencoding = encoding;
  7204. if (!ts.transforming) {
  7205. var rs = this._readableState;
  7206. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  7207. }
  7208. };
  7209. // Doesn't matter what the args are here.
  7210. // _transform does all the work.
  7211. // That we got here means that the readable side wants more data.
  7212. Transform.prototype._read = function (n) {
  7213. var ts = this._transformState;
  7214. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  7215. ts.transforming = true;
  7216. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  7217. } else {
  7218. // mark that we need a transform, so that any data that comes in
  7219. // will get processed, now that we've asked for it.
  7220. ts.needTransform = true;
  7221. }
  7222. };
  7223. Transform.prototype._destroy = function (err, cb) {
  7224. var _this2 = this;
  7225. Duplex.prototype._destroy.call(this, err, function (err2) {
  7226. cb(err2);
  7227. _this2.emit('close');
  7228. });
  7229. };
  7230. function done(stream, er, data) {
  7231. if (er) return stream.emit('error', er);
  7232. if (data != null) // single equals check for both `null` and `undefined`
  7233. stream.push(data);
  7234. // if there's nothing in the write buffer, then that means
  7235. // that nothing more will ever be provided
  7236. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  7237. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  7238. return stream.push(null);
  7239. }
  7240. },{"./_stream_duplex":36,"core-util-is":14,"inherits":18}],40:[function(require,module,exports){
  7241. (function (process,global){
  7242. // Copyright Joyent, Inc. and other Node contributors.
  7243. //
  7244. // Permission is hereby granted, free of charge, to any person obtaining a
  7245. // copy of this software and associated documentation files (the
  7246. // "Software"), to deal in the Software without restriction, including
  7247. // without limitation the rights to use, copy, modify, merge, publish,
  7248. // distribute, sublicense, and/or sell copies of the Software, and to permit
  7249. // persons to whom the Software is furnished to do so, subject to the
  7250. // following conditions:
  7251. //
  7252. // The above copyright notice and this permission notice shall be included
  7253. // in all copies or substantial portions of the Software.
  7254. //
  7255. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  7256. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7257. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  7258. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  7259. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  7260. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  7261. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  7262. // A bit simpler than readable streams.
  7263. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  7264. // the drain event emission and buffering.
  7265. 'use strict';
  7266. /*<replacement>*/
  7267. var pna = require('process-nextick-args');
  7268. /*</replacement>*/
  7269. module.exports = Writable;
  7270. /* <replacement> */
  7271. function WriteReq(chunk, encoding, cb) {
  7272. this.chunk = chunk;
  7273. this.encoding = encoding;
  7274. this.callback = cb;
  7275. this.next = null;
  7276. }
  7277. // It seems a linked list but it is not
  7278. // there will be only 2 of these for each stream
  7279. function CorkedRequest(state) {
  7280. var _this = this;
  7281. this.next = null;
  7282. this.entry = null;
  7283. this.finish = function () {
  7284. onCorkedFinish(_this, state);
  7285. };
  7286. }
  7287. /* </replacement> */
  7288. /*<replacement>*/
  7289. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  7290. /*</replacement>*/
  7291. /*<replacement>*/
  7292. var Duplex;
  7293. /*</replacement>*/
  7294. Writable.WritableState = WritableState;
  7295. /*<replacement>*/
  7296. var util = require('core-util-is');
  7297. util.inherits = require('inherits');
  7298. /*</replacement>*/
  7299. /*<replacement>*/
  7300. var internalUtil = {
  7301. deprecate: require('util-deprecate')
  7302. };
  7303. /*</replacement>*/
  7304. /*<replacement>*/
  7305. var Stream = require('./internal/streams/stream');
  7306. /*</replacement>*/
  7307. /*<replacement>*/
  7308. var Buffer = require('safe-buffer').Buffer;
  7309. var OurUint8Array = global.Uint8Array || function () {};
  7310. function _uint8ArrayToBuffer(chunk) {
  7311. return Buffer.from(chunk);
  7312. }
  7313. function _isUint8Array(obj) {
  7314. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  7315. }
  7316. /*</replacement>*/
  7317. var destroyImpl = require('./internal/streams/destroy');
  7318. util.inherits(Writable, Stream);
  7319. function nop() {}
  7320. function WritableState(options, stream) {
  7321. Duplex = Duplex || require('./_stream_duplex');
  7322. options = options || {};
  7323. // Duplex streams are both readable and writable, but share
  7324. // the same options object.
  7325. // However, some cases require setting options to different
  7326. // values for the readable and the writable sides of the duplex stream.
  7327. // These options can be provided separately as readableXXX and writableXXX.
  7328. var isDuplex = stream instanceof Duplex;
  7329. // object stream flag to indicate whether or not this stream
  7330. // contains buffers or objects.
  7331. this.objectMode = !!options.objectMode;
  7332. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  7333. // the point at which write() starts returning false
  7334. // Note: 0 is a valid value, means that we always return false if
  7335. // the entire buffer is not flushed immediately on write()
  7336. var hwm = options.highWaterMark;
  7337. var writableHwm = options.writableHighWaterMark;
  7338. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  7339. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
  7340. // cast to ints.
  7341. this.highWaterMark = Math.floor(this.highWaterMark);
  7342. // if _final has been called
  7343. this.finalCalled = false;
  7344. // drain event flag.
  7345. this.needDrain = false;
  7346. // at the start of calling end()
  7347. this.ending = false;
  7348. // when end() has been called, and returned
  7349. this.ended = false;
  7350. // when 'finish' is emitted
  7351. this.finished = false;
  7352. // has it been destroyed
  7353. this.destroyed = false;
  7354. // should we decode strings into buffers before passing to _write?
  7355. // this is here so that some node-core streams can optimize string
  7356. // handling at a lower level.
  7357. var noDecode = options.decodeStrings === false;
  7358. this.decodeStrings = !noDecode;
  7359. // Crypto is kind of old and crusty. Historically, its default string
  7360. // encoding is 'binary' so we have to make this configurable.
  7361. // Everything else in the universe uses 'utf8', though.
  7362. this.defaultEncoding = options.defaultEncoding || 'utf8';
  7363. // not an actual buffer we keep track of, but a measurement
  7364. // of how much we're waiting to get pushed to some underlying
  7365. // socket or file.
  7366. this.length = 0;
  7367. // a flag to see when we're in the middle of a write.
  7368. this.writing = false;
  7369. // when true all writes will be buffered until .uncork() call
  7370. this.corked = 0;
  7371. // a flag to be able to tell if the onwrite cb is called immediately,
  7372. // or on a later tick. We set this to true at first, because any
  7373. // actions that shouldn't happen until "later" should generally also
  7374. // not happen before the first write call.
  7375. this.sync = true;
  7376. // a flag to know if we're processing previously buffered items, which
  7377. // may call the _write() callback in the same tick, so that we don't
  7378. // end up in an overlapped onwrite situation.
  7379. this.bufferProcessing = false;
  7380. // the callback that's passed to _write(chunk,cb)
  7381. this.onwrite = function (er) {
  7382. onwrite(stream, er);
  7383. };
  7384. // the callback that the user supplies to write(chunk,encoding,cb)
  7385. this.writecb = null;
  7386. // the amount that is being written when _write is called.
  7387. this.writelen = 0;
  7388. this.bufferedRequest = null;
  7389. this.lastBufferedRequest = null;
  7390. // number of pending user-supplied write callbacks
  7391. // this must be 0 before 'finish' can be emitted
  7392. this.pendingcb = 0;
  7393. // emit prefinish if the only thing we're waiting for is _write cbs
  7394. // This is relevant for synchronous Transform streams
  7395. this.prefinished = false;
  7396. // True if the error was already emitted and should not be thrown again
  7397. this.errorEmitted = false;
  7398. // count buffered requests
  7399. this.bufferedRequestCount = 0;
  7400. // allocate the first CorkedRequest, there is always
  7401. // one allocated and free to use, and we maintain at most two
  7402. this.corkedRequestsFree = new CorkedRequest(this);
  7403. }
  7404. WritableState.prototype.getBuffer = function getBuffer() {
  7405. var current = this.bufferedRequest;
  7406. var out = [];
  7407. while (current) {
  7408. out.push(current);
  7409. current = current.next;
  7410. }
  7411. return out;
  7412. };
  7413. (function () {
  7414. try {
  7415. Object.defineProperty(WritableState.prototype, 'buffer', {
  7416. get: internalUtil.deprecate(function () {
  7417. return this.getBuffer();
  7418. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  7419. });
  7420. } catch (_) {}
  7421. })();
  7422. // Test _writableState for inheritance to account for Duplex streams,
  7423. // whose prototype chain only points to Readable.
  7424. var realHasInstance;
  7425. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  7426. realHasInstance = Function.prototype[Symbol.hasInstance];
  7427. Object.defineProperty(Writable, Symbol.hasInstance, {
  7428. value: function (object) {
  7429. if (realHasInstance.call(this, object)) return true;
  7430. if (this !== Writable) return false;
  7431. return object && object._writableState instanceof WritableState;
  7432. }
  7433. });
  7434. } else {
  7435. realHasInstance = function (object) {
  7436. return object instanceof this;
  7437. };
  7438. }
  7439. function Writable(options) {
  7440. Duplex = Duplex || require('./_stream_duplex');
  7441. // Writable ctor is applied to Duplexes, too.
  7442. // `realHasInstance` is necessary because using plain `instanceof`
  7443. // would return false, as no `_writableState` property is attached.
  7444. // Trying to use the custom `instanceof` for Writable here will also break the
  7445. // Node.js LazyTransform implementation, which has a non-trivial getter for
  7446. // `_writableState` that would lead to infinite recursion.
  7447. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  7448. return new Writable(options);
  7449. }
  7450. this._writableState = new WritableState(options, this);
  7451. // legacy.
  7452. this.writable = true;
  7453. if (options) {
  7454. if (typeof options.write === 'function') this._write = options.write;
  7455. if (typeof options.writev === 'function') this._writev = options.writev;
  7456. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  7457. if (typeof options.final === 'function') this._final = options.final;
  7458. }
  7459. Stream.call(this);
  7460. }
  7461. // Otherwise people can pipe Writable streams, which is just wrong.
  7462. Writable.prototype.pipe = function () {
  7463. this.emit('error', new Error('Cannot pipe, not readable'));
  7464. };
  7465. function writeAfterEnd(stream, cb) {
  7466. var er = new Error('write after end');
  7467. // TODO: defer error events consistently everywhere, not just the cb
  7468. stream.emit('error', er);
  7469. pna.nextTick(cb, er);
  7470. }
  7471. // Checks that a user-supplied chunk is valid, especially for the particular
  7472. // mode the stream is in. Currently this means that `null` is never accepted
  7473. // and undefined/non-string values are only allowed in object mode.
  7474. function validChunk(stream, state, chunk, cb) {
  7475. var valid = true;
  7476. var er = false;
  7477. if (chunk === null) {
  7478. er = new TypeError('May not write null values to stream');
  7479. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  7480. er = new TypeError('Invalid non-string/buffer chunk');
  7481. }
  7482. if (er) {
  7483. stream.emit('error', er);
  7484. pna.nextTick(cb, er);
  7485. valid = false;
  7486. }
  7487. return valid;
  7488. }
  7489. Writable.prototype.write = function (chunk, encoding, cb) {
  7490. var state = this._writableState;
  7491. var ret = false;
  7492. var isBuf = !state.objectMode && _isUint8Array(chunk);
  7493. if (isBuf && !Buffer.isBuffer(chunk)) {
  7494. chunk = _uint8ArrayToBuffer(chunk);
  7495. }
  7496. if (typeof encoding === 'function') {
  7497. cb = encoding;
  7498. encoding = null;
  7499. }
  7500. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  7501. if (typeof cb !== 'function') cb = nop;
  7502. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  7503. state.pendingcb++;
  7504. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  7505. }
  7506. return ret;
  7507. };
  7508. Writable.prototype.cork = function () {
  7509. var state = this._writableState;
  7510. state.corked++;
  7511. };
  7512. Writable.prototype.uncork = function () {
  7513. var state = this._writableState;
  7514. if (state.corked) {
  7515. state.corked--;
  7516. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  7517. }
  7518. };
  7519. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  7520. // node::ParseEncoding() requires lower case.
  7521. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  7522. 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);
  7523. this._writableState.defaultEncoding = encoding;
  7524. return this;
  7525. };
  7526. function decodeChunk(state, chunk, encoding) {
  7527. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  7528. chunk = Buffer.from(chunk, encoding);
  7529. }
  7530. return chunk;
  7531. }
  7532. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  7533. // making it explicit this property is not enumerable
  7534. // because otherwise some prototype manipulation in
  7535. // userland will fail
  7536. enumerable: false,
  7537. get: function () {
  7538. return this._writableState.highWaterMark;
  7539. }
  7540. });
  7541. // if we're already writing something, then just put this
  7542. // in the queue, and wait our turn. Otherwise, call _write
  7543. // If we return false, then we need a drain event, so set that flag.
  7544. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  7545. if (!isBuf) {
  7546. var newChunk = decodeChunk(state, chunk, encoding);
  7547. if (chunk !== newChunk) {
  7548. isBuf = true;
  7549. encoding = 'buffer';
  7550. chunk = newChunk;
  7551. }
  7552. }
  7553. var len = state.objectMode ? 1 : chunk.length;
  7554. state.length += len;
  7555. var ret = state.length < state.highWaterMark;
  7556. // we must ensure that previous needDrain will not be reset to false.
  7557. if (!ret) state.needDrain = true;
  7558. if (state.writing || state.corked) {
  7559. var last = state.lastBufferedRequest;
  7560. state.lastBufferedRequest = {
  7561. chunk: chunk,
  7562. encoding: encoding,
  7563. isBuf: isBuf,
  7564. callback: cb,
  7565. next: null
  7566. };
  7567. if (last) {
  7568. last.next = state.lastBufferedRequest;
  7569. } else {
  7570. state.bufferedRequest = state.lastBufferedRequest;
  7571. }
  7572. state.bufferedRequestCount += 1;
  7573. } else {
  7574. doWrite(stream, state, false, len, chunk, encoding, cb);
  7575. }
  7576. return ret;
  7577. }
  7578. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  7579. state.writelen = len;
  7580. state.writecb = cb;
  7581. state.writing = true;
  7582. state.sync = true;
  7583. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  7584. state.sync = false;
  7585. }
  7586. function onwriteError(stream, state, sync, er, cb) {
  7587. --state.pendingcb;
  7588. if (sync) {
  7589. // defer the callback if we are being called synchronously
  7590. // to avoid piling up things on the stack
  7591. pna.nextTick(cb, er);
  7592. // this can emit finish, and it will always happen
  7593. // after error
  7594. pna.nextTick(finishMaybe, stream, state);
  7595. stream._writableState.errorEmitted = true;
  7596. stream.emit('error', er);
  7597. } else {
  7598. // the caller expect this to happen before if
  7599. // it is async
  7600. cb(er);
  7601. stream._writableState.errorEmitted = true;
  7602. stream.emit('error', er);
  7603. // this can emit finish, but finish must
  7604. // always follow error
  7605. finishMaybe(stream, state);
  7606. }
  7607. }
  7608. function onwriteStateUpdate(state) {
  7609. state.writing = false;
  7610. state.writecb = null;
  7611. state.length -= state.writelen;
  7612. state.writelen = 0;
  7613. }
  7614. function onwrite(stream, er) {
  7615. var state = stream._writableState;
  7616. var sync = state.sync;
  7617. var cb = state.writecb;
  7618. onwriteStateUpdate(state);
  7619. if (er) onwriteError(stream, state, sync, er, cb);else {
  7620. // Check if we're actually ready to finish, but don't emit yet
  7621. var finished = needFinish(state);
  7622. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  7623. clearBuffer(stream, state);
  7624. }
  7625. if (sync) {
  7626. /*<replacement>*/
  7627. asyncWrite(afterWrite, stream, state, finished, cb);
  7628. /*</replacement>*/
  7629. } else {
  7630. afterWrite(stream, state, finished, cb);
  7631. }
  7632. }
  7633. }
  7634. function afterWrite(stream, state, finished, cb) {
  7635. if (!finished) onwriteDrain(stream, state);
  7636. state.pendingcb--;
  7637. cb();
  7638. finishMaybe(stream, state);
  7639. }
  7640. // Must force callback to be called on nextTick, so that we don't
  7641. // emit 'drain' before the write() consumer gets the 'false' return
  7642. // value, and has a chance to attach a 'drain' listener.
  7643. function onwriteDrain(stream, state) {
  7644. if (state.length === 0 && state.needDrain) {
  7645. state.needDrain = false;
  7646. stream.emit('drain');
  7647. }
  7648. }
  7649. // if there's something in the buffer waiting, then process it
  7650. function clearBuffer(stream, state) {
  7651. state.bufferProcessing = true;
  7652. var entry = state.bufferedRequest;
  7653. if (stream._writev && entry && entry.next) {
  7654. // Fast case, write everything using _writev()
  7655. var l = state.bufferedRequestCount;
  7656. var buffer = new Array(l);
  7657. var holder = state.corkedRequestsFree;
  7658. holder.entry = entry;
  7659. var count = 0;
  7660. var allBuffers = true;
  7661. while (entry) {
  7662. buffer[count] = entry;
  7663. if (!entry.isBuf) allBuffers = false;
  7664. entry = entry.next;
  7665. count += 1;
  7666. }
  7667. buffer.allBuffers = allBuffers;
  7668. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  7669. // doWrite is almost always async, defer these to save a bit of time
  7670. // as the hot path ends with doWrite
  7671. state.pendingcb++;
  7672. state.lastBufferedRequest = null;
  7673. if (holder.next) {
  7674. state.corkedRequestsFree = holder.next;
  7675. holder.next = null;
  7676. } else {
  7677. state.corkedRequestsFree = new CorkedRequest(state);
  7678. }
  7679. state.bufferedRequestCount = 0;
  7680. } else {
  7681. // Slow case, write chunks one-by-one
  7682. while (entry) {
  7683. var chunk = entry.chunk;
  7684. var encoding = entry.encoding;
  7685. var cb = entry.callback;
  7686. var len = state.objectMode ? 1 : chunk.length;
  7687. doWrite(stream, state, false, len, chunk, encoding, cb);
  7688. entry = entry.next;
  7689. state.bufferedRequestCount--;
  7690. // if we didn't call the onwrite immediately, then
  7691. // it means that we need to wait until it does.
  7692. // also, that means that the chunk and cb are currently
  7693. // being processed, so move the buffer counter past them.
  7694. if (state.writing) {
  7695. break;
  7696. }
  7697. }
  7698. if (entry === null) state.lastBufferedRequest = null;
  7699. }
  7700. state.bufferedRequest = entry;
  7701. state.bufferProcessing = false;
  7702. }
  7703. Writable.prototype._write = function (chunk, encoding, cb) {
  7704. cb(new Error('_write() is not implemented'));
  7705. };
  7706. Writable.prototype._writev = null;
  7707. Writable.prototype.end = function (chunk, encoding, cb) {
  7708. var state = this._writableState;
  7709. if (typeof chunk === 'function') {
  7710. cb = chunk;
  7711. chunk = null;
  7712. encoding = null;
  7713. } else if (typeof encoding === 'function') {
  7714. cb = encoding;
  7715. encoding = null;
  7716. }
  7717. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  7718. // .end() fully uncorks
  7719. if (state.corked) {
  7720. state.corked = 1;
  7721. this.uncork();
  7722. }
  7723. // ignore unnecessary end() calls.
  7724. if (!state.ending && !state.finished) endWritable(this, state, cb);
  7725. };
  7726. function needFinish(state) {
  7727. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  7728. }
  7729. function callFinal(stream, state) {
  7730. stream._final(function (err) {
  7731. state.pendingcb--;
  7732. if (err) {
  7733. stream.emit('error', err);
  7734. }
  7735. state.prefinished = true;
  7736. stream.emit('prefinish');
  7737. finishMaybe(stream, state);
  7738. });
  7739. }
  7740. function prefinish(stream, state) {
  7741. if (!state.prefinished && !state.finalCalled) {
  7742. if (typeof stream._final === 'function') {
  7743. state.pendingcb++;
  7744. state.finalCalled = true;
  7745. pna.nextTick(callFinal, stream, state);
  7746. } else {
  7747. state.prefinished = true;
  7748. stream.emit('prefinish');
  7749. }
  7750. }
  7751. }
  7752. function finishMaybe(stream, state) {
  7753. var need = needFinish(state);
  7754. if (need) {
  7755. prefinish(stream, state);
  7756. if (state.pendingcb === 0) {
  7757. state.finished = true;
  7758. stream.emit('finish');
  7759. }
  7760. }
  7761. return need;
  7762. }
  7763. function endWritable(stream, state, cb) {
  7764. state.ending = true;
  7765. finishMaybe(stream, state);
  7766. if (cb) {
  7767. if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  7768. }
  7769. state.ended = true;
  7770. stream.writable = false;
  7771. }
  7772. function onCorkedFinish(corkReq, state, err) {
  7773. var entry = corkReq.entry;
  7774. corkReq.entry = null;
  7775. while (entry) {
  7776. var cb = entry.callback;
  7777. state.pendingcb--;
  7778. cb(err);
  7779. entry = entry.next;
  7780. }
  7781. if (state.corkedRequestsFree) {
  7782. state.corkedRequestsFree.next = corkReq;
  7783. } else {
  7784. state.corkedRequestsFree = corkReq;
  7785. }
  7786. }
  7787. Object.defineProperty(Writable.prototype, 'destroyed', {
  7788. get: function () {
  7789. if (this._writableState === undefined) {
  7790. return false;
  7791. }
  7792. return this._writableState.destroyed;
  7793. },
  7794. set: function (value) {
  7795. // we ignore the value if the stream
  7796. // has not been initialized yet
  7797. if (!this._writableState) {
  7798. return;
  7799. }
  7800. // backward compatibility, the user is explicitly
  7801. // managing destroyed
  7802. this._writableState.destroyed = value;
  7803. }
  7804. });
  7805. Writable.prototype.destroy = destroyImpl.destroy;
  7806. Writable.prototype._undestroy = destroyImpl.undestroy;
  7807. Writable.prototype._destroy = function (err, cb) {
  7808. this.end();
  7809. cb(err);
  7810. };
  7811. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  7812. },{"./_stream_duplex":36,"./internal/streams/destroy":42,"./internal/streams/stream":43,"_process":30,"core-util-is":14,"inherits":18,"process-nextick-args":44,"safe-buffer":47,"util-deprecate":52}],41:[function(require,module,exports){
  7813. 'use strict';
  7814. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7815. var Buffer = require('safe-buffer').Buffer;
  7816. var util = require('util');
  7817. function copyBuffer(src, target, offset) {
  7818. src.copy(target, offset);
  7819. }
  7820. module.exports = function () {
  7821. function BufferList() {
  7822. _classCallCheck(this, BufferList);
  7823. this.head = null;
  7824. this.tail = null;
  7825. this.length = 0;
  7826. }
  7827. BufferList.prototype.push = function push(v) {
  7828. var entry = { data: v, next: null };
  7829. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  7830. this.tail = entry;
  7831. ++this.length;
  7832. };
  7833. BufferList.prototype.unshift = function unshift(v) {
  7834. var entry = { data: v, next: this.head };
  7835. if (this.length === 0) this.tail = entry;
  7836. this.head = entry;
  7837. ++this.length;
  7838. };
  7839. BufferList.prototype.shift = function shift() {
  7840. if (this.length === 0) return;
  7841. var ret = this.head.data;
  7842. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  7843. --this.length;
  7844. return ret;
  7845. };
  7846. BufferList.prototype.clear = function clear() {
  7847. this.head = this.tail = null;
  7848. this.length = 0;
  7849. };
  7850. BufferList.prototype.join = function join(s) {
  7851. if (this.length === 0) return '';
  7852. var p = this.head;
  7853. var ret = '' + p.data;
  7854. while (p = p.next) {
  7855. ret += s + p.data;
  7856. }return ret;
  7857. };
  7858. BufferList.prototype.concat = function concat(n) {
  7859. if (this.length === 0) return Buffer.alloc(0);
  7860. if (this.length === 1) return this.head.data;
  7861. var ret = Buffer.allocUnsafe(n >>> 0);
  7862. var p = this.head;
  7863. var i = 0;
  7864. while (p) {
  7865. copyBuffer(p.data, ret, i);
  7866. i += p.data.length;
  7867. p = p.next;
  7868. }
  7869. return ret;
  7870. };
  7871. return BufferList;
  7872. }();
  7873. if (util && util.inspect && util.inspect.custom) {
  7874. module.exports.prototype[util.inspect.custom] = function () {
  7875. var obj = util.inspect({ length: this.length });
  7876. return this.constructor.name + ' ' + obj;
  7877. };
  7878. }
  7879. },{"safe-buffer":47,"util":11}],42:[function(require,module,exports){
  7880. 'use strict';
  7881. /*<replacement>*/
  7882. var pna = require('process-nextick-args');
  7883. /*</replacement>*/
  7884. // undocumented cb() API, needed for core, not for public API
  7885. function destroy(err, cb) {
  7886. var _this = this;
  7887. var readableDestroyed = this._readableState && this._readableState.destroyed;
  7888. var writableDestroyed = this._writableState && this._writableState.destroyed;
  7889. if (readableDestroyed || writableDestroyed) {
  7890. if (cb) {
  7891. cb(err);
  7892. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  7893. pna.nextTick(emitErrorNT, this, err);
  7894. }
  7895. return this;
  7896. }
  7897. // we set destroyed to true before firing error callbacks in order
  7898. // to make it re-entrance safe in case destroy() is called within callbacks
  7899. if (this._readableState) {
  7900. this._readableState.destroyed = true;
  7901. }
  7902. // if this is a duplex stream mark the writable part as destroyed as well
  7903. if (this._writableState) {
  7904. this._writableState.destroyed = true;
  7905. }
  7906. this._destroy(err || null, function (err) {
  7907. if (!cb && err) {
  7908. pna.nextTick(emitErrorNT, _this, err);
  7909. if (_this._writableState) {
  7910. _this._writableState.errorEmitted = true;
  7911. }
  7912. } else if (cb) {
  7913. cb(err);
  7914. }
  7915. });
  7916. return this;
  7917. }
  7918. function undestroy() {
  7919. if (this._readableState) {
  7920. this._readableState.destroyed = false;
  7921. this._readableState.reading = false;
  7922. this._readableState.ended = false;
  7923. this._readableState.endEmitted = false;
  7924. }
  7925. if (this._writableState) {
  7926. this._writableState.destroyed = false;
  7927. this._writableState.ended = false;
  7928. this._writableState.ending = false;
  7929. this._writableState.finished = false;
  7930. this._writableState.errorEmitted = false;
  7931. }
  7932. }
  7933. function emitErrorNT(self, err) {
  7934. self.emit('error', err);
  7935. }
  7936. module.exports = {
  7937. destroy: destroy,
  7938. undestroy: undestroy
  7939. };
  7940. },{"process-nextick-args":44}],43:[function(require,module,exports){
  7941. module.exports = require('events').EventEmitter;
  7942. },{"events":12}],44:[function(require,module,exports){
  7943. arguments[4][24][0].apply(exports,arguments)
  7944. },{"_process":30,"dup":24}],45:[function(require,module,exports){
  7945. exports = module.exports = require('./lib/_stream_readable.js');
  7946. exports.Stream = exports;
  7947. exports.Readable = exports;
  7948. exports.Writable = require('./lib/_stream_writable.js');
  7949. exports.Duplex = require('./lib/_stream_duplex.js');
  7950. exports.Transform = require('./lib/_stream_transform.js');
  7951. exports.PassThrough = require('./lib/_stream_passthrough.js');
  7952. },{"./lib/_stream_duplex.js":36,"./lib/_stream_passthrough.js":37,"./lib/_stream_readable.js":38,"./lib/_stream_transform.js":39,"./lib/_stream_writable.js":40}],46:[function(require,module,exports){
  7953. 'use strict'
  7954. function ReInterval (callback, interval, args) {
  7955. var self = this;
  7956. this._callback = callback;
  7957. this._args = args;
  7958. this._interval = setInterval(callback, interval, this._args);
  7959. this.reschedule = function (interval) {
  7960. // if no interval entered, use the interval passed in on creation
  7961. if (!interval)
  7962. interval = self._interval;
  7963. if (self._interval)
  7964. clearInterval(self._interval);
  7965. self._interval = setInterval(self._callback, interval, self._args);
  7966. };
  7967. this.clear = function () {
  7968. if (self._interval) {
  7969. clearInterval(self._interval);
  7970. self._interval = undefined;
  7971. }
  7972. };
  7973. this.destroy = function () {
  7974. if (self._interval) {
  7975. clearInterval(self._interval);
  7976. }
  7977. self._callback = undefined;
  7978. self._interval = undefined;
  7979. self._args = undefined;
  7980. };
  7981. }
  7982. function reInterval () {
  7983. if (typeof arguments[0] !== 'function')
  7984. throw new Error('callback needed');
  7985. if (typeof arguments[1] !== 'number')
  7986. throw new Error('interval needed');
  7987. var args;
  7988. if (arguments.length > 0) {
  7989. args = new Array(arguments.length - 2);
  7990. for (var i = 0; i < args.length; i++) {
  7991. args[i] = arguments[i + 2];
  7992. }
  7993. }
  7994. return new ReInterval(arguments[0], arguments[1], args);
  7995. }
  7996. module.exports = reInterval;
  7997. },{}],47:[function(require,module,exports){
  7998. /* eslint-disable node/no-deprecated-api */
  7999. var buffer = require('buffer')
  8000. var Buffer = buffer.Buffer
  8001. // alternative to using Object.keys for old browsers
  8002. function copyProps (src, dst) {
  8003. for (var key in src) {
  8004. dst[key] = src[key]
  8005. }
  8006. }
  8007. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  8008. module.exports = buffer
  8009. } else {
  8010. // Copy properties from require('buffer')
  8011. copyProps(buffer, exports)
  8012. exports.Buffer = SafeBuffer
  8013. }
  8014. function SafeBuffer (arg, encodingOrOffset, length) {
  8015. return Buffer(arg, encodingOrOffset, length)
  8016. }
  8017. // Copy static methods from Buffer
  8018. copyProps(Buffer, SafeBuffer)
  8019. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  8020. if (typeof arg === 'number') {
  8021. throw new TypeError('Argument must not be a number')
  8022. }
  8023. return Buffer(arg, encodingOrOffset, length)
  8024. }
  8025. SafeBuffer.alloc = function (size, fill, encoding) {
  8026. if (typeof size !== 'number') {
  8027. throw new TypeError('Argument must be a number')
  8028. }
  8029. var buf = Buffer(size)
  8030. if (fill !== undefined) {
  8031. if (typeof encoding === 'string') {
  8032. buf.fill(fill, encoding)
  8033. } else {
  8034. buf.fill(fill)
  8035. }
  8036. } else {
  8037. buf.fill(0)
  8038. }
  8039. return buf
  8040. }
  8041. SafeBuffer.allocUnsafe = function (size) {
  8042. if (typeof size !== 'number') {
  8043. throw new TypeError('Argument must be a number')
  8044. }
  8045. return Buffer(size)
  8046. }
  8047. SafeBuffer.allocUnsafeSlow = function (size) {
  8048. if (typeof size !== 'number') {
  8049. throw new TypeError('Argument must be a number')
  8050. }
  8051. return buffer.SlowBuffer(size)
  8052. }
  8053. },{"buffer":13}],48:[function(require,module,exports){
  8054. module.exports = shift
  8055. function shift (stream) {
  8056. var rs = stream._readableState
  8057. if (!rs) return null
  8058. return rs.objectMode ? stream.read() : stream.read(getStateLength(rs))
  8059. }
  8060. function getStateLength (state) {
  8061. if (state.buffer.length) {
  8062. // Since node 6.3.0 state.buffer is a BufferList not an array
  8063. if (state.buffer.head) {
  8064. return state.buffer.head.data.length
  8065. }
  8066. return state.buffer[0].length
  8067. }
  8068. return state.length
  8069. }
  8070. },{}],49:[function(require,module,exports){
  8071. // Copyright Joyent, Inc. and other Node contributors.
  8072. //
  8073. // Permission is hereby granted, free of charge, to any person obtaining a
  8074. // copy of this software and associated documentation files (the
  8075. // "Software"), to deal in the Software without restriction, including
  8076. // without limitation the rights to use, copy, modify, merge, publish,
  8077. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8078. // persons to whom the Software is furnished to do so, subject to the
  8079. // following conditions:
  8080. //
  8081. // The above copyright notice and this permission notice shall be included
  8082. // in all copies or substantial portions of the Software.
  8083. //
  8084. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8085. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8086. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8087. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8088. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8089. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8090. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8091. 'use strict';
  8092. /*<replacement>*/
  8093. var Buffer = require('safe-buffer').Buffer;
  8094. /*</replacement>*/
  8095. var isEncoding = Buffer.isEncoding || function (encoding) {
  8096. encoding = '' + encoding;
  8097. switch (encoding && encoding.toLowerCase()) {
  8098. 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':
  8099. return true;
  8100. default:
  8101. return false;
  8102. }
  8103. };
  8104. function _normalizeEncoding(enc) {
  8105. if (!enc) return 'utf8';
  8106. var retried;
  8107. while (true) {
  8108. switch (enc) {
  8109. case 'utf8':
  8110. case 'utf-8':
  8111. return 'utf8';
  8112. case 'ucs2':
  8113. case 'ucs-2':
  8114. case 'utf16le':
  8115. case 'utf-16le':
  8116. return 'utf16le';
  8117. case 'latin1':
  8118. case 'binary':
  8119. return 'latin1';
  8120. case 'base64':
  8121. case 'ascii':
  8122. case 'hex':
  8123. return enc;
  8124. default:
  8125. if (retried) return; // undefined
  8126. enc = ('' + enc).toLowerCase();
  8127. retried = true;
  8128. }
  8129. }
  8130. };
  8131. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  8132. // modules monkey-patch it to support additional encodings
  8133. function normalizeEncoding(enc) {
  8134. var nenc = _normalizeEncoding(enc);
  8135. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  8136. return nenc || enc;
  8137. }
  8138. // StringDecoder provides an interface for efficiently splitting a series of
  8139. // buffers into a series of JS strings without breaking apart multi-byte
  8140. // characters.
  8141. exports.StringDecoder = StringDecoder;
  8142. function StringDecoder(encoding) {
  8143. this.encoding = normalizeEncoding(encoding);
  8144. var nb;
  8145. switch (this.encoding) {
  8146. case 'utf16le':
  8147. this.text = utf16Text;
  8148. this.end = utf16End;
  8149. nb = 4;
  8150. break;
  8151. case 'utf8':
  8152. this.fillLast = utf8FillLast;
  8153. nb = 4;
  8154. break;
  8155. case 'base64':
  8156. this.text = base64Text;
  8157. this.end = base64End;
  8158. nb = 3;
  8159. break;
  8160. default:
  8161. this.write = simpleWrite;
  8162. this.end = simpleEnd;
  8163. return;
  8164. }
  8165. this.lastNeed = 0;
  8166. this.lastTotal = 0;
  8167. this.lastChar = Buffer.allocUnsafe(nb);
  8168. }
  8169. StringDecoder.prototype.write = function (buf) {
  8170. if (buf.length === 0) return '';
  8171. var r;
  8172. var i;
  8173. if (this.lastNeed) {
  8174. r = this.fillLast(buf);
  8175. if (r === undefined) return '';
  8176. i = this.lastNeed;
  8177. this.lastNeed = 0;
  8178. } else {
  8179. i = 0;
  8180. }
  8181. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  8182. return r || '';
  8183. };
  8184. StringDecoder.prototype.end = utf8End;
  8185. // Returns only complete characters in a Buffer
  8186. StringDecoder.prototype.text = utf8Text;
  8187. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  8188. StringDecoder.prototype.fillLast = function (buf) {
  8189. if (this.lastNeed <= buf.length) {
  8190. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  8191. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  8192. }
  8193. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  8194. this.lastNeed -= buf.length;
  8195. };
  8196. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  8197. // continuation byte. If an invalid byte is detected, -2 is returned.
  8198. function utf8CheckByte(byte) {
  8199. if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  8200. return byte >> 6 === 0x02 ? -1 : -2;
  8201. }
  8202. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  8203. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  8204. // needed to complete the UTF-8 character (if applicable) are returned.
  8205. function utf8CheckIncomplete(self, buf, i) {
  8206. var j = buf.length - 1;
  8207. if (j < i) return 0;
  8208. var nb = utf8CheckByte(buf[j]);
  8209. if (nb >= 0) {
  8210. if (nb > 0) self.lastNeed = nb - 1;
  8211. return nb;
  8212. }
  8213. if (--j < i || nb === -2) return 0;
  8214. nb = utf8CheckByte(buf[j]);
  8215. if (nb >= 0) {
  8216. if (nb > 0) self.lastNeed = nb - 2;
  8217. return nb;
  8218. }
  8219. if (--j < i || nb === -2) return 0;
  8220. nb = utf8CheckByte(buf[j]);
  8221. if (nb >= 0) {
  8222. if (nb > 0) {
  8223. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  8224. }
  8225. return nb;
  8226. }
  8227. return 0;
  8228. }
  8229. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  8230. // needed or are available. If we see a non-continuation byte where we expect
  8231. // one, we "replace" the validated continuation bytes we've seen so far with
  8232. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  8233. // behavior. The continuation byte check is included three times in the case
  8234. // where all of the continuation bytes for a character exist in the same buffer.
  8235. // It is also done this way as a slight performance increase instead of using a
  8236. // loop.
  8237. function utf8CheckExtraBytes(self, buf, p) {
  8238. if ((buf[0] & 0xC0) !== 0x80) {
  8239. self.lastNeed = 0;
  8240. return '\ufffd';
  8241. }
  8242. if (self.lastNeed > 1 && buf.length > 1) {
  8243. if ((buf[1] & 0xC0) !== 0x80) {
  8244. self.lastNeed = 1;
  8245. return '\ufffd';
  8246. }
  8247. if (self.lastNeed > 2 && buf.length > 2) {
  8248. if ((buf[2] & 0xC0) !== 0x80) {
  8249. self.lastNeed = 2;
  8250. return '\ufffd';
  8251. }
  8252. }
  8253. }
  8254. }
  8255. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  8256. function utf8FillLast(buf) {
  8257. var p = this.lastTotal - this.lastNeed;
  8258. var r = utf8CheckExtraBytes(this, buf, p);
  8259. if (r !== undefined) return r;
  8260. if (this.lastNeed <= buf.length) {
  8261. buf.copy(this.lastChar, p, 0, this.lastNeed);
  8262. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  8263. }
  8264. buf.copy(this.lastChar, p, 0, buf.length);
  8265. this.lastNeed -= buf.length;
  8266. }
  8267. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  8268. // partial character, the character's bytes are buffered until the required
  8269. // number of bytes are available.
  8270. function utf8Text(buf, i) {
  8271. var total = utf8CheckIncomplete(this, buf, i);
  8272. if (!this.lastNeed) return buf.toString('utf8', i);
  8273. this.lastTotal = total;
  8274. var end = buf.length - (total - this.lastNeed);
  8275. buf.copy(this.lastChar, 0, end);
  8276. return buf.toString('utf8', i, end);
  8277. }
  8278. // For UTF-8, a replacement character is added when ending on a partial
  8279. // character.
  8280. function utf8End(buf) {
  8281. var r = buf && buf.length ? this.write(buf) : '';
  8282. if (this.lastNeed) return r + '\ufffd';
  8283. return r;
  8284. }
  8285. // UTF-16LE typically needs two bytes per character, but even if we have an even
  8286. // number of bytes available, we need to check if we end on a leading/high
  8287. // surrogate. In that case, we need to wait for the next two bytes in order to
  8288. // decode the last character properly.
  8289. function utf16Text(buf, i) {
  8290. if ((buf.length - i) % 2 === 0) {
  8291. var r = buf.toString('utf16le', i);
  8292. if (r) {
  8293. var c = r.charCodeAt(r.length - 1);
  8294. if (c >= 0xD800 && c <= 0xDBFF) {
  8295. this.lastNeed = 2;
  8296. this.lastTotal = 4;
  8297. this.lastChar[0] = buf[buf.length - 2];
  8298. this.lastChar[1] = buf[buf.length - 1];
  8299. return r.slice(0, -1);
  8300. }
  8301. }
  8302. return r;
  8303. }
  8304. this.lastNeed = 1;
  8305. this.lastTotal = 2;
  8306. this.lastChar[0] = buf[buf.length - 1];
  8307. return buf.toString('utf16le', i, buf.length - 1);
  8308. }
  8309. // For UTF-16LE we do not explicitly append special replacement characters if we
  8310. // end on a partial character, we simply let v8 handle that.
  8311. function utf16End(buf) {
  8312. var r = buf && buf.length ? this.write(buf) : '';
  8313. if (this.lastNeed) {
  8314. var end = this.lastTotal - this.lastNeed;
  8315. return r + this.lastChar.toString('utf16le', 0, end);
  8316. }
  8317. return r;
  8318. }
  8319. function base64Text(buf, i) {
  8320. var n = (buf.length - i) % 3;
  8321. if (n === 0) return buf.toString('base64', i);
  8322. this.lastNeed = 3 - n;
  8323. this.lastTotal = 3;
  8324. if (n === 1) {
  8325. this.lastChar[0] = buf[buf.length - 1];
  8326. } else {
  8327. this.lastChar[0] = buf[buf.length - 2];
  8328. this.lastChar[1] = buf[buf.length - 1];
  8329. }
  8330. return buf.toString('base64', i, buf.length - n);
  8331. }
  8332. function base64End(buf) {
  8333. var r = buf && buf.length ? this.write(buf) : '';
  8334. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  8335. return r;
  8336. }
  8337. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  8338. function simpleWrite(buf) {
  8339. return buf.toString(this.encoding);
  8340. }
  8341. function simpleEnd(buf) {
  8342. return buf && buf.length ? this.write(buf) : '';
  8343. }
  8344. },{"safe-buffer":47}],50:[function(require,module,exports){
  8345. // Copyright Joyent, Inc. and other Node contributors.
  8346. //
  8347. // Permission is hereby granted, free of charge, to any person obtaining a
  8348. // copy of this software and associated documentation files (the
  8349. // "Software"), to deal in the Software without restriction, including
  8350. // without limitation the rights to use, copy, modify, merge, publish,
  8351. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8352. // persons to whom the Software is furnished to do so, subject to the
  8353. // following conditions:
  8354. //
  8355. // The above copyright notice and this permission notice shall be included
  8356. // in all copies or substantial portions of the Software.
  8357. //
  8358. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8359. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8360. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8361. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8362. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8363. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8364. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8365. 'use strict';
  8366. var punycode = require('punycode');
  8367. var util = require('./util');
  8368. exports.parse = urlParse;
  8369. exports.resolve = urlResolve;
  8370. exports.resolveObject = urlResolveObject;
  8371. exports.format = urlFormat;
  8372. exports.Url = Url;
  8373. function Url() {
  8374. this.protocol = null;
  8375. this.slashes = null;
  8376. this.auth = null;
  8377. this.host = null;
  8378. this.port = null;
  8379. this.hostname = null;
  8380. this.hash = null;
  8381. this.search = null;
  8382. this.query = null;
  8383. this.pathname = null;
  8384. this.path = null;
  8385. this.href = null;
  8386. }
  8387. // Reference: RFC 3986, RFC 1808, RFC 2396
  8388. // define these here so at least they only have to be
  8389. // compiled once on the first module load.
  8390. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  8391. portPattern = /:[0-9]*$/,
  8392. // Special case for a simple path URL
  8393. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  8394. // RFC 2396: characters reserved for delimiting URLs.
  8395. // We actually just auto-escape these.
  8396. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  8397. // RFC 2396: characters not allowed for various reasons.
  8398. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  8399. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  8400. autoEscape = ['\''].concat(unwise),
  8401. // Characters that are never ever allowed in a hostname.
  8402. // Note that any invalid chars are also handled, but these
  8403. // are the ones that are *expected* to be seen, so we fast-path
  8404. // them.
  8405. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  8406. hostEndingChars = ['/', '?', '#'],
  8407. hostnameMaxLen = 255,
  8408. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  8409. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  8410. // protocols that can allow "unsafe" and "unwise" chars.
  8411. unsafeProtocol = {
  8412. 'javascript': true,
  8413. 'javascript:': true
  8414. },
  8415. // protocols that never have a hostname.
  8416. hostlessProtocol = {
  8417. 'javascript': true,
  8418. 'javascript:': true
  8419. },
  8420. // protocols that always contain a // bit.
  8421. slashedProtocol = {
  8422. 'http': true,
  8423. 'https': true,
  8424. 'ftp': true,
  8425. 'gopher': true,
  8426. 'file': true,
  8427. 'http:': true,
  8428. 'https:': true,
  8429. 'ftp:': true,
  8430. 'gopher:': true,
  8431. 'file:': true
  8432. },
  8433. querystring = require('querystring');
  8434. function urlParse(url, parseQueryString, slashesDenoteHost) {
  8435. if (url && util.isObject(url) && url instanceof Url) return url;
  8436. var u = new Url;
  8437. u.parse(url, parseQueryString, slashesDenoteHost);
  8438. return u;
  8439. }
  8440. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  8441. if (!util.isString(url)) {
  8442. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  8443. }
  8444. // Copy chrome, IE, opera backslash-handling behavior.
  8445. // Back slashes before the query string get converted to forward slashes
  8446. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  8447. var queryIndex = url.indexOf('?'),
  8448. splitter =
  8449. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  8450. uSplit = url.split(splitter),
  8451. slashRegex = /\\/g;
  8452. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  8453. url = uSplit.join(splitter);
  8454. var rest = url;
  8455. // trim before proceeding.
  8456. // This is to support parse stuff like " http://foo.com \n"
  8457. rest = rest.trim();
  8458. if (!slashesDenoteHost && url.split('#').length === 1) {
  8459. // Try fast path regexp
  8460. var simplePath = simplePathPattern.exec(rest);
  8461. if (simplePath) {
  8462. this.path = rest;
  8463. this.href = rest;
  8464. this.pathname = simplePath[1];
  8465. if (simplePath[2]) {
  8466. this.search = simplePath[2];
  8467. if (parseQueryString) {
  8468. this.query = querystring.parse(this.search.substr(1));
  8469. } else {
  8470. this.query = this.search.substr(1);
  8471. }
  8472. } else if (parseQueryString) {
  8473. this.search = '';
  8474. this.query = {};
  8475. }
  8476. return this;
  8477. }
  8478. }
  8479. var proto = protocolPattern.exec(rest);
  8480. if (proto) {
  8481. proto = proto[0];
  8482. var lowerProto = proto.toLowerCase();
  8483. this.protocol = lowerProto;
  8484. rest = rest.substr(proto.length);
  8485. }
  8486. // figure out if it's got a host
  8487. // user@server is *always* interpreted as a hostname, and url
  8488. // resolution will treat //foo/bar as host=foo,path=bar because that's
  8489. // how the browser resolves relative URLs.
  8490. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  8491. var slashes = rest.substr(0, 2) === '//';
  8492. if (slashes && !(proto && hostlessProtocol[proto])) {
  8493. rest = rest.substr(2);
  8494. this.slashes = true;
  8495. }
  8496. }
  8497. if (!hostlessProtocol[proto] &&
  8498. (slashes || (proto && !slashedProtocol[proto]))) {
  8499. // there's a hostname.
  8500. // the first instance of /, ?, ;, or # ends the host.
  8501. //
  8502. // If there is an @ in the hostname, then non-host chars *are* allowed
  8503. // to the left of the last @ sign, unless some host-ending character
  8504. // comes *before* the @-sign.
  8505. // URLs are obnoxious.
  8506. //
  8507. // ex:
  8508. // http://a@b@c/ => user:a@b host:c
  8509. // http://a@b?@c => user:a host:c path:/?@c
  8510. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  8511. // Review our test case against browsers more comprehensively.
  8512. // find the first instance of any hostEndingChars
  8513. var hostEnd = -1;
  8514. for (var i = 0; i < hostEndingChars.length; i++) {
  8515. var hec = rest.indexOf(hostEndingChars[i]);
  8516. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  8517. hostEnd = hec;
  8518. }
  8519. // at this point, either we have an explicit point where the
  8520. // auth portion cannot go past, or the last @ char is the decider.
  8521. var auth, atSign;
  8522. if (hostEnd === -1) {
  8523. // atSign can be anywhere.
  8524. atSign = rest.lastIndexOf('@');
  8525. } else {
  8526. // atSign must be in auth portion.
  8527. // http://a@b/c@d => host:b auth:a path:/c@d
  8528. atSign = rest.lastIndexOf('@', hostEnd);
  8529. }
  8530. // Now we have a portion which is definitely the auth.
  8531. // Pull that off.
  8532. if (atSign !== -1) {
  8533. auth = rest.slice(0, atSign);
  8534. rest = rest.slice(atSign + 1);
  8535. this.auth = decodeURIComponent(auth);
  8536. }
  8537. // the host is the remaining to the left of the first non-host char
  8538. hostEnd = -1;
  8539. for (var i = 0; i < nonHostChars.length; i++) {
  8540. var hec = rest.indexOf(nonHostChars[i]);
  8541. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  8542. hostEnd = hec;
  8543. }
  8544. // if we still have not hit it, then the entire thing is a host.
  8545. if (hostEnd === -1)
  8546. hostEnd = rest.length;
  8547. this.host = rest.slice(0, hostEnd);
  8548. rest = rest.slice(hostEnd);
  8549. // pull out port.
  8550. this.parseHost();
  8551. // we've indicated that there is a hostname,
  8552. // so even if it's empty, it has to be present.
  8553. this.hostname = this.hostname || '';
  8554. // if hostname begins with [ and ends with ]
  8555. // assume that it's an IPv6 address.
  8556. var ipv6Hostname = this.hostname[0] === '[' &&
  8557. this.hostname[this.hostname.length - 1] === ']';
  8558. // validate a little.
  8559. if (!ipv6Hostname) {
  8560. var hostparts = this.hostname.split(/\./);
  8561. for (var i = 0, l = hostparts.length; i < l; i++) {
  8562. var part = hostparts[i];
  8563. if (!part) continue;
  8564. if (!part.match(hostnamePartPattern)) {
  8565. var newpart = '';
  8566. for (var j = 0, k = part.length; j < k; j++) {
  8567. if (part.charCodeAt(j) > 127) {
  8568. // we replace non-ASCII char with a temporary placeholder
  8569. // we need this to make sure size of hostname is not
  8570. // broken by replacing non-ASCII by nothing
  8571. newpart += 'x';
  8572. } else {
  8573. newpart += part[j];
  8574. }
  8575. }
  8576. // we test again with ASCII char only
  8577. if (!newpart.match(hostnamePartPattern)) {
  8578. var validParts = hostparts.slice(0, i);
  8579. var notHost = hostparts.slice(i + 1);
  8580. var bit = part.match(hostnamePartStart);
  8581. if (bit) {
  8582. validParts.push(bit[1]);
  8583. notHost.unshift(bit[2]);
  8584. }
  8585. if (notHost.length) {
  8586. rest = '/' + notHost.join('.') + rest;
  8587. }
  8588. this.hostname = validParts.join('.');
  8589. break;
  8590. }
  8591. }
  8592. }
  8593. }
  8594. if (this.hostname.length > hostnameMaxLen) {
  8595. this.hostname = '';
  8596. } else {
  8597. // hostnames are always lower case.
  8598. this.hostname = this.hostname.toLowerCase();
  8599. }
  8600. if (!ipv6Hostname) {
  8601. // IDNA Support: Returns a punycoded representation of "domain".
  8602. // It only converts parts of the domain name that
  8603. // have non-ASCII characters, i.e. it doesn't matter if
  8604. // you call it with a domain that already is ASCII-only.
  8605. this.hostname = punycode.toASCII(this.hostname);
  8606. }
  8607. var p = this.port ? ':' + this.port : '';
  8608. var h = this.hostname || '';
  8609. this.host = h + p;
  8610. this.href += this.host;
  8611. // strip [ and ] from the hostname
  8612. // the host field still retains them, though
  8613. if (ipv6Hostname) {
  8614. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  8615. if (rest[0] !== '/') {
  8616. rest = '/' + rest;
  8617. }
  8618. }
  8619. }
  8620. // now rest is set to the post-host stuff.
  8621. // chop off any delim chars.
  8622. if (!unsafeProtocol[lowerProto]) {
  8623. // First, make 100% sure that any "autoEscape" chars get
  8624. // escaped, even if encodeURIComponent doesn't think they
  8625. // need to be.
  8626. for (var i = 0, l = autoEscape.length; i < l; i++) {
  8627. var ae = autoEscape[i];
  8628. if (rest.indexOf(ae) === -1)
  8629. continue;
  8630. var esc = encodeURIComponent(ae);
  8631. if (esc === ae) {
  8632. esc = escape(ae);
  8633. }
  8634. rest = rest.split(ae).join(esc);
  8635. }
  8636. }
  8637. // chop off from the tail first.
  8638. var hash = rest.indexOf('#');
  8639. if (hash !== -1) {
  8640. // got a fragment string.
  8641. this.hash = rest.substr(hash);
  8642. rest = rest.slice(0, hash);
  8643. }
  8644. var qm = rest.indexOf('?');
  8645. if (qm !== -1) {
  8646. this.search = rest.substr(qm);
  8647. this.query = rest.substr(qm + 1);
  8648. if (parseQueryString) {
  8649. this.query = querystring.parse(this.query);
  8650. }
  8651. rest = rest.slice(0, qm);
  8652. } else if (parseQueryString) {
  8653. // no query string, but parseQueryString still requested
  8654. this.search = '';
  8655. this.query = {};
  8656. }
  8657. if (rest) this.pathname = rest;
  8658. if (slashedProtocol[lowerProto] &&
  8659. this.hostname && !this.pathname) {
  8660. this.pathname = '/';
  8661. }
  8662. //to support http.request
  8663. if (this.pathname || this.search) {
  8664. var p = this.pathname || '';
  8665. var s = this.search || '';
  8666. this.path = p + s;
  8667. }
  8668. // finally, reconstruct the href based on what has been validated.
  8669. this.href = this.format();
  8670. return this;
  8671. };
  8672. // format a parsed object into a url string
  8673. function urlFormat(obj) {
  8674. // ensure it's an object, and not a string url.
  8675. // If it's an obj, this is a no-op.
  8676. // this way, you can call url_format() on strings
  8677. // to clean up potentially wonky urls.
  8678. if (util.isString(obj)) obj = urlParse(obj);
  8679. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  8680. return obj.format();
  8681. }
  8682. Url.prototype.format = function() {
  8683. var auth = this.auth || '';
  8684. if (auth) {
  8685. auth = encodeURIComponent(auth);
  8686. auth = auth.replace(/%3A/i, ':');
  8687. auth += '@';
  8688. }
  8689. var protocol = this.protocol || '',
  8690. pathname = this.pathname || '',
  8691. hash = this.hash || '',
  8692. host = false,
  8693. query = '';
  8694. if (this.host) {
  8695. host = auth + this.host;
  8696. } else if (this.hostname) {
  8697. host = auth + (this.hostname.indexOf(':') === -1 ?
  8698. this.hostname :
  8699. '[' + this.hostname + ']');
  8700. if (this.port) {
  8701. host += ':' + this.port;
  8702. }
  8703. }
  8704. if (this.query &&
  8705. util.isObject(this.query) &&
  8706. Object.keys(this.query).length) {
  8707. query = querystring.stringify(this.query);
  8708. }
  8709. var search = this.search || (query && ('?' + query)) || '';
  8710. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  8711. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  8712. // unless they had them to begin with.
  8713. if (this.slashes ||
  8714. (!protocol || slashedProtocol[protocol]) && host !== false) {
  8715. host = '//' + (host || '');
  8716. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  8717. } else if (!host) {
  8718. host = '';
  8719. }
  8720. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  8721. if (search && search.charAt(0) !== '?') search = '?' + search;
  8722. pathname = pathname.replace(/[?#]/g, function(match) {
  8723. return encodeURIComponent(match);
  8724. });
  8725. search = search.replace('#', '%23');
  8726. return protocol + host + pathname + search + hash;
  8727. };
  8728. function urlResolve(source, relative) {
  8729. return urlParse(source, false, true).resolve(relative);
  8730. }
  8731. Url.prototype.resolve = function(relative) {
  8732. return this.resolveObject(urlParse(relative, false, true)).format();
  8733. };
  8734. function urlResolveObject(source, relative) {
  8735. if (!source) return relative;
  8736. return urlParse(source, false, true).resolveObject(relative);
  8737. }
  8738. Url.prototype.resolveObject = function(relative) {
  8739. if (util.isString(relative)) {
  8740. var rel = new Url();
  8741. rel.parse(relative, false, true);
  8742. relative = rel;
  8743. }
  8744. var result = new Url();
  8745. var tkeys = Object.keys(this);
  8746. for (var tk = 0; tk < tkeys.length; tk++) {
  8747. var tkey = tkeys[tk];
  8748. result[tkey] = this[tkey];
  8749. }
  8750. // hash is always overridden, no matter what.
  8751. // even href="" will remove it.
  8752. result.hash = relative.hash;
  8753. // if the relative url is empty, then there's nothing left to do here.
  8754. if (relative.href === '') {
  8755. result.href = result.format();
  8756. return result;
  8757. }
  8758. // hrefs like //foo/bar always cut to the protocol.
  8759. if (relative.slashes && !relative.protocol) {
  8760. // take everything except the protocol from relative
  8761. var rkeys = Object.keys(relative);
  8762. for (var rk = 0; rk < rkeys.length; rk++) {
  8763. var rkey = rkeys[rk];
  8764. if (rkey !== 'protocol')
  8765. result[rkey] = relative[rkey];
  8766. }
  8767. //urlParse appends trailing / to urls like http://www.example.com
  8768. if (slashedProtocol[result.protocol] &&
  8769. result.hostname && !result.pathname) {
  8770. result.path = result.pathname = '/';
  8771. }
  8772. result.href = result.format();
  8773. return result;
  8774. }
  8775. if (relative.protocol && relative.protocol !== result.protocol) {
  8776. // if it's a known url protocol, then changing
  8777. // the protocol does weird things
  8778. // first, if it's not file:, then we MUST have a host,
  8779. // and if there was a path
  8780. // to begin with, then we MUST have a path.
  8781. // if it is file:, then the host is dropped,
  8782. // because that's known to be hostless.
  8783. // anything else is assumed to be absolute.
  8784. if (!slashedProtocol[relative.protocol]) {
  8785. var keys = Object.keys(relative);
  8786. for (var v = 0; v < keys.length; v++) {
  8787. var k = keys[v];
  8788. result[k] = relative[k];
  8789. }
  8790. result.href = result.format();
  8791. return result;
  8792. }
  8793. result.protocol = relative.protocol;
  8794. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  8795. var relPath = (relative.pathname || '').split('/');
  8796. while (relPath.length && !(relative.host = relPath.shift()));
  8797. if (!relative.host) relative.host = '';
  8798. if (!relative.hostname) relative.hostname = '';
  8799. if (relPath[0] !== '') relPath.unshift('');
  8800. if (relPath.length < 2) relPath.unshift('');
  8801. result.pathname = relPath.join('/');
  8802. } else {
  8803. result.pathname = relative.pathname;
  8804. }
  8805. result.search = relative.search;
  8806. result.query = relative.query;
  8807. result.host = relative.host || '';
  8808. result.auth = relative.auth;
  8809. result.hostname = relative.hostname || relative.host;
  8810. result.port = relative.port;
  8811. // to support http.request
  8812. if (result.pathname || result.search) {
  8813. var p = result.pathname || '';
  8814. var s = result.search || '';
  8815. result.path = p + s;
  8816. }
  8817. result.slashes = result.slashes || relative.slashes;
  8818. result.href = result.format();
  8819. return result;
  8820. }
  8821. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  8822. isRelAbs = (
  8823. relative.host ||
  8824. relative.pathname && relative.pathname.charAt(0) === '/'
  8825. ),
  8826. mustEndAbs = (isRelAbs || isSourceAbs ||
  8827. (result.host && relative.pathname)),
  8828. removeAllDots = mustEndAbs,
  8829. srcPath = result.pathname && result.pathname.split('/') || [],
  8830. relPath = relative.pathname && relative.pathname.split('/') || [],
  8831. psychotic = result.protocol && !slashedProtocol[result.protocol];
  8832. // if the url is a non-slashed url, then relative
  8833. // links like ../.. should be able
  8834. // to crawl up to the hostname, as well. This is strange.
  8835. // result.protocol has already been set by now.
  8836. // Later on, put the first path part into the host field.
  8837. if (psychotic) {
  8838. result.hostname = '';
  8839. result.port = null;
  8840. if (result.host) {
  8841. if (srcPath[0] === '') srcPath[0] = result.host;
  8842. else srcPath.unshift(result.host);
  8843. }
  8844. result.host = '';
  8845. if (relative.protocol) {
  8846. relative.hostname = null;
  8847. relative.port = null;
  8848. if (relative.host) {
  8849. if (relPath[0] === '') relPath[0] = relative.host;
  8850. else relPath.unshift(relative.host);
  8851. }
  8852. relative.host = null;
  8853. }
  8854. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  8855. }
  8856. if (isRelAbs) {
  8857. // it's absolute.
  8858. result.host = (relative.host || relative.host === '') ?
  8859. relative.host : result.host;
  8860. result.hostname = (relative.hostname || relative.hostname === '') ?
  8861. relative.hostname : result.hostname;
  8862. result.search = relative.search;
  8863. result.query = relative.query;
  8864. srcPath = relPath;
  8865. // fall through to the dot-handling below.
  8866. } else if (relPath.length) {
  8867. // it's relative
  8868. // throw away the existing file, and take the new path instead.
  8869. if (!srcPath) srcPath = [];
  8870. srcPath.pop();
  8871. srcPath = srcPath.concat(relPath);
  8872. result.search = relative.search;
  8873. result.query = relative.query;
  8874. } else if (!util.isNullOrUndefined(relative.search)) {
  8875. // just pull out the search.
  8876. // like href='?foo'.
  8877. // Put this after the other two cases because it simplifies the booleans
  8878. if (psychotic) {
  8879. result.hostname = result.host = srcPath.shift();
  8880. //occationaly the auth can get stuck only in host
  8881. //this especially happens in cases like
  8882. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  8883. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  8884. result.host.split('@') : false;
  8885. if (authInHost) {
  8886. result.auth = authInHost.shift();
  8887. result.host = result.hostname = authInHost.shift();
  8888. }
  8889. }
  8890. result.search = relative.search;
  8891. result.query = relative.query;
  8892. //to support http.request
  8893. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  8894. result.path = (result.pathname ? result.pathname : '') +
  8895. (result.search ? result.search : '');
  8896. }
  8897. result.href = result.format();
  8898. return result;
  8899. }
  8900. if (!srcPath.length) {
  8901. // no path at all. easy.
  8902. // we've already handled the other stuff above.
  8903. result.pathname = null;
  8904. //to support http.request
  8905. if (result.search) {
  8906. result.path = '/' + result.search;
  8907. } else {
  8908. result.path = null;
  8909. }
  8910. result.href = result.format();
  8911. return result;
  8912. }
  8913. // if a url ENDs in . or .., then it must get a trailing slash.
  8914. // however, if it ends in anything else non-slashy,
  8915. // then it must NOT get a trailing slash.
  8916. var last = srcPath.slice(-1)[0];
  8917. var hasTrailingSlash = (
  8918. (result.host || relative.host || srcPath.length > 1) &&
  8919. (last === '.' || last === '..') || last === '');
  8920. // strip single dots, resolve double dots to parent dir
  8921. // if the path tries to go above the root, `up` ends up > 0
  8922. var up = 0;
  8923. for (var i = srcPath.length; i >= 0; i--) {
  8924. last = srcPath[i];
  8925. if (last === '.') {
  8926. srcPath.splice(i, 1);
  8927. } else if (last === '..') {
  8928. srcPath.splice(i, 1);
  8929. up++;
  8930. } else if (up) {
  8931. srcPath.splice(i, 1);
  8932. up--;
  8933. }
  8934. }
  8935. // if the path is allowed to go above the root, restore leading ..s
  8936. if (!mustEndAbs && !removeAllDots) {
  8937. for (; up--; up) {
  8938. srcPath.unshift('..');
  8939. }
  8940. }
  8941. if (mustEndAbs && srcPath[0] !== '' &&
  8942. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  8943. srcPath.unshift('');
  8944. }
  8945. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  8946. srcPath.push('');
  8947. }
  8948. var isAbsolute = srcPath[0] === '' ||
  8949. (srcPath[0] && srcPath[0].charAt(0) === '/');
  8950. // put the host back
  8951. if (psychotic) {
  8952. result.hostname = result.host = isAbsolute ? '' :
  8953. srcPath.length ? srcPath.shift() : '';
  8954. //occationaly the auth can get stuck only in host
  8955. //this especially happens in cases like
  8956. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  8957. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  8958. result.host.split('@') : false;
  8959. if (authInHost) {
  8960. result.auth = authInHost.shift();
  8961. result.host = result.hostname = authInHost.shift();
  8962. }
  8963. }
  8964. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  8965. if (mustEndAbs && !isAbsolute) {
  8966. srcPath.unshift('');
  8967. }
  8968. if (!srcPath.length) {
  8969. result.pathname = null;
  8970. result.path = null;
  8971. } else {
  8972. result.pathname = srcPath.join('/');
  8973. }
  8974. //to support request.http
  8975. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  8976. result.path = (result.pathname ? result.pathname : '') +
  8977. (result.search ? result.search : '');
  8978. }
  8979. result.auth = relative.auth || result.auth;
  8980. result.slashes = result.slashes || relative.slashes;
  8981. result.href = result.format();
  8982. return result;
  8983. };
  8984. Url.prototype.parseHost = function() {
  8985. var host = this.host;
  8986. var port = portPattern.exec(host);
  8987. if (port) {
  8988. port = port[0];
  8989. if (port !== ':') {
  8990. this.port = port.substr(1);
  8991. }
  8992. host = host.substr(0, host.length - port.length);
  8993. }
  8994. if (host) this.hostname = host;
  8995. };
  8996. },{"./util":51,"punycode":31,"querystring":34}],51:[function(require,module,exports){
  8997. 'use strict';
  8998. module.exports = {
  8999. isString: function(arg) {
  9000. return typeof(arg) === 'string';
  9001. },
  9002. isObject: function(arg) {
  9003. return typeof(arg) === 'object' && arg !== null;
  9004. },
  9005. isNull: function(arg) {
  9006. return arg === null;
  9007. },
  9008. isNullOrUndefined: function(arg) {
  9009. return arg == null;
  9010. }
  9011. };
  9012. },{}],52:[function(require,module,exports){
  9013. (function (global){
  9014. /**
  9015. * Module exports.
  9016. */
  9017. module.exports = deprecate;
  9018. /**
  9019. * Mark that a method should not be used.
  9020. * Returns a modified function which warns once by default.
  9021. *
  9022. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  9023. *
  9024. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  9025. * will throw an Error when invoked.
  9026. *
  9027. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  9028. * will invoke `console.trace()` instead of `console.error()`.
  9029. *
  9030. * @param {Function} fn - the function to deprecate
  9031. * @param {String} msg - the string to print to the console when `fn` is invoked
  9032. * @returns {Function} a new "deprecated" version of `fn`
  9033. * @api public
  9034. */
  9035. function deprecate (fn, msg) {
  9036. if (config('noDeprecation')) {
  9037. return fn;
  9038. }
  9039. var warned = false;
  9040. function deprecated() {
  9041. if (!warned) {
  9042. if (config('throwDeprecation')) {
  9043. throw new Error(msg);
  9044. } else if (config('traceDeprecation')) {
  9045. console.trace(msg);
  9046. } else {
  9047. console.warn(msg);
  9048. }
  9049. warned = true;
  9050. }
  9051. return fn.apply(this, arguments);
  9052. }
  9053. return deprecated;
  9054. }
  9055. /**
  9056. * Checks `localStorage` for boolean values for the given `name`.
  9057. *
  9058. * @param {String} name
  9059. * @returns {Boolean}
  9060. * @api private
  9061. */
  9062. function config (name) {
  9063. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  9064. try {
  9065. if (!global.localStorage) return false;
  9066. } catch (_) {
  9067. return false;
  9068. }
  9069. var val = global.localStorage[name];
  9070. if (null == val) return false;
  9071. return String(val).toLowerCase() === 'true';
  9072. }
  9073. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9074. },{}],53:[function(require,module,exports){
  9075. arguments[4][18][0].apply(exports,arguments)
  9076. },{"dup":18}],54:[function(require,module,exports){
  9077. module.exports = function isBuffer(arg) {
  9078. return arg && typeof arg === 'object'
  9079. && typeof arg.copy === 'function'
  9080. && typeof arg.fill === 'function'
  9081. && typeof arg.readUInt8 === 'function';
  9082. }
  9083. },{}],55:[function(require,module,exports){
  9084. (function (process,global){
  9085. // Copyright Joyent, Inc. and other Node contributors.
  9086. //
  9087. // Permission is hereby granted, free of charge, to any person obtaining a
  9088. // copy of this software and associated documentation files (the
  9089. // "Software"), to deal in the Software without restriction, including
  9090. // without limitation the rights to use, copy, modify, merge, publish,
  9091. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9092. // persons to whom the Software is furnished to do so, subject to the
  9093. // following conditions:
  9094. //
  9095. // The above copyright notice and this permission notice shall be included
  9096. // in all copies or substantial portions of the Software.
  9097. //
  9098. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9099. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9100. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9101. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9102. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9103. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9104. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9105. var formatRegExp = /%[sdj%]/g;
  9106. exports.format = function(f) {
  9107. if (!isString(f)) {
  9108. var objects = [];
  9109. for (var i = 0; i < arguments.length; i++) {
  9110. objects.push(inspect(arguments[i]));
  9111. }
  9112. return objects.join(' ');
  9113. }
  9114. var i = 1;
  9115. var args = arguments;
  9116. var len = args.length;
  9117. var str = String(f).replace(formatRegExp, function(x) {
  9118. if (x === '%%') return '%';
  9119. if (i >= len) return x;
  9120. switch (x) {
  9121. case '%s': return String(args[i++]);
  9122. case '%d': return Number(args[i++]);
  9123. case '%j':
  9124. try {
  9125. return JSON.stringify(args[i++]);
  9126. } catch (_) {
  9127. return '[Circular]';
  9128. }
  9129. default:
  9130. return x;
  9131. }
  9132. });
  9133. for (var x = args[i]; i < len; x = args[++i]) {
  9134. if (isNull(x) || !isObject(x)) {
  9135. str += ' ' + x;
  9136. } else {
  9137. str += ' ' + inspect(x);
  9138. }
  9139. }
  9140. return str;
  9141. };
  9142. // Mark that a method should not be used.
  9143. // Returns a modified function which warns once by default.
  9144. // If --no-deprecation is set, then it is a no-op.
  9145. exports.deprecate = function(fn, msg) {
  9146. // Allow for deprecating things in the process of starting up.
  9147. if (isUndefined(global.process)) {
  9148. return function() {
  9149. return exports.deprecate(fn, msg).apply(this, arguments);
  9150. };
  9151. }
  9152. if (process.noDeprecation === true) {
  9153. return fn;
  9154. }
  9155. var warned = false;
  9156. function deprecated() {
  9157. if (!warned) {
  9158. if (process.throwDeprecation) {
  9159. throw new Error(msg);
  9160. } else if (process.traceDeprecation) {
  9161. console.trace(msg);
  9162. } else {
  9163. console.error(msg);
  9164. }
  9165. warned = true;
  9166. }
  9167. return fn.apply(this, arguments);
  9168. }
  9169. return deprecated;
  9170. };
  9171. var debugs = {};
  9172. var debugEnviron;
  9173. exports.debuglog = function(set) {
  9174. if (isUndefined(debugEnviron))
  9175. debugEnviron = process.env.NODE_DEBUG || '';
  9176. set = set.toUpperCase();
  9177. if (!debugs[set]) {
  9178. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  9179. var pid = process.pid;
  9180. debugs[set] = function() {
  9181. var msg = exports.format.apply(exports, arguments);
  9182. console.error('%s %d: %s', set, pid, msg);
  9183. };
  9184. } else {
  9185. debugs[set] = function() {};
  9186. }
  9187. }
  9188. return debugs[set];
  9189. };
  9190. /**
  9191. * Echos the value of a value. Trys to print the value out
  9192. * in the best way possible given the different types.
  9193. *
  9194. * @param {Object} obj The object to print out.
  9195. * @param {Object} opts Optional options object that alters the output.
  9196. */
  9197. /* legacy: obj, showHidden, depth, colors*/
  9198. function inspect(obj, opts) {
  9199. // default options
  9200. var ctx = {
  9201. seen: [],
  9202. stylize: stylizeNoColor
  9203. };
  9204. // legacy...
  9205. if (arguments.length >= 3) ctx.depth = arguments[2];
  9206. if (arguments.length >= 4) ctx.colors = arguments[3];
  9207. if (isBoolean(opts)) {
  9208. // legacy...
  9209. ctx.showHidden = opts;
  9210. } else if (opts) {
  9211. // got an "options" object
  9212. exports._extend(ctx, opts);
  9213. }
  9214. // set default options
  9215. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  9216. if (isUndefined(ctx.depth)) ctx.depth = 2;
  9217. if (isUndefined(ctx.colors)) ctx.colors = false;
  9218. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  9219. if (ctx.colors) ctx.stylize = stylizeWithColor;
  9220. return formatValue(ctx, obj, ctx.depth);
  9221. }
  9222. exports.inspect = inspect;
  9223. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  9224. inspect.colors = {
  9225. 'bold' : [1, 22],
  9226. 'italic' : [3, 23],
  9227. 'underline' : [4, 24],
  9228. 'inverse' : [7, 27],
  9229. 'white' : [37, 39],
  9230. 'grey' : [90, 39],
  9231. 'black' : [30, 39],
  9232. 'blue' : [34, 39],
  9233. 'cyan' : [36, 39],
  9234. 'green' : [32, 39],
  9235. 'magenta' : [35, 39],
  9236. 'red' : [31, 39],
  9237. 'yellow' : [33, 39]
  9238. };
  9239. // Don't use 'blue' not visible on cmd.exe
  9240. inspect.styles = {
  9241. 'special': 'cyan',
  9242. 'number': 'yellow',
  9243. 'boolean': 'yellow',
  9244. 'undefined': 'grey',
  9245. 'null': 'bold',
  9246. 'string': 'green',
  9247. 'date': 'magenta',
  9248. // "name": intentionally not styling
  9249. 'regexp': 'red'
  9250. };
  9251. function stylizeWithColor(str, styleType) {
  9252. var style = inspect.styles[styleType];
  9253. if (style) {
  9254. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  9255. '\u001b[' + inspect.colors[style][1] + 'm';
  9256. } else {
  9257. return str;
  9258. }
  9259. }
  9260. function stylizeNoColor(str, styleType) {
  9261. return str;
  9262. }
  9263. function arrayToHash(array) {
  9264. var hash = {};
  9265. array.forEach(function(val, idx) {
  9266. hash[val] = true;
  9267. });
  9268. return hash;
  9269. }
  9270. function formatValue(ctx, value, recurseTimes) {
  9271. // Provide a hook for user-specified inspect functions.
  9272. // Check that value is an object with an inspect function on it
  9273. if (ctx.customInspect &&
  9274. value &&
  9275. isFunction(value.inspect) &&
  9276. // Filter out the util module, it's inspect function is special
  9277. value.inspect !== exports.inspect &&
  9278. // Also filter out any prototype objects using the circular check.
  9279. !(value.constructor && value.constructor.prototype === value)) {
  9280. var ret = value.inspect(recurseTimes, ctx);
  9281. if (!isString(ret)) {
  9282. ret = formatValue(ctx, ret, recurseTimes);
  9283. }
  9284. return ret;
  9285. }
  9286. // Primitive types cannot have properties
  9287. var primitive = formatPrimitive(ctx, value);
  9288. if (primitive) {
  9289. return primitive;
  9290. }
  9291. // Look up the keys of the object.
  9292. var keys = Object.keys(value);
  9293. var visibleKeys = arrayToHash(keys);
  9294. if (ctx.showHidden) {
  9295. keys = Object.getOwnPropertyNames(value);
  9296. }
  9297. // IE doesn't make error fields non-enumerable
  9298. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  9299. if (isError(value)
  9300. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  9301. return formatError(value);
  9302. }
  9303. // Some type of object without properties can be shortcutted.
  9304. if (keys.length === 0) {
  9305. if (isFunction(value)) {
  9306. var name = value.name ? ': ' + value.name : '';
  9307. return ctx.stylize('[Function' + name + ']', 'special');
  9308. }
  9309. if (isRegExp(value)) {
  9310. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  9311. }
  9312. if (isDate(value)) {
  9313. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  9314. }
  9315. if (isError(value)) {
  9316. return formatError(value);
  9317. }
  9318. }
  9319. var base = '', array = false, braces = ['{', '}'];
  9320. // Make Array say that they are Array
  9321. if (isArray(value)) {
  9322. array = true;
  9323. braces = ['[', ']'];
  9324. }
  9325. // Make functions say that they are functions
  9326. if (isFunction(value)) {
  9327. var n = value.name ? ': ' + value.name : '';
  9328. base = ' [Function' + n + ']';
  9329. }
  9330. // Make RegExps say that they are RegExps
  9331. if (isRegExp(value)) {
  9332. base = ' ' + RegExp.prototype.toString.call(value);
  9333. }
  9334. // Make dates with properties first say the date
  9335. if (isDate(value)) {
  9336. base = ' ' + Date.prototype.toUTCString.call(value);
  9337. }
  9338. // Make error with message first say the error
  9339. if (isError(value)) {
  9340. base = ' ' + formatError(value);
  9341. }
  9342. if (keys.length === 0 && (!array || value.length == 0)) {
  9343. return braces[0] + base + braces[1];
  9344. }
  9345. if (recurseTimes < 0) {
  9346. if (isRegExp(value)) {
  9347. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  9348. } else {
  9349. return ctx.stylize('[Object]', 'special');
  9350. }
  9351. }
  9352. ctx.seen.push(value);
  9353. var output;
  9354. if (array) {
  9355. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  9356. } else {
  9357. output = keys.map(function(key) {
  9358. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  9359. });
  9360. }
  9361. ctx.seen.pop();
  9362. return reduceToSingleString(output, base, braces);
  9363. }
  9364. function formatPrimitive(ctx, value) {
  9365. if (isUndefined(value))
  9366. return ctx.stylize('undefined', 'undefined');
  9367. if (isString(value)) {
  9368. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  9369. .replace(/'/g, "\\'")
  9370. .replace(/\\"/g, '"') + '\'';
  9371. return ctx.stylize(simple, 'string');
  9372. }
  9373. if (isNumber(value))
  9374. return ctx.stylize('' + value, 'number');
  9375. if (isBoolean(value))
  9376. return ctx.stylize('' + value, 'boolean');
  9377. // For some reason typeof null is "object", so special case here.
  9378. if (isNull(value))
  9379. return ctx.stylize('null', 'null');
  9380. }
  9381. function formatError(value) {
  9382. return '[' + Error.prototype.toString.call(value) + ']';
  9383. }
  9384. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  9385. var output = [];
  9386. for (var i = 0, l = value.length; i < l; ++i) {
  9387. if (hasOwnProperty(value, String(i))) {
  9388. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  9389. String(i), true));
  9390. } else {
  9391. output.push('');
  9392. }
  9393. }
  9394. keys.forEach(function(key) {
  9395. if (!key.match(/^\d+$/)) {
  9396. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  9397. key, true));
  9398. }
  9399. });
  9400. return output;
  9401. }
  9402. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  9403. var name, str, desc;
  9404. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  9405. if (desc.get) {
  9406. if (desc.set) {
  9407. str = ctx.stylize('[Getter/Setter]', 'special');
  9408. } else {
  9409. str = ctx.stylize('[Getter]', 'special');
  9410. }
  9411. } else {
  9412. if (desc.set) {
  9413. str = ctx.stylize('[Setter]', 'special');
  9414. }
  9415. }
  9416. if (!hasOwnProperty(visibleKeys, key)) {
  9417. name = '[' + key + ']';
  9418. }
  9419. if (!str) {
  9420. if (ctx.seen.indexOf(desc.value) < 0) {
  9421. if (isNull(recurseTimes)) {
  9422. str = formatValue(ctx, desc.value, null);
  9423. } else {
  9424. str = formatValue(ctx, desc.value, recurseTimes - 1);
  9425. }
  9426. if (str.indexOf('\n') > -1) {
  9427. if (array) {
  9428. str = str.split('\n').map(function(line) {
  9429. return ' ' + line;
  9430. }).join('\n').substr(2);
  9431. } else {
  9432. str = '\n' + str.split('\n').map(function(line) {
  9433. return ' ' + line;
  9434. }).join('\n');
  9435. }
  9436. }
  9437. } else {
  9438. str = ctx.stylize('[Circular]', 'special');
  9439. }
  9440. }
  9441. if (isUndefined(name)) {
  9442. if (array && key.match(/^\d+$/)) {
  9443. return str;
  9444. }
  9445. name = JSON.stringify('' + key);
  9446. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  9447. name = name.substr(1, name.length - 2);
  9448. name = ctx.stylize(name, 'name');
  9449. } else {
  9450. name = name.replace(/'/g, "\\'")
  9451. .replace(/\\"/g, '"')
  9452. .replace(/(^"|"$)/g, "'");
  9453. name = ctx.stylize(name, 'string');
  9454. }
  9455. }
  9456. return name + ': ' + str;
  9457. }
  9458. function reduceToSingleString(output, base, braces) {
  9459. var numLinesEst = 0;
  9460. var length = output.reduce(function(prev, cur) {
  9461. numLinesEst++;
  9462. if (cur.indexOf('\n') >= 0) numLinesEst++;
  9463. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  9464. }, 0);
  9465. if (length > 60) {
  9466. return braces[0] +
  9467. (base === '' ? '' : base + '\n ') +
  9468. ' ' +
  9469. output.join(',\n ') +
  9470. ' ' +
  9471. braces[1];
  9472. }
  9473. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  9474. }
  9475. // NOTE: These type checking functions intentionally don't use `instanceof`
  9476. // because it is fragile and can be easily faked with `Object.create()`.
  9477. function isArray(ar) {
  9478. return Array.isArray(ar);
  9479. }
  9480. exports.isArray = isArray;
  9481. function isBoolean(arg) {
  9482. return typeof arg === 'boolean';
  9483. }
  9484. exports.isBoolean = isBoolean;
  9485. function isNull(arg) {
  9486. return arg === null;
  9487. }
  9488. exports.isNull = isNull;
  9489. function isNullOrUndefined(arg) {
  9490. return arg == null;
  9491. }
  9492. exports.isNullOrUndefined = isNullOrUndefined;
  9493. function isNumber(arg) {
  9494. return typeof arg === 'number';
  9495. }
  9496. exports.isNumber = isNumber;
  9497. function isString(arg) {
  9498. return typeof arg === 'string';
  9499. }
  9500. exports.isString = isString;
  9501. function isSymbol(arg) {
  9502. return typeof arg === 'symbol';
  9503. }
  9504. exports.isSymbol = isSymbol;
  9505. function isUndefined(arg) {
  9506. return arg === void 0;
  9507. }
  9508. exports.isUndefined = isUndefined;
  9509. function isRegExp(re) {
  9510. return isObject(re) && objectToString(re) === '[object RegExp]';
  9511. }
  9512. exports.isRegExp = isRegExp;
  9513. function isObject(arg) {
  9514. return typeof arg === 'object' && arg !== null;
  9515. }
  9516. exports.isObject = isObject;
  9517. function isDate(d) {
  9518. return isObject(d) && objectToString(d) === '[object Date]';
  9519. }
  9520. exports.isDate = isDate;
  9521. function isError(e) {
  9522. return isObject(e) &&
  9523. (objectToString(e) === '[object Error]' || e instanceof Error);
  9524. }
  9525. exports.isError = isError;
  9526. function isFunction(arg) {
  9527. return typeof arg === 'function';
  9528. }
  9529. exports.isFunction = isFunction;
  9530. function isPrimitive(arg) {
  9531. return arg === null ||
  9532. typeof arg === 'boolean' ||
  9533. typeof arg === 'number' ||
  9534. typeof arg === 'string' ||
  9535. typeof arg === 'symbol' || // ES6 symbol
  9536. typeof arg === 'undefined';
  9537. }
  9538. exports.isPrimitive = isPrimitive;
  9539. exports.isBuffer = require('./support/isBuffer');
  9540. function objectToString(o) {
  9541. return Object.prototype.toString.call(o);
  9542. }
  9543. function pad(n) {
  9544. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  9545. }
  9546. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  9547. 'Oct', 'Nov', 'Dec'];
  9548. // 26 Feb 16:19:34
  9549. function timestamp() {
  9550. var d = new Date();
  9551. var time = [pad(d.getHours()),
  9552. pad(d.getMinutes()),
  9553. pad(d.getSeconds())].join(':');
  9554. return [d.getDate(), months[d.getMonth()], time].join(' ');
  9555. }
  9556. // log is just a thin wrapper to console.log that prepends a timestamp
  9557. exports.log = function() {
  9558. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  9559. };
  9560. /**
  9561. * Inherit the prototype methods from one constructor into another.
  9562. *
  9563. * The Function.prototype.inherits from lang.js rewritten as a standalone
  9564. * function (not on Function.prototype). NOTE: If this file is to be loaded
  9565. * during bootstrapping this function needs to be rewritten using some native
  9566. * functions as prototype setup using normal JavaScript does not work as
  9567. * expected during bootstrapping (see mirror.js in r114903).
  9568. *
  9569. * @param {function} ctor Constructor function which needs to inherit the
  9570. * prototype.
  9571. * @param {function} superCtor Constructor function to inherit prototype from.
  9572. */
  9573. exports.inherits = require('inherits');
  9574. exports._extend = function(origin, add) {
  9575. // Don't do anything if add isn't an object
  9576. if (!add || !isObject(add)) return origin;
  9577. var keys = Object.keys(add);
  9578. var i = keys.length;
  9579. while (i--) {
  9580. origin[keys[i]] = add[keys[i]];
  9581. }
  9582. return origin;
  9583. };
  9584. function hasOwnProperty(obj, prop) {
  9585. return Object.prototype.hasOwnProperty.call(obj, prop);
  9586. }
  9587. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9588. },{"./support/isBuffer":54,"_process":30,"inherits":53}],56:[function(require,module,exports){
  9589. (function (process,global){
  9590. 'use strict'
  9591. var Transform = require('readable-stream').Transform
  9592. var duplexify = require('duplexify')
  9593. var WS = require('ws')
  9594. var Buffer = require('safe-buffer').Buffer
  9595. module.exports = WebSocketStream
  9596. function buildProxy (options, socketWrite, socketEnd) {
  9597. var proxy = new Transform({
  9598. objectMode: options.objectMode
  9599. })
  9600. proxy._write = socketWrite
  9601. proxy._flush = socketEnd
  9602. return proxy
  9603. }
  9604. function WebSocketStream(target, protocols, options) {
  9605. var stream, socket
  9606. var isBrowser = process.title === 'browser'
  9607. var isNative = !!global.WebSocket
  9608. var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode
  9609. if (protocols && !Array.isArray(protocols) && 'object' === typeof protocols) {
  9610. // accept the "options" Object as the 2nd argument
  9611. options = protocols
  9612. protocols = null
  9613. if (typeof options.protocol === 'string' || Array.isArray(options.protocol)) {
  9614. protocols = options.protocol;
  9615. }
  9616. }
  9617. if (!options) options = {}
  9618. if (options.objectMode === undefined) {
  9619. options.objectMode = !(options.binary === true || options.binary === undefined)
  9620. }
  9621. var proxy = buildProxy(options, socketWrite, socketEnd)
  9622. if (!options.objectMode) {
  9623. proxy._writev = writev
  9624. }
  9625. // browser only: sets the maximum socket buffer size before throttling
  9626. var bufferSize = options.browserBufferSize || 1024 * 512
  9627. // browser only: how long to wait when throttling
  9628. var bufferTimeout = options.browserBufferTimeout || 1000
  9629. // use existing WebSocket object that was passed in
  9630. if (typeof target === 'object') {
  9631. socket = target
  9632. // otherwise make a new one
  9633. } else {
  9634. // special constructor treatment for native websockets in browsers, see
  9635. // https://github.com/maxogden/websocket-stream/issues/82
  9636. if (isNative && isBrowser) {
  9637. socket = new WS(target, protocols)
  9638. } else {
  9639. socket = new WS(target, protocols, options)
  9640. }
  9641. socket.binaryType = 'arraybuffer'
  9642. }
  9643. // was already open when passed in
  9644. if (socket.readyState === socket.OPEN) {
  9645. stream = proxy
  9646. } else {
  9647. stream = duplexify.obj()
  9648. socket.onopen = onopen
  9649. }
  9650. stream.socket = socket
  9651. socket.onclose = onclose
  9652. socket.onerror = onerror
  9653. socket.onmessage = onmessage
  9654. proxy.on('close', destroy)
  9655. var coerceToBuffer = !options.objectMode
  9656. function socketWriteNode(chunk, enc, next) {
  9657. // avoid errors, this never happens unless
  9658. // destroy() is called
  9659. if (socket.readyState !== socket.OPEN) {
  9660. next()
  9661. return
  9662. }
  9663. if (coerceToBuffer && typeof chunk === 'string') {
  9664. chunk = Buffer.from(chunk, 'utf8')
  9665. }
  9666. socket.send(chunk, next)
  9667. }
  9668. function socketWriteBrowser(chunk, enc, next) {
  9669. if (socket.bufferedAmount > bufferSize) {
  9670. setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
  9671. return
  9672. }
  9673. if (coerceToBuffer && typeof chunk === 'string') {
  9674. chunk = Buffer.from(chunk, 'utf8')
  9675. }
  9676. try {
  9677. socket.send(chunk)
  9678. } catch(err) {
  9679. return next(err)
  9680. }
  9681. next()
  9682. }
  9683. function socketEnd(done) {
  9684. socket.close()
  9685. done()
  9686. }
  9687. function onopen() {
  9688. stream.setReadable(proxy)
  9689. stream.setWritable(proxy)
  9690. stream.emit('connect')
  9691. }
  9692. function onclose() {
  9693. stream.end()
  9694. stream.destroy()
  9695. }
  9696. function onerror(err) {
  9697. stream.destroy(err)
  9698. }
  9699. function onmessage(event) {
  9700. var data = event.data
  9701. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  9702. else data = Buffer.from(data, 'utf8')
  9703. proxy.push(data)
  9704. }
  9705. function destroy() {
  9706. socket.close()
  9707. }
  9708. // this is to be enabled only if objectMode is false
  9709. function writev (chunks, cb) {
  9710. var buffers = new Array(chunks.length)
  9711. for (var i = 0; i < chunks.length; i++) {
  9712. if (typeof chunks[i].chunk === 'string') {
  9713. buffers[i] = Buffer.from(chunks[i], 'utf8')
  9714. } else {
  9715. buffers[i] = chunks[i].chunk
  9716. }
  9717. }
  9718. this._write(Buffer.concat(buffers), 'binary', cb)
  9719. }
  9720. return stream
  9721. }
  9722. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9723. },{"_process":30,"duplexify":15,"readable-stream":45,"safe-buffer":47,"ws":57}],57:[function(require,module,exports){
  9724. var ws = null
  9725. if (typeof WebSocket !== 'undefined') {
  9726. ws = WebSocket
  9727. } else if (typeof MozWebSocket !== 'undefined') {
  9728. ws = MozWebSocket
  9729. } else if (typeof window !== 'undefined') {
  9730. ws = window.WebSocket || window.MozWebSocket
  9731. }
  9732. module.exports = ws
  9733. },{}],58:[function(require,module,exports){
  9734. // Returns a wrapper function that returns a wrapped callback
  9735. // The wrapper function should do some stuff, and return a
  9736. // presumably different callback function.
  9737. // This makes sure that own properties are retained, so that
  9738. // decorations and such are not lost along the way.
  9739. module.exports = wrappy
  9740. function wrappy (fn, cb) {
  9741. if (fn && cb) return wrappy(fn)(cb)
  9742. if (typeof fn !== 'function')
  9743. throw new TypeError('need wrapper function')
  9744. Object.keys(fn).forEach(function (k) {
  9745. wrapper[k] = fn[k]
  9746. })
  9747. return wrapper
  9748. function wrapper() {
  9749. var args = new Array(arguments.length)
  9750. for (var i = 0; i < args.length; i++) {
  9751. args[i] = arguments[i]
  9752. }
  9753. var ret = fn.apply(this, args)
  9754. var cb = args[args.length-1]
  9755. if (typeof ret === 'function' && ret !== cb) {
  9756. Object.keys(cb).forEach(function (k) {
  9757. ret[k] = cb[k]
  9758. })
  9759. }
  9760. return ret
  9761. }
  9762. }
  9763. },{}],59:[function(require,module,exports){
  9764. module.exports = extend
  9765. var hasOwnProperty = Object.prototype.hasOwnProperty;
  9766. function extend() {
  9767. var target = {}
  9768. for (var i = 0; i < arguments.length; i++) {
  9769. var source = arguments[i]
  9770. for (var key in source) {
  9771. if (hasOwnProperty.call(source, key)) {
  9772. target[key] = source[key]
  9773. }
  9774. }
  9775. }
  9776. return target
  9777. }
  9778. },{}]},{},[8])(8)
  9779. });