mqtt.js 429 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687
  1. // function vilidator(f) {
  2. // if (typeof exports === "object" && typeof module !== "undefined") {
  3. // module.exports = f()
  4. // } else if (typeof define === "function" && define.amd) {
  5. // define([], f)
  6. // } else {
  7. // var g;
  8. // if (typeof window !== "undefined") {
  9. // g = window
  10. // } else if (typeof global !== "undefined") {
  11. // g = global
  12. // } else if (typeof self !== "undefined") {
  13. // g = self
  14. // } else {
  15. // g = this
  16. // }
  17. // g.mqtt = f()
  18. // }
  19. // }
  20. // 解决vite引入报错问题
  21. const init = function() {
  22. var define, module, exports;
  23. return (function() {
  24. function r(e, n, t) {
  25. function o(i, f) {
  26. if (!n[i]) {
  27. if (!e[i]) {
  28. var c = "function" == typeof require && require;
  29. if (!f && c) return c(i, !0);
  30. if (u) return u(i, !0);
  31. var a = new Error("Cannot find module '" + i + "'");
  32. throw a.code = "MODULE_NOT_FOUND", a
  33. }
  34. var p = n[i] = {
  35. exports: {}
  36. };
  37. e[i][0].call(p.exports, function(r) {
  38. var n = e[i][1][r];
  39. return o(n || r)
  40. }, p, p.exports, r, e, n, t)
  41. }
  42. return n[i].exports
  43. }
  44. for (var u = "function" == typeof require && require, i = 0; i < t.length; i++) o(t[i]);
  45. return o
  46. }
  47. return r
  48. })()({
  49. 1: [function(require, module, exports) {
  50. (function(process, global) {
  51. 'use strict'
  52. /**
  53. * Module dependencies
  54. */
  55. var events = require('events')
  56. var Store = require('./store')
  57. var mqttPacket = require('mqtt-packet')
  58. var Writable = require('readable-stream').Writable
  59. var inherits = require('inherits')
  60. var reInterval = require('reinterval')
  61. var validations = require('./validations')
  62. var xtend = require('xtend')
  63. var setImmediate = global.setImmediate || function(callback) {
  64. // works in node v0.8
  65. process.nextTick(callback)
  66. }
  67. var defaultConnectOptions = {
  68. keepalive: 60,
  69. reschedulePings: true,
  70. protocolId: 'MQTT',
  71. protocolVersion: 4,
  72. reconnectPeriod: 1000,
  73. connectTimeout: 30 * 1000,
  74. clean: true,
  75. resubscribe: true
  76. }
  77. var errors = {
  78. 0: '',
  79. 1: 'Unacceptable protocol version',
  80. 2: 'Identifier rejected',
  81. 3: 'Server unavailable',
  82. 4: 'Bad username or password',
  83. 5: 'Not authorized',
  84. 16: 'No matching subscribers',
  85. 17: 'No subscription existed',
  86. 128: 'Unspecified error',
  87. 129: 'Malformed Packet',
  88. 130: 'Protocol Error',
  89. 131: 'Implementation specific error',
  90. 132: 'Unsupported Protocol Version',
  91. 133: 'Client Identifier not valid',
  92. 134: 'Bad User Name or Password',
  93. 135: 'Not authorized',
  94. 136: 'Server unavailable',
  95. 137: 'Server busy',
  96. 138: 'Banned',
  97. 139: 'Server shutting down',
  98. 140: 'Bad authentication method',
  99. 141: 'Keep Alive timeout',
  100. 142: 'Session taken over',
  101. 143: 'Topic Filter invalid',
  102. 144: 'Topic Name invalid',
  103. 145: 'Packet identifier in use',
  104. 146: 'Packet Identifier not found',
  105. 147: 'Receive Maximum exceeded',
  106. 148: 'Topic Alias invalid',
  107. 149: 'Packet too large',
  108. 150: 'Message rate too high',
  109. 151: 'Quota exceeded',
  110. 152: 'Administrative action',
  111. 153: 'Payload format invalid',
  112. 154: 'Retain not supported',
  113. 155: 'QoS not supported',
  114. 156: 'Use another server',
  115. 157: 'Server moved',
  116. 158: 'Shared Subscriptions not supported',
  117. 159: 'Connection rate exceeded',
  118. 160: 'Maximum connect time',
  119. 161: 'Subscription Identifiers not supported',
  120. 162: 'Wildcard Subscriptions not supported'
  121. }
  122. function defaultId() {
  123. return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
  124. }
  125. function sendPacket(client, packet, cb) {
  126. client.emit('packetsend', packet)
  127. var result = mqttPacket.writeToStream(packet, client.stream, client.options)
  128. if (!result && cb) {
  129. client.stream.once('drain', cb)
  130. } else if (cb) {
  131. cb()
  132. }
  133. }
  134. function flush(queue) {
  135. if (queue) {
  136. Object.keys(queue).forEach(function(messageId) {
  137. if (typeof queue[messageId].cb === 'function') {
  138. queue[messageId].cb(new Error('Connection closed'))
  139. delete queue[messageId]
  140. }
  141. })
  142. }
  143. }
  144. function flushVolatile(queue) {
  145. if (queue) {
  146. Object.keys(queue).forEach(function(messageId) {
  147. if (queue[messageId].volatile && typeof queue[messageId]
  148. .cb === 'function') {
  149. queue[messageId].cb(new Error('Connection closed'))
  150. delete queue[messageId]
  151. }
  152. })
  153. }
  154. }
  155. function storeAndSend(client, packet, cb, cbStorePut) {
  156. client.outgoingStore.put(packet, function storedPacket(err) {
  157. if (err) {
  158. return cb && cb(err)
  159. }
  160. cbStorePut()
  161. sendPacket(client, packet, cb)
  162. })
  163. }
  164. function nop() {}
  165. /**
  166. * MqttClient constructor
  167. *
  168. * @param {Stream} stream - stream
  169. * @param {Object} [options] - connection options
  170. * (see Connection#connect)
  171. */
  172. function MqttClient(streamBuilder, options) {
  173. var k
  174. var that = this
  175. if (!(this instanceof MqttClient)) {
  176. return new MqttClient(streamBuilder, options)
  177. }
  178. this.options = options || {}
  179. // Defaults
  180. for (k in defaultConnectOptions) {
  181. if (typeof this.options[k] === 'undefined') {
  182. this.options[k] = defaultConnectOptions[k]
  183. } else {
  184. this.options[k] = options[k]
  185. }
  186. }
  187. this.options.clientId = (typeof options.clientId === 'string') ? options
  188. .clientId : defaultId()
  189. this.options.customHandleAcks = (options.protocolVersion === 5 && options
  190. .customHandleAcks) ? options.customHandleAcks : function() {
  191. arguments[3](0)
  192. }
  193. this.streamBuilder = streamBuilder
  194. // Inflight message storages
  195. this.outgoingStore = options.outgoingStore || new Store()
  196. this.incomingStore = options.incomingStore || new Store()
  197. // Should QoS zero messages be queued when the connection is broken?
  198. this.queueQoSZero = options.queueQoSZero === undefined ? true : options
  199. .queueQoSZero
  200. // map of subscribed topics to support reconnection
  201. this._resubscribeTopics = {}
  202. // map of a subscribe messageId and a topic
  203. this.messageIdToTopic = {}
  204. // Ping timer, setup in _setupPingTimer
  205. this.pingTimer = null
  206. // Is the client connected?
  207. this.connected = false
  208. // Are we disconnecting?
  209. this.disconnecting = false
  210. // Packet queue
  211. this.queue = []
  212. // connack timer
  213. this.connackTimer = null
  214. // Reconnect timer
  215. this.reconnectTimer = null
  216. // Is processing store?
  217. this._storeProcessing = false
  218. // Packet Ids are put into the store during store processing
  219. this._packetIdsDuringStoreProcessing = {}
  220. /**
  221. * MessageIDs starting with 1
  222. * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
  223. */
  224. this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
  225. // Inflight callbacks
  226. this.outgoing = {}
  227. // True if connection is first time.
  228. this._firstConnection = true
  229. // Mark disconnected on stream close
  230. this.on('close', function() {
  231. this.connected = false
  232. clearTimeout(this.connackTimer)
  233. })
  234. // Send queued packets
  235. this.on('connect', function() {
  236. var queue = this.queue
  237. function deliver() {
  238. var entry = queue.shift()
  239. var packet = null
  240. if (!entry) {
  241. return
  242. }
  243. packet = entry.packet
  244. that._sendPacket(
  245. packet,
  246. function(err) {
  247. if (entry.cb) {
  248. entry.cb(err)
  249. }
  250. deliver()
  251. }
  252. )
  253. }
  254. deliver()
  255. })
  256. // Clear ping timer
  257. this.on('close', function() {
  258. if (that.pingTimer !== null) {
  259. that.pingTimer.clear()
  260. that.pingTimer = null
  261. }
  262. })
  263. // Setup reconnect timer on disconnect
  264. this.on('close', this._setupReconnect)
  265. events.EventEmitter.call(this)
  266. this._setupStream()
  267. }
  268. inherits(MqttClient, events.EventEmitter)
  269. /**
  270. * setup the event handlers in the inner stream.
  271. *
  272. * @api private
  273. */
  274. MqttClient.prototype._setupStream = function() {
  275. var connectPacket
  276. var that = this
  277. var writable = new Writable()
  278. var parser = mqttPacket.parser(this.options)
  279. var completeParse = null
  280. var packets = []
  281. this._clearReconnect()
  282. this.stream = this.streamBuilder(this)
  283. parser.on('packet', function(packet) {
  284. packets.push(packet)
  285. })
  286. function nextTickWork() {
  287. if (packets.length) {
  288. process.nextTick(work)
  289. } else {
  290. var done = completeParse
  291. completeParse = null
  292. done()
  293. }
  294. }
  295. function work() {
  296. var packet = packets.shift()
  297. if (packet) {
  298. that._handlePacket(packet, nextTickWork)
  299. } else {
  300. var done = completeParse
  301. completeParse = null
  302. if (done) done()
  303. }
  304. }
  305. writable._write = function(buf, enc, done) {
  306. completeParse = done
  307. parser.parse(buf)
  308. work()
  309. }
  310. this.stream.pipe(writable)
  311. // Suppress connection errors
  312. this.stream.on('error', nop)
  313. // Echo stream close
  314. this.stream.on('close', function() {
  315. flushVolatile(that.outgoing)
  316. that.emit('close')
  317. })
  318. // Send a connect packet
  319. connectPacket = Object.create(this.options)
  320. connectPacket.cmd = 'connect'
  321. // avoid message queue
  322. sendPacket(this, connectPacket)
  323. // Echo connection errors
  324. parser.on('error', this.emit.bind(this, 'error'))
  325. // auth
  326. if (this.options.properties) {
  327. if (!this.options.properties.authenticationMethod && this.options
  328. .properties.authenticationData) {
  329. this.emit('error', new Error(
  330. 'Packet has no Authentication Method'))
  331. return this
  332. }
  333. if (this.options.properties.authenticationMethod && this.options
  334. .authPacket && typeof this.options.authPacket === 'object') {
  335. var authPacket = xtend({
  336. cmd: 'auth',
  337. reasonCode: 0
  338. }, this.options.authPacket)
  339. sendPacket(this, authPacket)
  340. }
  341. }
  342. // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
  343. this.stream.setMaxListeners(1000)
  344. clearTimeout(this.connackTimer)
  345. this.connackTimer = setTimeout(function() {
  346. that._cleanUp(true)
  347. }, this.options.connectTimeout)
  348. }
  349. MqttClient.prototype._handlePacket = function(packet, done) {
  350. var options = this.options
  351. if (options.protocolVersion === 5 && options.properties && options
  352. .properties.maximumPacketSize && options.properties
  353. .maximumPacketSize < packet.length) {
  354. this.emit('error', new Error('exceeding packets size ' + packet
  355. .cmd))
  356. this.end({
  357. reasonCode: 149,
  358. properties: {
  359. reasonString: 'Maximum packet size was exceeded'
  360. }
  361. })
  362. return this
  363. }
  364. this.emit('packetreceive', packet)
  365. switch (packet.cmd) {
  366. case 'publish':
  367. this._handlePublish(packet, done)
  368. break
  369. case 'puback':
  370. case 'pubrec':
  371. case 'pubcomp':
  372. case 'suback':
  373. case 'unsuback':
  374. this._handleAck(packet)
  375. done()
  376. break
  377. case 'pubrel':
  378. this._handlePubrel(packet, done)
  379. break
  380. case 'connack':
  381. this._handleConnack(packet)
  382. done()
  383. break
  384. case 'pingresp':
  385. this._handlePingresp(packet)
  386. done()
  387. break
  388. case 'disconnect':
  389. this._handleDisconnect(packet)
  390. done()
  391. break
  392. default:
  393. // do nothing
  394. // maybe we should do an error handling
  395. // or just log it
  396. break
  397. }
  398. }
  399. MqttClient.prototype._checkDisconnecting = function(callback) {
  400. if (this.disconnecting) {
  401. if (callback) {
  402. callback(new Error('client disconnecting'))
  403. } else {
  404. this.emit('error', new Error('client disconnecting'))
  405. }
  406. }
  407. return this.disconnecting
  408. }
  409. /**
  410. * publish - publish <message> to <topic>
  411. *
  412. * @param {String} topic - topic to publish to
  413. * @param {String, Buffer} message - message to publish
  414. * @param {Object} [opts] - publish options, includes:
  415. * {Number} qos - qos level to publish on
  416. * {Boolean} retain - whether or not to retain the message
  417. * {Boolean} dup - whether or not mark a message as duplicate
  418. * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
  419. * @param {Function} [callback] - function(err){}
  420. * called when publish succeeds or fails
  421. * @returns {MqttClient} this - for chaining
  422. * @api public
  423. *
  424. * @example client.publish('topic', 'message');
  425. * @example
  426. * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
  427. * @example client.publish('topic', 'message', console.log);
  428. */
  429. MqttClient.prototype.publish = function(topic, message, opts, callback) {
  430. var packet
  431. var options = this.options
  432. // .publish(topic, payload, cb);
  433. if (typeof opts === 'function') {
  434. callback = opts
  435. opts = null
  436. }
  437. // default opts
  438. var defaultOpts = {
  439. qos: 0,
  440. retain: false,
  441. dup: false
  442. }
  443. opts = xtend(defaultOpts, opts)
  444. if (this._checkDisconnecting(callback)) {
  445. return this
  446. }
  447. packet = {
  448. cmd: 'publish',
  449. topic: topic,
  450. payload: message,
  451. qos: opts.qos,
  452. retain: opts.retain,
  453. messageId: this._nextId(),
  454. dup: opts.dup
  455. }
  456. if (options.protocolVersion === 5) {
  457. packet.properties = opts.properties
  458. if ((!options.properties && packet.properties && packet.properties
  459. .topicAlias) || ((opts.properties && options.properties) &&
  460. ((opts.properties.topicAlias && options.properties
  461. .topicAliasMaximum && opts.properties.topicAlias >
  462. options.properties.topicAliasMaximum) ||
  463. (!options.properties.topicAliasMaximum && opts
  464. .properties.topicAlias)))) {
  465. /*
  466. if we are don`t setup topic alias or
  467. topic alias maximum less than topic alias or
  468. server don`t give topic alias maximum,
  469. we are removing topic alias from packet
  470. */
  471. delete packet.properties.topicAlias
  472. }
  473. }
  474. switch (opts.qos) {
  475. case 1:
  476. case 2:
  477. // Add to callbacks
  478. this.outgoing[packet.messageId] = {
  479. volatile: false,
  480. cb: callback || nop
  481. }
  482. if (this._storeProcessing) {
  483. this._packetIdsDuringStoreProcessing[packet.messageId] =
  484. false
  485. this._storePacket(packet, undefined, opts.cbStorePut)
  486. } else {
  487. this._sendPacket(packet, undefined, opts.cbStorePut)
  488. }
  489. break
  490. default:
  491. if (this._storeProcessing) {
  492. this._storePacket(packet, callback, opts.cbStorePut)
  493. } else {
  494. this._sendPacket(packet, callback, opts.cbStorePut)
  495. }
  496. break
  497. }
  498. return this
  499. }
  500. /**
  501. * subscribe - subscribe to <topic>
  502. *
  503. * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
  504. * @param {Object} [opts] - optional subscription options, includes:
  505. * {Number} qos - subscribe qos level
  506. * @param {Function} [callback] - function(err, granted){} where:
  507. * {Error} err - subscription error (none at the moment!)
  508. * {Array} granted - array of {topic: 't', qos: 0}
  509. * @returns {MqttClient} this - for chaining
  510. * @api public
  511. * @example client.subscribe('topic');
  512. * @example client.subscribe('topic', {qos: 1});
  513. * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
  514. * @example client.subscribe('topic', console.log);
  515. */
  516. MqttClient.prototype.subscribe = function() {
  517. var packet
  518. var args = new Array(arguments.length)
  519. for (var i = 0; i < arguments.length; i++) {
  520. args[i] = arguments[i]
  521. }
  522. var subs = []
  523. var obj = args.shift()
  524. var resubscribe = obj.resubscribe
  525. var callback = args.pop() || nop
  526. var opts = args.pop()
  527. var invalidTopic
  528. var that = this
  529. var version = this.options.protocolVersion
  530. delete obj.resubscribe
  531. if (typeof obj === 'string') {
  532. obj = [obj]
  533. }
  534. if (typeof callback !== 'function') {
  535. opts = callback
  536. callback = nop
  537. }
  538. invalidTopic = validations.validateTopics(obj)
  539. if (invalidTopic !== null) {
  540. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  541. return this
  542. }
  543. if (this._checkDisconnecting(callback)) {
  544. return this
  545. }
  546. var defaultOpts = {
  547. qos: 0
  548. }
  549. if (version === 5) {
  550. defaultOpts.nl = false
  551. defaultOpts.rap = false
  552. defaultOpts.rh = 0
  553. }
  554. opts = xtend(defaultOpts, opts)
  555. if (Array.isArray(obj)) {
  556. obj.forEach(function(topic) {
  557. if (!that._resubscribeTopics.hasOwnProperty(topic) ||
  558. that._resubscribeTopics[topic].qos < opts.qos ||
  559. resubscribe) {
  560. var currentOpts = {
  561. topic: topic,
  562. qos: opts.qos
  563. }
  564. if (version === 5) {
  565. currentOpts.nl = opts.nl
  566. currentOpts.rap = opts.rap
  567. currentOpts.rh = opts.rh
  568. currentOpts.properties = opts.properties
  569. }
  570. subs.push(currentOpts)
  571. }
  572. })
  573. } else {
  574. Object
  575. .keys(obj)
  576. .forEach(function(k) {
  577. if (!that._resubscribeTopics.hasOwnProperty(k) ||
  578. that._resubscribeTopics[k].qos < obj[k].qos ||
  579. resubscribe) {
  580. var currentOpts = {
  581. topic: k,
  582. qos: obj[k].qos
  583. }
  584. if (version === 5) {
  585. currentOpts.nl = obj[k].nl
  586. currentOpts.rap = obj[k].rap
  587. currentOpts.rh = obj[k].rh
  588. currentOpts.properties = opts.properties
  589. }
  590. subs.push(currentOpts)
  591. }
  592. })
  593. }
  594. packet = {
  595. cmd: 'subscribe',
  596. subscriptions: subs,
  597. qos: 1,
  598. retain: false,
  599. dup: false,
  600. messageId: this._nextId()
  601. }
  602. if (opts.properties) {
  603. packet.properties = opts.properties
  604. }
  605. if (!subs.length) {
  606. callback(null, [])
  607. return
  608. }
  609. // subscriptions to resubscribe to in case of disconnect
  610. if (this.options.resubscribe) {
  611. var topics = []
  612. subs.forEach(function(sub) {
  613. if (that.options.reconnectPeriod > 0) {
  614. var topic = {
  615. qos: sub.qos
  616. }
  617. if (version === 5) {
  618. topic.nl = sub.nl || false
  619. topic.rap = sub.rap || false
  620. topic.rh = sub.rh || 0
  621. topic.properties = sub.properties
  622. }
  623. that._resubscribeTopics[sub.topic] = topic
  624. topics.push(sub.topic)
  625. }
  626. })
  627. that.messageIdToTopic[packet.messageId] = topics
  628. }
  629. this.outgoing[packet.messageId] = {
  630. volatile: true,
  631. cb: function(err, packet) {
  632. if (!err) {
  633. var granted = packet.granted
  634. for (var i = 0; i < granted.length; i += 1) {
  635. subs[i].qos = granted[i]
  636. }
  637. }
  638. callback(err, subs)
  639. }
  640. }
  641. this._sendPacket(packet)
  642. return this
  643. }
  644. /**
  645. * unsubscribe - unsubscribe from topic(s)
  646. *
  647. * @param {String, Array} topic - topics to unsubscribe from
  648. * @param {Object} [opts] - optional subscription options, includes:
  649. * {Object} properties - properties of unsubscribe packet
  650. * @param {Function} [callback] - callback fired on unsuback
  651. * @returns {MqttClient} this - for chaining
  652. * @api public
  653. * @example client.unsubscribe('topic');
  654. * @example client.unsubscribe('topic', console.log);
  655. */
  656. MqttClient.prototype.unsubscribe = function() {
  657. var packet = {
  658. cmd: 'unsubscribe',
  659. qos: 1,
  660. messageId: this._nextId()
  661. }
  662. var that = this
  663. var args = new Array(arguments.length)
  664. for (var i = 0; i < arguments.length; i++) {
  665. args[i] = arguments[i]
  666. }
  667. var topic = args.shift()
  668. var callback = args.pop() || nop
  669. var opts = args.pop()
  670. if (typeof topic === 'string') {
  671. topic = [topic]
  672. }
  673. if (typeof callback !== 'function') {
  674. opts = callback
  675. callback = nop
  676. }
  677. if (this._checkDisconnecting(callback)) {
  678. return this
  679. }
  680. if (typeof topic === 'string') {
  681. packet.unsubscriptions = [topic]
  682. } else if (typeof topic === 'object' && topic.length) {
  683. packet.unsubscriptions = topic
  684. }
  685. if (this.options.resubscribe) {
  686. packet.unsubscriptions.forEach(function(topic) {
  687. delete that._resubscribeTopics[topic]
  688. })
  689. }
  690. if (typeof opts === 'object' && opts.properties) {
  691. packet.properties = opts.properties
  692. }
  693. this.outgoing[packet.messageId] = {
  694. volatile: true,
  695. cb: callback
  696. }
  697. this._sendPacket(packet)
  698. return this
  699. }
  700. /**
  701. * end - close connection
  702. *
  703. * @returns {MqttClient} this - for chaining
  704. * @param {Boolean} force - do not wait for all in-flight messages to be acked
  705. * @param {Function} cb - called when the client has been closed
  706. *
  707. * @api public
  708. */
  709. MqttClient.prototype.end = function() {
  710. var that = this
  711. var force = arguments[0]
  712. var opts = arguments[1]
  713. var cb = arguments[2]
  714. if (force == null || typeof force !== 'boolean') {
  715. cb = opts || nop
  716. opts = force
  717. force = false
  718. if (typeof opts !== 'object') {
  719. cb = opts
  720. opts = null
  721. if (typeof cb !== 'function') {
  722. cb = nop
  723. }
  724. }
  725. }
  726. if (typeof opts !== 'object') {
  727. cb = opts
  728. opts = null
  729. }
  730. cb = cb || nop
  731. function closeStores() {
  732. that.disconnected = true
  733. that.incomingStore.close(function() {
  734. that.outgoingStore.close(function() {
  735. if (cb) {
  736. cb.apply(null, arguments)
  737. }
  738. that.emit('end')
  739. })
  740. })
  741. if (that._deferredReconnect) {
  742. that._deferredReconnect()
  743. }
  744. }
  745. function finish() {
  746. // defer closesStores of an I/O cycle,
  747. // just to make sure things are
  748. // ok for websockets
  749. that._cleanUp(force, setImmediate.bind(null, closeStores), opts)
  750. }
  751. if (this.disconnecting) {
  752. return this
  753. }
  754. this._clearReconnect()
  755. this.disconnecting = true
  756. if (!force && Object.keys(this.outgoing).length > 0) {
  757. // wait 10ms, just to be sure we received all of it
  758. this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
  759. } else {
  760. finish()
  761. }
  762. return this
  763. }
  764. /**
  765. * removeOutgoingMessage - remove a message in outgoing store
  766. * the outgoing callback will be called withe Error('Message removed') if the message is removed
  767. *
  768. * @param {Number} mid - messageId to remove message
  769. * @returns {MqttClient} this - for chaining
  770. * @api public
  771. *
  772. * @example client.removeOutgoingMessage(client.getLastMessageId());
  773. */
  774. MqttClient.prototype.removeOutgoingMessage = function(mid) {
  775. var cb = this.outgoing[mid] ? this.outgoing[mid].cb : null
  776. delete this.outgoing[mid]
  777. this.outgoingStore.del({
  778. messageId: mid
  779. }, function() {
  780. cb(new Error('Message removed'))
  781. })
  782. return this
  783. }
  784. /**
  785. * reconnect - connect again using the same options as connect()
  786. *
  787. * @param {Object} [opts] - optional reconnect options, includes:
  788. * {Store} incomingStore - a store for the incoming packets
  789. * {Store} outgoingStore - a store for the outgoing packets
  790. * if opts is not given, current stores are used
  791. * @returns {MqttClient} this - for chaining
  792. *
  793. * @api public
  794. */
  795. MqttClient.prototype.reconnect = function(opts) {
  796. var that = this
  797. var f = function() {
  798. if (opts) {
  799. that.options.incomingStore = opts.incomingStore
  800. that.options.outgoingStore = opts.outgoingStore
  801. } else {
  802. that.options.incomingStore = null
  803. that.options.outgoingStore = null
  804. }
  805. that.incomingStore = that.options.incomingStore || new Store()
  806. that.outgoingStore = that.options.outgoingStore || new Store()
  807. that.disconnecting = false
  808. that.disconnected = false
  809. that._deferredReconnect = null
  810. that._reconnect()
  811. }
  812. if (this.disconnecting && !this.disconnected) {
  813. this._deferredReconnect = f
  814. } else {
  815. f()
  816. }
  817. return this
  818. }
  819. /**
  820. * _reconnect - implement reconnection
  821. * @api privateish
  822. */
  823. MqttClient.prototype._reconnect = function() {
  824. this.emit('reconnect')
  825. this._setupStream()
  826. }
  827. /**
  828. * _setupReconnect - setup reconnect timer
  829. */
  830. MqttClient.prototype._setupReconnect = function() {
  831. var that = this
  832. if (!that.disconnecting && !that.reconnectTimer && (that.options
  833. .reconnectPeriod > 0)) {
  834. if (!this.reconnecting) {
  835. this.emit('offline')
  836. this.reconnecting = true
  837. }
  838. that.reconnectTimer = setInterval(function() {
  839. that._reconnect()
  840. }, that.options.reconnectPeriod)
  841. }
  842. }
  843. /**
  844. * _clearReconnect - clear the reconnect timer
  845. */
  846. MqttClient.prototype._clearReconnect = function() {
  847. if (this.reconnectTimer) {
  848. clearInterval(this.reconnectTimer)
  849. this.reconnectTimer = null
  850. }
  851. }
  852. /**
  853. * _cleanUp - clean up on connection end
  854. * @api private
  855. */
  856. MqttClient.prototype._cleanUp = function(forced, done) {
  857. var opts = arguments[2]
  858. if (done) {
  859. this.stream.on('close', done)
  860. }
  861. if (forced) {
  862. if ((this.options.reconnectPeriod === 0) && this.options.clean) {
  863. flush(this.outgoing)
  864. }
  865. this.stream.destroy()
  866. } else {
  867. var packet = xtend({
  868. cmd: 'disconnect'
  869. }, opts)
  870. this._sendPacket(
  871. packet,
  872. setImmediate.bind(
  873. null,
  874. this.stream.end.bind(this.stream)
  875. )
  876. )
  877. }
  878. if (!this.disconnecting) {
  879. this._clearReconnect()
  880. this._setupReconnect()
  881. }
  882. if (this.pingTimer !== null) {
  883. this.pingTimer.clear()
  884. this.pingTimer = null
  885. }
  886. if (done && !this.connected) {
  887. this.stream.removeListener('close', done)
  888. done()
  889. }
  890. }
  891. /**
  892. * _sendPacket - send or queue a packet
  893. * @param {String} type - packet type (see `protocol`)
  894. * @param {Object} packet - packet options
  895. * @param {Function} cb - callback when the packet is sent
  896. * @param {Function} cbStorePut - called when message is put into outgoingStore
  897. * @api private
  898. */
  899. MqttClient.prototype._sendPacket = function(packet, cb, cbStorePut) {
  900. cbStorePut = cbStorePut || nop
  901. if (!this.connected) {
  902. this._storePacket(packet, cb, cbStorePut)
  903. return
  904. }
  905. // When sending a packet, reschedule the ping timer
  906. this._shiftPingInterval()
  907. switch (packet.cmd) {
  908. case 'publish':
  909. break
  910. case 'pubrel':
  911. storeAndSend(this, packet, cb, cbStorePut)
  912. return
  913. default:
  914. sendPacket(this, packet, cb)
  915. return
  916. }
  917. switch (packet.qos) {
  918. case 2:
  919. case 1:
  920. storeAndSend(this, packet, cb, cbStorePut)
  921. break
  922. /**
  923. * no need of case here since it will be caught by default
  924. * and jshint comply that before default it must be a break
  925. * anyway it will result in -1 evaluation
  926. */
  927. case 0:
  928. /* falls through */
  929. default:
  930. sendPacket(this, packet, cb)
  931. break
  932. }
  933. }
  934. /**
  935. * _storePacket - queue a packet
  936. * @param {String} type - packet type (see `protocol`)
  937. * @param {Object} packet - packet options
  938. * @param {Function} cb - callback when the packet is sent
  939. * @param {Function} cbStorePut - called when message is put into outgoingStore
  940. * @api private
  941. */
  942. MqttClient.prototype._storePacket = function(packet, cb, cbStorePut) {
  943. cbStorePut = cbStorePut || nop
  944. if (((packet.qos || 0) === 0 && this.queueQoSZero) || packet.cmd !==
  945. 'publish') {
  946. this.queue.push({
  947. packet: packet,
  948. cb: cb
  949. })
  950. } else if (packet.qos > 0) {
  951. cb = this.outgoing[packet.messageId] ? this.outgoing[packet
  952. .messageId].cb : null
  953. this.outgoingStore.put(packet, function(err) {
  954. if (err) {
  955. return cb && cb(err)
  956. }
  957. cbStorePut()
  958. })
  959. } else if (cb) {
  960. cb(new Error('No connection to broker'))
  961. }
  962. }
  963. /**
  964. * _setupPingTimer - setup the ping timer
  965. *
  966. * @api private
  967. */
  968. MqttClient.prototype._setupPingTimer = function() {
  969. var that = this
  970. if (!this.pingTimer && this.options.keepalive) {
  971. this.pingResp = true
  972. this.pingTimer = reInterval(function() {
  973. that._checkPing()
  974. }, this.options.keepalive * 1000)
  975. }
  976. }
  977. /**
  978. * _shiftPingInterval - reschedule the ping interval
  979. *
  980. * @api private
  981. */
  982. MqttClient.prototype._shiftPingInterval = function() {
  983. if (this.pingTimer && this.options.keepalive && this.options
  984. .reschedulePings) {
  985. this.pingTimer.reschedule(this.options.keepalive * 1000)
  986. }
  987. }
  988. /**
  989. * _checkPing - check if a pingresp has come back, and ping the server again
  990. *
  991. * @api private
  992. */
  993. MqttClient.prototype._checkPing = function() {
  994. if (this.pingResp) {
  995. this.pingResp = false
  996. this._sendPacket({
  997. cmd: 'pingreq'
  998. })
  999. } else {
  1000. // do a forced cleanup since socket will be in bad shape
  1001. this._cleanUp(true)
  1002. }
  1003. }
  1004. /**
  1005. * _handlePingresp - handle a pingresp
  1006. *
  1007. * @api private
  1008. */
  1009. MqttClient.prototype._handlePingresp = function() {
  1010. this.pingResp = true
  1011. }
  1012. /**
  1013. * _handleConnack
  1014. *
  1015. * @param {Object} packet
  1016. * @api private
  1017. */
  1018. MqttClient.prototype._handleConnack = function(packet) {
  1019. var options = this.options
  1020. var version = options.protocolVersion
  1021. var rc = version === 5 ? packet.reasonCode : packet.returnCode
  1022. clearTimeout(this.connackTimer)
  1023. if (packet.properties) {
  1024. if (packet.properties.topicAliasMaximum) {
  1025. if (!options.properties) {
  1026. options.properties = {}
  1027. }
  1028. options.properties.topicAliasMaximum = packet.properties
  1029. .topicAliasMaximum
  1030. }
  1031. if (packet.properties.serverKeepAlive && options.keepalive) {
  1032. options.keepalive = packet.properties.serverKeepAlive
  1033. this._shiftPingInterval()
  1034. }
  1035. if (packet.properties.maximumPacketSize) {
  1036. if (!options.properties) {
  1037. options.properties = {}
  1038. }
  1039. options.properties.maximumPacketSize = packet.properties
  1040. .maximumPacketSize
  1041. }
  1042. }
  1043. if (rc === 0) {
  1044. this.reconnecting = false
  1045. this._onConnect(packet)
  1046. } else if (rc > 0) {
  1047. var err = new Error('Connection refused: ' + errors[rc])
  1048. err.code = rc
  1049. this.emit('error', err)
  1050. }
  1051. }
  1052. /**
  1053. * _handlePublish
  1054. *
  1055. * @param {Object} packet
  1056. * @api private
  1057. */
  1058. /*
  1059. those late 2 case should be rewrite to comply with coding style:
  1060. case 1:
  1061. case 0:
  1062. // do not wait sending a puback
  1063. // no callback passed
  1064. if (1 === qos) {
  1065. this._sendPacket({
  1066. cmd: 'puback',
  1067. messageId: mid
  1068. });
  1069. }
  1070. // emit the message event for both qos 1 and 0
  1071. this.emit('message', topic, message, packet);
  1072. this.handleMessage(packet, done);
  1073. break;
  1074. default:
  1075. // do nothing but every switch mus have a default
  1076. // log or throw an error about unknown qos
  1077. break;
  1078. for now i just suppressed the warnings
  1079. */
  1080. MqttClient.prototype._handlePublish = function(packet, done) {
  1081. done = typeof done !== 'undefined' ? done : nop
  1082. var topic = packet.topic.toString()
  1083. var message = packet.payload
  1084. var qos = packet.qos
  1085. var mid = packet.messageId
  1086. var that = this
  1087. var options = this.options
  1088. var validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
  1089. switch (qos) {
  1090. case 2: {
  1091. options.customHandleAcks(topic, message, packet, function(error,
  1092. code) {
  1093. if (!(error instanceof Error)) {
  1094. code = error
  1095. error = null
  1096. }
  1097. if (error) {
  1098. return that.emit('error', error)
  1099. }
  1100. if (validReasonCodes.indexOf(code) === -1) {
  1101. return that.emit('error', new Error(
  1102. 'Wrong reason code for pubrec'))
  1103. }
  1104. if (code) {
  1105. that._sendPacket({
  1106. cmd: 'pubrec',
  1107. messageId: mid,
  1108. reasonCode: code
  1109. }, done)
  1110. } else {
  1111. that.incomingStore.put(packet, function() {
  1112. that._sendPacket({
  1113. cmd: 'pubrec',
  1114. messageId: mid
  1115. }, done)
  1116. })
  1117. }
  1118. })
  1119. break
  1120. }
  1121. case 1: {
  1122. // emit the message event
  1123. options.customHandleAcks(topic, message, packet, function(error,
  1124. code) {
  1125. if (!(error instanceof Error)) {
  1126. code = error
  1127. error = null
  1128. }
  1129. if (error) {
  1130. return that.emit('error', error)
  1131. }
  1132. if (validReasonCodes.indexOf(code) === -1) {
  1133. return that.emit('error', new Error(
  1134. 'Wrong reason code for puback'))
  1135. }
  1136. if (!code) {
  1137. that.emit('message', topic, message, packet)
  1138. }
  1139. that.handleMessage(packet, function(err) {
  1140. if (err) {
  1141. return done && done(err)
  1142. }
  1143. that._sendPacket({
  1144. cmd: 'puback',
  1145. messageId: mid,
  1146. reasonCode: code
  1147. }, done)
  1148. })
  1149. })
  1150. break
  1151. }
  1152. case 0:
  1153. // emit the message event
  1154. this.emit('message', topic, message, packet)
  1155. this.handleMessage(packet, done)
  1156. break
  1157. default:
  1158. // do nothing
  1159. // log or throw an error about unknown qos
  1160. break
  1161. }
  1162. }
  1163. /**
  1164. * Handle messages with backpressure support, one at a time.
  1165. * Override at will.
  1166. *
  1167. * @param Packet packet the packet
  1168. * @param Function callback call when finished
  1169. * @api public
  1170. */
  1171. MqttClient.prototype.handleMessage = function(packet, callback) {
  1172. callback()
  1173. }
  1174. /**
  1175. * _handleAck
  1176. *
  1177. * @param {Object} packet
  1178. * @api private
  1179. */
  1180. MqttClient.prototype._handleAck = function(packet) {
  1181. /* eslint no-fallthrough: "off" */
  1182. var mid = packet.messageId
  1183. var type = packet.cmd
  1184. var response = null
  1185. var cb = this.outgoing[mid] ? this.outgoing[mid].cb : null
  1186. var that = this
  1187. var err
  1188. if (!cb) {
  1189. // Server sent an ack in error, ignore it.
  1190. return
  1191. }
  1192. // Process
  1193. switch (type) {
  1194. case 'pubcomp':
  1195. // same thing as puback for QoS 2
  1196. case 'puback':
  1197. var pubackRC = packet.reasonCode
  1198. // Callback - we're done
  1199. if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
  1200. err = new Error('Publish error: ' + errors[pubackRC])
  1201. err.code = pubackRC
  1202. cb(err, packet)
  1203. }
  1204. delete this.outgoing[mid]
  1205. this.outgoingStore.del(packet, cb)
  1206. break
  1207. case 'pubrec':
  1208. response = {
  1209. cmd: 'pubrel',
  1210. qos: 2,
  1211. messageId: mid
  1212. }
  1213. var pubrecRC = packet.reasonCode
  1214. if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
  1215. err = new Error('Publish error: ' + errors[pubrecRC])
  1216. err.code = pubrecRC
  1217. cb(err, packet)
  1218. } else {
  1219. this._sendPacket(response)
  1220. }
  1221. break
  1222. case 'suback':
  1223. delete this.outgoing[mid]
  1224. for (var grantedI = 0; grantedI < packet.granted
  1225. .length; grantedI++) {
  1226. if ((packet.granted[grantedI] & 0x80) !== 0) {
  1227. // suback with Failure status
  1228. var topics = this.messageIdToTopic[mid]
  1229. if (topics) {
  1230. topics.forEach(function(topic) {
  1231. delete that._resubscribeTopics[topic]
  1232. })
  1233. }
  1234. }
  1235. }
  1236. cb(null, packet)
  1237. break
  1238. case 'unsuback':
  1239. delete this.outgoing[mid]
  1240. cb(null)
  1241. break
  1242. default:
  1243. that.emit('error', new Error('unrecognized packet type'))
  1244. }
  1245. if (this.disconnecting &&
  1246. Object.keys(this.outgoing).length === 0) {
  1247. this.emit('outgoingEmpty')
  1248. }
  1249. }
  1250. /**
  1251. * _handlePubrel
  1252. *
  1253. * @param {Object} packet
  1254. * @api private
  1255. */
  1256. MqttClient.prototype._handlePubrel = function(packet, callback) {
  1257. callback = typeof callback !== 'undefined' ? callback : nop
  1258. var mid = packet.messageId
  1259. var that = this
  1260. var comp = {
  1261. cmd: 'pubcomp',
  1262. messageId: mid
  1263. }
  1264. that.incomingStore.get(packet, function(err, pub) {
  1265. if (!err) {
  1266. that.emit('message', pub.topic, pub.payload, pub)
  1267. that.handleMessage(pub, function(err) {
  1268. if (err) {
  1269. return callback(err)
  1270. }
  1271. that.incomingStore.del(pub, nop)
  1272. that._sendPacket(comp, callback)
  1273. })
  1274. } else {
  1275. that._sendPacket(comp, callback)
  1276. }
  1277. })
  1278. }
  1279. /**
  1280. * _handleDisconnect
  1281. *
  1282. * @param {Object} packet
  1283. * @api private
  1284. */
  1285. MqttClient.prototype._handleDisconnect = function(packet) {
  1286. this.emit('disconnect', packet)
  1287. }
  1288. /**
  1289. * _nextId
  1290. * @return unsigned int
  1291. */
  1292. MqttClient.prototype._nextId = function() {
  1293. // id becomes current state of this.nextId and increments afterwards
  1294. var id = this.nextId++
  1295. // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
  1296. if (this.nextId === 65536) {
  1297. this.nextId = 1
  1298. }
  1299. return id
  1300. }
  1301. /**
  1302. * getLastMessageId
  1303. * @return unsigned int
  1304. */
  1305. MqttClient.prototype.getLastMessageId = function() {
  1306. return (this.nextId === 1) ? 65535 : (this.nextId - 1)
  1307. }
  1308. /**
  1309. * _resubscribe
  1310. * @api private
  1311. */
  1312. MqttClient.prototype._resubscribe = function(connack) {
  1313. var _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
  1314. if (!this._firstConnection &&
  1315. (this.options.clean || (this.options.protocolVersion === 5 && !
  1316. connack.sessionPresent)) &&
  1317. _resubscribeTopicsKeys.length > 0) {
  1318. if (this.options.resubscribe) {
  1319. if (this.options.protocolVersion === 5) {
  1320. for (var topicI = 0; topicI < _resubscribeTopicsKeys
  1321. .length; topicI++) {
  1322. var resubscribeTopic = {}
  1323. resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this
  1324. ._resubscribeTopics[_resubscribeTopicsKeys[topicI]]
  1325. resubscribeTopic.resubscribe = true
  1326. this.subscribe(resubscribeTopic, {
  1327. properties: resubscribeTopic[
  1328. _resubscribeTopicsKeys[topicI]]
  1329. .properties
  1330. })
  1331. }
  1332. } else {
  1333. this._resubscribeTopics.resubscribe = true
  1334. this.subscribe(this._resubscribeTopics)
  1335. }
  1336. } else {
  1337. this._resubscribeTopics = {}
  1338. }
  1339. }
  1340. this._firstConnection = false
  1341. }
  1342. /**
  1343. * _onConnect
  1344. *
  1345. * @api private
  1346. */
  1347. MqttClient.prototype._onConnect = function(packet) {
  1348. if (this.disconnected) {
  1349. this.emit('connect', packet)
  1350. return
  1351. }
  1352. var that = this
  1353. this._setupPingTimer()
  1354. this._resubscribe(packet)
  1355. this.connected = true
  1356. function startStreamProcess() {
  1357. var outStore = that.outgoingStore.createStream()
  1358. function clearStoreProcessing() {
  1359. that._storeProcessing = false
  1360. that._packetIdsDuringStoreProcessing = {}
  1361. }
  1362. that.once('close', remove)
  1363. outStore.on('error', function(err) {
  1364. clearStoreProcessing()
  1365. that.removeListener('close', remove)
  1366. that.emit('error', err)
  1367. })
  1368. function remove() {
  1369. outStore.destroy()
  1370. outStore = null
  1371. clearStoreProcessing()
  1372. }
  1373. function storeDeliver() {
  1374. // edge case, we wrapped this twice
  1375. if (!outStore) {
  1376. return
  1377. }
  1378. that._storeProcessing = true
  1379. var packet = outStore.read(1)
  1380. var cb
  1381. if (!packet) {
  1382. // read when data is available in the future
  1383. outStore.once('readable', storeDeliver)
  1384. return
  1385. }
  1386. // Skip already processed store packets
  1387. if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
  1388. storeDeliver()
  1389. return
  1390. }
  1391. // Avoid unnecessary stream read operations when disconnected
  1392. if (!that.disconnecting && !that.reconnectTimer) {
  1393. cb = that.outgoing[packet.messageId] ? that.outgoing[packet
  1394. .messageId].cb : null
  1395. that.outgoing[packet.messageId] = {
  1396. volatile: false,
  1397. cb: function(err, status) {
  1398. // Ensure that the original callback passed in to publish gets invoked
  1399. if (cb) {
  1400. cb(err, status)
  1401. }
  1402. storeDeliver()
  1403. }
  1404. }
  1405. that._packetIdsDuringStoreProcessing[packet.messageId] =
  1406. true
  1407. that._sendPacket(packet)
  1408. } else if (outStore.destroy) {
  1409. outStore.destroy()
  1410. }
  1411. }
  1412. outStore.on('end', function() {
  1413. var allProcessed = true
  1414. for (var id in that._packetIdsDuringStoreProcessing) {
  1415. if (!that._packetIdsDuringStoreProcessing[id]) {
  1416. allProcessed = false
  1417. break
  1418. }
  1419. }
  1420. if (allProcessed) {
  1421. clearStoreProcessing()
  1422. that.removeListener('close', remove)
  1423. that.emit('connect', packet)
  1424. } else {
  1425. startStreamProcess()
  1426. }
  1427. })
  1428. storeDeliver()
  1429. }
  1430. // start flowing
  1431. startStreamProcess()
  1432. }
  1433. module.exports = MqttClient
  1434. }).call(this, require('_process'), typeof global !== "undefined" ? global :
  1435. typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}
  1436. )
  1437. }, {
  1438. "./store": 7,
  1439. "./validations": 8,
  1440. "_process": 92,
  1441. "events": 13,
  1442. "inherits": 80,
  1443. "mqtt-packet": 84,
  1444. "readable-stream": 108,
  1445. "reinterval": 109,
  1446. "xtend": 121
  1447. }],
  1448. 2: [function(require, module, exports) {
  1449. (function(Buffer) {
  1450. 'use strict'
  1451. var Transform = require('readable-stream').Transform
  1452. var duplexify = require('duplexify')
  1453. var base64 = require('base64-js')
  1454. /* global FileReader */
  1455. var my
  1456. var proxy
  1457. var stream
  1458. var isInitialized = false
  1459. function buildProxy() {
  1460. var proxy = new Transform()
  1461. proxy._write = function(chunk, encoding, next) {
  1462. my.sendSocketMessage({
  1463. data: chunk.buffer,
  1464. success: function() {
  1465. next()
  1466. },
  1467. fail: function() {
  1468. next(new Error())
  1469. }
  1470. })
  1471. }
  1472. proxy._flush = function socketEnd(done) {
  1473. my.closeSocket({
  1474. success: function() {
  1475. done()
  1476. }
  1477. })
  1478. }
  1479. return proxy
  1480. }
  1481. function setDefaultOpts(opts) {
  1482. if (!opts.hostname) {
  1483. opts.hostname = 'localhost'
  1484. }
  1485. if (!opts.path) {
  1486. opts.path = '/'
  1487. }
  1488. if (!opts.wsOptions) {
  1489. opts.wsOptions = {}
  1490. }
  1491. }
  1492. function buildUrl(opts, client) {
  1493. var protocol = opts.protocol === 'alis' ? 'wss' : 'ws'
  1494. var url = protocol + '://' + opts.hostname + opts.path
  1495. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1496. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1497. }
  1498. if (typeof(opts.transformWsUrl) === 'function') {
  1499. url = opts.transformWsUrl(url, opts, client)
  1500. }
  1501. return url
  1502. }
  1503. function bindEventHandler() {
  1504. if (isInitialized) return
  1505. isInitialized = true
  1506. my.onSocketOpen(function() {
  1507. stream.setReadable(proxy)
  1508. stream.setWritable(proxy)
  1509. stream.emit('connect')
  1510. })
  1511. my.onSocketMessage(function(res) {
  1512. if (typeof res.data === 'string') {
  1513. var array = base64.toByteArray(res.data)
  1514. var buffer = Buffer.from(array)
  1515. proxy.push(buffer)
  1516. } else {
  1517. var reader = new FileReader()
  1518. reader.addEventListener('load', function() {
  1519. var data = reader.result
  1520. if (data instanceof ArrayBuffer) data = Buffer
  1521. .from(data)
  1522. else data = Buffer.from(data, 'utf8')
  1523. proxy.push(data)
  1524. })
  1525. reader.readAsArrayBuffer(res.data)
  1526. }
  1527. })
  1528. my.onSocketClose(function() {
  1529. stream.end()
  1530. stream.destroy()
  1531. })
  1532. my.onSocketError(function(res) {
  1533. stream.destroy(res)
  1534. })
  1535. }
  1536. function buildStream(client, opts) {
  1537. opts.hostname = opts.hostname || opts.host
  1538. if (!opts.hostname) {
  1539. throw new Error('Could not determine host. Specify host manually.')
  1540. }
  1541. var websocketSubProtocol =
  1542. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3) ?
  1543. 'mqttv3.1' :
  1544. 'mqtt'
  1545. setDefaultOpts(opts)
  1546. var url = buildUrl(opts, client)
  1547. my = opts.my
  1548. my.connectSocket({
  1549. url: url,
  1550. protocols: websocketSubProtocol
  1551. })
  1552. proxy = buildProxy()
  1553. stream = duplexify.obj()
  1554. bindEventHandler()
  1555. return stream
  1556. }
  1557. module.exports = buildStream
  1558. }).call(this, require("buffer").Buffer)
  1559. }, {
  1560. "base64-js": 10,
  1561. "buffer": 12,
  1562. "duplexify": 17,
  1563. "readable-stream": 108
  1564. }],
  1565. 3: [function(require, module, exports) {
  1566. 'use strict'
  1567. var net = require('net')
  1568. /*
  1569. variables port and host can be removed since
  1570. you have all required information in opts object
  1571. */
  1572. function buildBuilder(client, opts) {
  1573. var port, host
  1574. opts.port = opts.port || 1883
  1575. opts.hostname = opts.hostname || opts.host || 'localhost'
  1576. port = opts.port
  1577. host = opts.hostname
  1578. return net.createConnection(port, host)
  1579. }
  1580. module.exports = buildBuilder
  1581. }, {
  1582. "net": 11
  1583. }],
  1584. 4: [function(require, module, exports) {
  1585. 'use strict'
  1586. var tls = require('tls')
  1587. function buildBuilder(mqttClient, opts) {
  1588. var connection
  1589. opts.port = opts.port || 8883
  1590. opts.host = opts.hostname || opts.host || 'localhost'
  1591. opts.rejectUnauthorized = opts.rejectUnauthorized !== false
  1592. delete opts.path
  1593. connection = tls.connect(opts)
  1594. /* eslint no-use-before-define: [2, "nofunc"] */
  1595. connection.on('secureConnect', function() {
  1596. if (opts.rejectUnauthorized && !connection.authorized) {
  1597. connection.emit('error', new Error('TLS not authorized'))
  1598. } else {
  1599. connection.removeListener('error', handleTLSerrors)
  1600. }
  1601. })
  1602. function handleTLSerrors(err) {
  1603. // How can I get verify this error is a tls error?
  1604. if (opts.rejectUnauthorized) {
  1605. mqttClient.emit('error', err)
  1606. }
  1607. // close this connection to match the behaviour of net
  1608. // otherwise all we get is an error from the connection
  1609. // and close event doesn't fire. This is a work around
  1610. // to enable the reconnect code to work the same as with
  1611. // net.createConnection
  1612. connection.end()
  1613. }
  1614. connection.on('error', handleTLSerrors)
  1615. return connection
  1616. }
  1617. module.exports = buildBuilder
  1618. }, {
  1619. "tls": 11
  1620. }],
  1621. 5: [function(require, module, exports) {
  1622. (function(process) {
  1623. 'use strict'
  1624. var websocket = require('websocket-stream')
  1625. var urlModule = require('url')
  1626. var WSS_OPTIONS = [
  1627. 'rejectUnauthorized',
  1628. 'ca',
  1629. 'cert',
  1630. 'key',
  1631. 'pfx',
  1632. 'passphrase'
  1633. ]
  1634. var IS_BROWSER = process.title === 'browser'
  1635. function buildUrl(opts, client) {
  1636. var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts
  1637. .path
  1638. if (typeof(opts.transformWsUrl) === 'function') {
  1639. url = opts.transformWsUrl(url, opts, client)
  1640. }
  1641. return url
  1642. }
  1643. function setDefaultOpts(opts) {
  1644. if (!opts.hostname) {
  1645. opts.hostname = 'localhost'
  1646. }
  1647. if (!opts.port) {
  1648. if (opts.protocol === 'wss') {
  1649. opts.port = 443
  1650. } else {
  1651. opts.port = 80
  1652. }
  1653. }
  1654. if (!opts.path) {
  1655. opts.path = '/'
  1656. }
  1657. if (!opts.wsOptions) {
  1658. opts.wsOptions = {}
  1659. }
  1660. if (!IS_BROWSER && opts.protocol === 'wss') {
  1661. // Add cert/key/ca etc options
  1662. WSS_OPTIONS.forEach(function(prop) {
  1663. if (opts.hasOwnProperty(prop) && !opts.wsOptions
  1664. .hasOwnProperty(prop)) {
  1665. opts.wsOptions[prop] = opts[prop]
  1666. }
  1667. })
  1668. }
  1669. }
  1670. function createWebSocket(client, opts) {
  1671. var websocketSubProtocol =
  1672. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3) ?
  1673. 'mqttv3.1' :
  1674. 'mqtt'
  1675. setDefaultOpts(opts)
  1676. var url = buildUrl(opts, client)
  1677. return websocket(url, [websocketSubProtocol], opts.wsOptions)
  1678. }
  1679. function buildBuilder(client, opts) {
  1680. return createWebSocket(client, opts)
  1681. }
  1682. function buildBuilderBrowser(client, opts) {
  1683. if (!opts.hostname) {
  1684. opts.hostname = opts.host
  1685. }
  1686. if (!opts.hostname) {
  1687. // Throwing an error in a Web Worker if no `hostname` is given, because we
  1688. // can not determine the `hostname` automatically. If connecting to
  1689. // localhost, please supply the `hostname` as an argument.
  1690. if (typeof(document) === 'undefined') {
  1691. throw new Error('Could not determine host. Specify host manually.')
  1692. }
  1693. var parsed = urlModule.parse(document.URL)
  1694. opts.hostname = parsed.hostname
  1695. if (!opts.port) {
  1696. opts.port = parsed.port
  1697. }
  1698. }
  1699. return createWebSocket(client, opts)
  1700. }
  1701. if (IS_BROWSER) {
  1702. module.exports = buildBuilderBrowser
  1703. } else {
  1704. module.exports = buildBuilder
  1705. }
  1706. }).call(this, require('_process'))
  1707. }, {
  1708. "_process": 92,
  1709. "url": 113,
  1710. "websocket-stream": 118
  1711. }],
  1712. 6: [function(require, module, exports) {
  1713. (function(process, Buffer) {
  1714. 'use strict'
  1715. var Transform = require('readable-stream').Transform
  1716. var duplexify = require('duplexify')
  1717. /* global wx */
  1718. var socketTask
  1719. var proxy
  1720. var stream
  1721. function buildProxy() {
  1722. var proxy = new Transform()
  1723. proxy._write = function(chunk, encoding, next) {
  1724. socketTask.send({
  1725. data: chunk.buffer,
  1726. success: function() {
  1727. next()
  1728. },
  1729. fail: function(errMsg) {
  1730. next(new Error(errMsg))
  1731. }
  1732. })
  1733. }
  1734. proxy._flush = function socketEnd(done) {
  1735. socketTask.close({
  1736. success: function() {
  1737. done()
  1738. }
  1739. })
  1740. }
  1741. return proxy
  1742. }
  1743. function setDefaultOpts(opts) {
  1744. if (!opts.hostname) {
  1745. opts.hostname = 'localhost'
  1746. }
  1747. if (!opts.path) {
  1748. opts.path = '/'
  1749. }
  1750. if (!opts.wsOptions) {
  1751. opts.wsOptions = {}
  1752. }
  1753. }
  1754. function buildUrl(opts, client) {
  1755. var protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  1756. var url = protocol + '://' + opts.hostname + opts.path
  1757. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1758. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1759. }
  1760. if (typeof(opts.transformWsUrl) === 'function') {
  1761. url = opts.transformWsUrl(url, opts, client)
  1762. }
  1763. return url
  1764. }
  1765. function bindEventHandler() {
  1766. socketTask.onOpen(function() {
  1767. stream.setReadable(proxy)
  1768. stream.setWritable(proxy)
  1769. stream.emit('connect')
  1770. })
  1771. socketTask.onMessage(function(res) {
  1772. var data = res.data
  1773. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  1774. else data = Buffer.from(data, 'utf8')
  1775. proxy.push(data)
  1776. })
  1777. socketTask.onClose(function() {
  1778. stream.end()
  1779. stream.destroy()
  1780. })
  1781. socketTask.onError(function(res) {
  1782. stream.destroy(new Error(res.errMsg))
  1783. })
  1784. }
  1785. function buildStream(client, opts) {
  1786. opts.hostname = opts.hostname || opts.host
  1787. if (!opts.hostname) {
  1788. throw new Error('Could not determine host. Specify host manually.')
  1789. }
  1790. var websocketSubProtocol =
  1791. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3) ?
  1792. 'mqttv3.1' :
  1793. 'mqtt'
  1794. setDefaultOpts(opts)
  1795. var url = buildUrl(opts, client)
  1796. socketTask = wx.connectSocket({
  1797. url: url,
  1798. protocols: websocketSubProtocol,
  1799. success() {}
  1800. })
  1801. proxy = buildProxy()
  1802. stream = duplexify.obj()
  1803. stream._destroy = function(err, cb) {
  1804. socketTask.close({
  1805. success: function() {
  1806. cb && cb(err)
  1807. }
  1808. })
  1809. }
  1810. var destroyRef = stream.destroy
  1811. stream.destroy = function() {
  1812. stream.destroy = destroyRef
  1813. var self = this
  1814. process.nextTick(function() {
  1815. socketTask.close({
  1816. fail: function() {
  1817. self._destroy(new Error())
  1818. }
  1819. })
  1820. })
  1821. }.bind(stream)
  1822. bindEventHandler()
  1823. return stream
  1824. }
  1825. module.exports = buildStream
  1826. }).call(this, require('_process'), require("buffer").Buffer)
  1827. }, {
  1828. "_process": 92,
  1829. "buffer": 12,
  1830. "duplexify": 17,
  1831. "readable-stream": 108
  1832. }],
  1833. 7: [function(require, module, exports) {
  1834. (function(process) {
  1835. 'use strict'
  1836. /**
  1837. * Module dependencies
  1838. */
  1839. var xtend = require('xtend')
  1840. var Readable = require('readable-stream').Readable
  1841. var streamsOpts = {
  1842. objectMode: true
  1843. }
  1844. var defaultStoreOptions = {
  1845. clean: true
  1846. }
  1847. /**
  1848. * es6-map can preserve insertion order even if ES version is older.
  1849. *
  1850. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Description
  1851. * It should be noted that a Map which is a map of an object, especially
  1852. * a dictionary of dictionaries, will only map to the object's insertion
  1853. * order. In ES2015 this is ordered for objects but for older versions of
  1854. * ES, this may be random and not ordered.
  1855. *
  1856. */
  1857. var Map = require('es6-map')
  1858. /**
  1859. * In-memory implementation of the message store
  1860. * This can actually be saved into files.
  1861. *
  1862. * @param {Object} [options] - store options
  1863. */
  1864. function Store(options) {
  1865. if (!(this instanceof Store)) {
  1866. return new Store(options)
  1867. }
  1868. this.options = options || {}
  1869. // Defaults
  1870. this.options = xtend(defaultStoreOptions, options)
  1871. this._inflights = new Map()
  1872. }
  1873. /**
  1874. * Adds a packet to the store, a packet is
  1875. * anything that has a messageId property.
  1876. *
  1877. */
  1878. Store.prototype.put = function(packet, cb) {
  1879. this._inflights.set(packet.messageId, packet)
  1880. if (cb) {
  1881. cb()
  1882. }
  1883. return this
  1884. }
  1885. /**
  1886. * Creates a stream with all the packets in the store
  1887. *
  1888. */
  1889. Store.prototype.createStream = function() {
  1890. var stream = new Readable(streamsOpts)
  1891. var destroyed = false
  1892. var values = []
  1893. var i = 0
  1894. this._inflights.forEach(function(value, key) {
  1895. values.push(value)
  1896. })
  1897. stream._read = function() {
  1898. if (!destroyed && i < values.length) {
  1899. this.push(values[i++])
  1900. } else {
  1901. this.push(null)
  1902. }
  1903. }
  1904. stream.destroy = function() {
  1905. if (destroyed) {
  1906. return
  1907. }
  1908. var self = this
  1909. destroyed = true
  1910. process.nextTick(function() {
  1911. self.emit('close')
  1912. })
  1913. }
  1914. return stream
  1915. }
  1916. /**
  1917. * deletes a packet from the store.
  1918. */
  1919. Store.prototype.del = function(packet, cb) {
  1920. packet = this._inflights.get(packet.messageId)
  1921. if (packet) {
  1922. this._inflights.delete(packet.messageId)
  1923. cb(null, packet)
  1924. } else if (cb) {
  1925. cb(new Error('missing packet'))
  1926. }
  1927. return this
  1928. }
  1929. /**
  1930. * get a packet from the store.
  1931. */
  1932. Store.prototype.get = function(packet, cb) {
  1933. packet = this._inflights.get(packet.messageId)
  1934. if (packet) {
  1935. cb(null, packet)
  1936. } else if (cb) {
  1937. cb(new Error('missing packet'))
  1938. }
  1939. return this
  1940. }
  1941. /**
  1942. * Close the store
  1943. */
  1944. Store.prototype.close = function(cb) {
  1945. if (this.options.clean) {
  1946. this._inflights = null
  1947. }
  1948. if (cb) {
  1949. cb()
  1950. }
  1951. }
  1952. module.exports = Store
  1953. }).call(this, require('_process'))
  1954. }, {
  1955. "_process": 92,
  1956. "es6-map": 67,
  1957. "readable-stream": 108,
  1958. "xtend": 121
  1959. }],
  1960. 8: [function(require, module, exports) {
  1961. 'use strict'
  1962. /**
  1963. * Validate a topic to see if it's valid or not.
  1964. * A topic is valid if it follow below rules:
  1965. * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
  1966. * - Rule #2: Part `#` must be located at the end of the mailbox
  1967. *
  1968. * @param {String} topic - A topic
  1969. * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
  1970. */
  1971. function validateTopic(topic) {
  1972. var parts = topic.split('/')
  1973. for (var i = 0; i < parts.length; i++) {
  1974. if (parts[i] === '+') {
  1975. continue
  1976. }
  1977. if (parts[i] === '#') {
  1978. // for Rule #2
  1979. return i === parts.length - 1
  1980. }
  1981. if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
  1982. return false
  1983. }
  1984. }
  1985. return true
  1986. }
  1987. /**
  1988. * Validate an array of topics to see if any of them is valid or not
  1989. * @param {Array} topics - Array of topics
  1990. * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
  1991. */
  1992. function validateTopics(topics) {
  1993. if (topics.length === 0) {
  1994. return 'empty_topic_list'
  1995. }
  1996. for (var i = 0; i < topics.length; i++) {
  1997. if (!validateTopic(topics[i])) {
  1998. return topics[i]
  1999. }
  2000. }
  2001. return null
  2002. }
  2003. module.exports = {
  2004. validateTopics: validateTopics
  2005. }
  2006. }, {}],
  2007. 9: [function(require, module, exports) {
  2008. (function(process) {
  2009. 'use strict'
  2010. var MqttClient = require('../client')
  2011. var Store = require('../store')
  2012. var url = require('url')
  2013. var xtend = require('xtend')
  2014. var protocols = {}
  2015. if (process.title !== 'browser') {
  2016. protocols.mqtt = require('./tcp')
  2017. protocols.tcp = require('./tcp')
  2018. protocols.ssl = require('./tls')
  2019. protocols.tls = require('./tls')
  2020. protocols.mqtts = require('./tls')
  2021. } else {
  2022. protocols.wx = require('./wx')
  2023. protocols.wxs = require('./wx')
  2024. protocols.ali = require('./ali')
  2025. protocols.alis = require('./ali')
  2026. }
  2027. protocols.ws = require('./ws')
  2028. protocols.wss = require('./ws')
  2029. /**
  2030. * Parse the auth attribute and merge username and password in the options object.
  2031. *
  2032. * @param {Object} [opts] option object
  2033. */
  2034. function parseAuthOptions(opts) {
  2035. var matches
  2036. if (opts.auth) {
  2037. matches = opts.auth.match(/^(.+):(.+)$/)
  2038. if (matches) {
  2039. opts.username = matches[1]
  2040. opts.password = matches[2]
  2041. } else {
  2042. opts.username = opts.auth
  2043. }
  2044. }
  2045. }
  2046. /**
  2047. * connect - connect to an MQTT broker.
  2048. *
  2049. * @param {String} [brokerUrl] - url of the broker, optional
  2050. * @param {Object} opts - see MqttClient#constructor
  2051. */
  2052. function connect(brokerUrl, opts) {
  2053. if ((typeof brokerUrl === 'object') && !opts) {
  2054. opts = brokerUrl
  2055. brokerUrl = null
  2056. }
  2057. opts = opts || {}
  2058. if (brokerUrl) {
  2059. var parsed = url.parse(brokerUrl, true)
  2060. if (parsed.port != null) {
  2061. parsed.port = Number(parsed.port)
  2062. }
  2063. opts = xtend(parsed, opts)
  2064. if (opts.protocol === null) {
  2065. throw new Error('Missing protocol')
  2066. }
  2067. opts.protocol = opts.protocol.replace(/:$/, '')
  2068. }
  2069. // merge in the auth options if supplied
  2070. parseAuthOptions(opts)
  2071. // support clientId passed in the query string of the url
  2072. if (opts.query && typeof opts.query.clientId === 'string') {
  2073. opts.clientId = opts.query.clientId
  2074. }
  2075. if (opts.cert && opts.key) {
  2076. if (opts.protocol) {
  2077. if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
  2078. switch (opts.protocol) {
  2079. case 'mqtt':
  2080. opts.protocol = 'mqtts'
  2081. break
  2082. case 'ws':
  2083. opts.protocol = 'wss'
  2084. break
  2085. case 'wx':
  2086. opts.protocol = 'wxs'
  2087. break
  2088. case 'ali':
  2089. opts.protocol = 'alis'
  2090. break
  2091. default:
  2092. throw new Error(
  2093. 'Unknown protocol for secure connection: "' +
  2094. opts.protocol + '"!')
  2095. }
  2096. }
  2097. } else {
  2098. // don't know what protocol he want to use, mqtts or wss
  2099. throw new Error('Missing secure protocol key')
  2100. }
  2101. }
  2102. if (!protocols[opts.protocol]) {
  2103. var isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
  2104. opts.protocol = [
  2105. 'mqtt',
  2106. 'mqtts',
  2107. 'ws',
  2108. 'wss',
  2109. 'wx',
  2110. 'wxs',
  2111. 'ali',
  2112. 'alis'
  2113. ].filter(function(key, index) {
  2114. if (isSecure && index % 2 === 0) {
  2115. // Skip insecure protocols when requesting a secure one.
  2116. return false
  2117. }
  2118. return (typeof protocols[key] === 'function')
  2119. })[0]
  2120. }
  2121. if (opts.clean === false && !opts.clientId) {
  2122. throw new Error('Missing clientId for unclean clients')
  2123. }
  2124. if (opts.protocol) {
  2125. opts.defaultProtocol = opts.protocol
  2126. }
  2127. function wrapper(client) {
  2128. if (opts.servers) {
  2129. if (!client._reconnectCount || client._reconnectCount === opts
  2130. .servers.length) {
  2131. client._reconnectCount = 0
  2132. }
  2133. opts.host = opts.servers[client._reconnectCount].host
  2134. opts.port = opts.servers[client._reconnectCount].port
  2135. opts.protocol = (!opts.servers[client._reconnectCount].protocol ?
  2136. opts.defaultProtocol : opts.servers[client._reconnectCount]
  2137. .protocol)
  2138. opts.hostname = opts.host
  2139. client._reconnectCount++
  2140. }
  2141. return protocols[opts.protocol](client, opts)
  2142. }
  2143. return new MqttClient(wrapper, opts)
  2144. }
  2145. module.exports = connect
  2146. module.exports.connect = connect
  2147. module.exports.MqttClient = MqttClient
  2148. module.exports.Store = Store
  2149. }).call(this, require('_process'))
  2150. }, {
  2151. "../client": 1,
  2152. "../store": 7,
  2153. "./ali": 2,
  2154. "./tcp": 3,
  2155. "./tls": 4,
  2156. "./ws": 5,
  2157. "./wx": 6,
  2158. "_process": 92,
  2159. "url": 113,
  2160. "xtend": 121
  2161. }],
  2162. 10: [function(require, module, exports) {
  2163. 'use strict'
  2164. exports.byteLength = byteLength
  2165. exports.toByteArray = toByteArray
  2166. exports.fromByteArray = fromByteArray
  2167. var lookup = []
  2168. var revLookup = []
  2169. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  2170. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  2171. for (var i = 0, len = code.length; i < len; ++i) {
  2172. lookup[i] = code[i]
  2173. revLookup[code.charCodeAt(i)] = i
  2174. }
  2175. // Support decoding URL-safe base64 strings, as Node.js does.
  2176. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  2177. revLookup['-'.charCodeAt(0)] = 62
  2178. revLookup['_'.charCodeAt(0)] = 63
  2179. function getLens(b64) {
  2180. var len = b64.length
  2181. if (len % 4 > 0) {
  2182. throw new Error('Invalid string. Length must be a multiple of 4')
  2183. }
  2184. // Trim off extra bytes after placeholder bytes are found
  2185. // See: https://github.com/beatgammit/base64-js/issues/42
  2186. var validLen = b64.indexOf('=')
  2187. if (validLen === -1) validLen = len
  2188. var placeHoldersLen = validLen === len ?
  2189. 0 :
  2190. 4 - (validLen % 4)
  2191. return [validLen, placeHoldersLen]
  2192. }
  2193. // base64 is 4/3 + up to two characters of the original data
  2194. function byteLength(b64) {
  2195. var lens = getLens(b64)
  2196. var validLen = lens[0]
  2197. var placeHoldersLen = lens[1]
  2198. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2199. }
  2200. function _byteLength(b64, validLen, placeHoldersLen) {
  2201. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2202. }
  2203. function toByteArray(b64) {
  2204. var tmp
  2205. var lens = getLens(b64)
  2206. var validLen = lens[0]
  2207. var placeHoldersLen = lens[1]
  2208. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  2209. var curByte = 0
  2210. // if there are placeholders, only get up to the last complete 4 chars
  2211. var len = placeHoldersLen > 0 ?
  2212. validLen - 4 :
  2213. validLen
  2214. for (var i = 0; i < len; i += 4) {
  2215. tmp =
  2216. (revLookup[b64.charCodeAt(i)] << 18) |
  2217. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  2218. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  2219. revLookup[b64.charCodeAt(i + 3)]
  2220. arr[curByte++] = (tmp >> 16) & 0xFF
  2221. arr[curByte++] = (tmp >> 8) & 0xFF
  2222. arr[curByte++] = tmp & 0xFF
  2223. }
  2224. if (placeHoldersLen === 2) {
  2225. tmp =
  2226. (revLookup[b64.charCodeAt(i)] << 2) |
  2227. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  2228. arr[curByte++] = tmp & 0xFF
  2229. }
  2230. if (placeHoldersLen === 1) {
  2231. tmp =
  2232. (revLookup[b64.charCodeAt(i)] << 10) |
  2233. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  2234. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  2235. arr[curByte++] = (tmp >> 8) & 0xFF
  2236. arr[curByte++] = tmp & 0xFF
  2237. }
  2238. return arr
  2239. }
  2240. function tripletToBase64(num) {
  2241. return lookup[num >> 18 & 0x3F] +
  2242. lookup[num >> 12 & 0x3F] +
  2243. lookup[num >> 6 & 0x3F] +
  2244. lookup[num & 0x3F]
  2245. }
  2246. function encodeChunk(uint8, start, end) {
  2247. var tmp
  2248. var output = []
  2249. for (var i = start; i < end; i += 3) {
  2250. tmp =
  2251. ((uint8[i] << 16) & 0xFF0000) +
  2252. ((uint8[i + 1] << 8) & 0xFF00) +
  2253. (uint8[i + 2] & 0xFF)
  2254. output.push(tripletToBase64(tmp))
  2255. }
  2256. return output.join('')
  2257. }
  2258. function fromByteArray(uint8) {
  2259. var tmp
  2260. var len = uint8.length
  2261. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  2262. var parts = []
  2263. var maxChunkLength = 16383 // must be multiple of 3
  2264. // go through the array every three bytes, we'll deal with trailing stuff later
  2265. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  2266. parts.push(encodeChunk(
  2267. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  2268. ))
  2269. }
  2270. // pad the end with zeros, but make sure to not forget the extra bytes
  2271. if (extraBytes === 1) {
  2272. tmp = uint8[len - 1]
  2273. parts.push(
  2274. lookup[tmp >> 2] +
  2275. lookup[(tmp << 4) & 0x3F] +
  2276. '=='
  2277. )
  2278. } else if (extraBytes === 2) {
  2279. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  2280. parts.push(
  2281. lookup[tmp >> 10] +
  2282. lookup[(tmp >> 4) & 0x3F] +
  2283. lookup[(tmp << 2) & 0x3F] +
  2284. '='
  2285. )
  2286. }
  2287. return parts.join('')
  2288. }
  2289. }, {}],
  2290. 11: [function(require, module, exports) {
  2291. }, {}],
  2292. 12: [function(require, module, exports) {
  2293. /*!
  2294. * The buffer module from node.js, for the browser.
  2295. *
  2296. * @author Feross Aboukhadijeh <https://feross.org>
  2297. * @license MIT
  2298. */
  2299. /* eslint-disable no-proto */
  2300. 'use strict'
  2301. var base64 = require('base64-js')
  2302. var ieee754 = require('ieee754')
  2303. exports.Buffer = Buffer
  2304. exports.SlowBuffer = SlowBuffer
  2305. exports.INSPECT_MAX_BYTES = 50
  2306. var K_MAX_LENGTH = 0x7fffffff
  2307. exports.kMaxLength = K_MAX_LENGTH
  2308. /**
  2309. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  2310. * === true Use Uint8Array implementation (fastest)
  2311. * === false Print warning and recommend using `buffer` v4.x which has an Object
  2312. * implementation (most compatible, even IE6)
  2313. *
  2314. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  2315. * Opera 11.6+, iOS 4.2+.
  2316. *
  2317. * We report that the browser does not support typed arrays if the are not subclassable
  2318. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  2319. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  2320. * for __proto__ and has a buggy typed array implementation.
  2321. */
  2322. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  2323. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  2324. typeof console.error === 'function') {
  2325. console.error(
  2326. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  2327. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  2328. )
  2329. }
  2330. function typedArraySupport() {
  2331. // Can typed array instances can be augmented?
  2332. try {
  2333. var arr = new Uint8Array(1)
  2334. arr.__proto__ = {
  2335. __proto__: Uint8Array.prototype,
  2336. foo: function() {
  2337. return 42
  2338. }
  2339. }
  2340. return arr.foo() === 42
  2341. } catch (e) {
  2342. return false
  2343. }
  2344. }
  2345. Object.defineProperty(Buffer.prototype, 'parent', {
  2346. enumerable: true,
  2347. get: function() {
  2348. if (!Buffer.isBuffer(this)) return undefined
  2349. return this.buffer
  2350. }
  2351. })
  2352. Object.defineProperty(Buffer.prototype, 'offset', {
  2353. enumerable: true,
  2354. get: function() {
  2355. if (!Buffer.isBuffer(this)) return undefined
  2356. return this.byteOffset
  2357. }
  2358. })
  2359. function createBuffer(length) {
  2360. if (length > K_MAX_LENGTH) {
  2361. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  2362. }
  2363. // Return an augmented `Uint8Array` instance
  2364. var buf = new Uint8Array(length)
  2365. buf.__proto__ = Buffer.prototype
  2366. return buf
  2367. }
  2368. /**
  2369. * The Buffer constructor returns instances of `Uint8Array` that have their
  2370. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  2371. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  2372. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  2373. * returns a single octet.
  2374. *
  2375. * The `Uint8Array` prototype remains unmodified.
  2376. */
  2377. function Buffer(arg, encodingOrOffset, length) {
  2378. // Common case.
  2379. if (typeof arg === 'number') {
  2380. if (typeof encodingOrOffset === 'string') {
  2381. throw new TypeError(
  2382. 'The "string" argument must be of type string. Received type number'
  2383. )
  2384. }
  2385. return allocUnsafe(arg)
  2386. }
  2387. return from(arg, encodingOrOffset, length)
  2388. }
  2389. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2390. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  2391. Buffer[Symbol.species] === Buffer) {
  2392. Object.defineProperty(Buffer, Symbol.species, {
  2393. value: null,
  2394. configurable: true,
  2395. enumerable: false,
  2396. writable: false
  2397. })
  2398. }
  2399. Buffer.poolSize = 8192 // not used by this implementation
  2400. function from(value, encodingOrOffset, length) {
  2401. if (typeof value === 'string') {
  2402. return fromString(value, encodingOrOffset)
  2403. }
  2404. if (ArrayBuffer.isView(value)) {
  2405. return fromArrayLike(value)
  2406. }
  2407. if (value == null) {
  2408. throw TypeError(
  2409. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2410. 'or Array-like Object. Received type ' + (typeof value)
  2411. )
  2412. }
  2413. if (isInstance(value, ArrayBuffer) ||
  2414. (value && isInstance(value.buffer, ArrayBuffer))) {
  2415. return fromArrayBuffer(value, encodingOrOffset, length)
  2416. }
  2417. if (typeof value === 'number') {
  2418. throw new TypeError(
  2419. 'The "value" argument must not be of type number. Received type number'
  2420. )
  2421. }
  2422. var valueOf = value.valueOf && value.valueOf()
  2423. if (valueOf != null && valueOf !== value) {
  2424. return Buffer.from(valueOf, encodingOrOffset, length)
  2425. }
  2426. var b = fromObject(value)
  2427. if (b) return b
  2428. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  2429. typeof value[Symbol.toPrimitive] === 'function') {
  2430. return Buffer.from(
  2431. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  2432. )
  2433. }
  2434. throw new TypeError(
  2435. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2436. 'or Array-like Object. Received type ' + (typeof value)
  2437. )
  2438. }
  2439. /**
  2440. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2441. * if value is a number.
  2442. * Buffer.from(str[, encoding])
  2443. * Buffer.from(array)
  2444. * Buffer.from(buffer)
  2445. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2446. **/
  2447. Buffer.from = function(value, encodingOrOffset, length) {
  2448. return from(value, encodingOrOffset, length)
  2449. }
  2450. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  2451. // https://github.com/feross/buffer/pull/148
  2452. Buffer.prototype.__proto__ = Uint8Array.prototype
  2453. Buffer.__proto__ = Uint8Array
  2454. function assertSize(size) {
  2455. if (typeof size !== 'number') {
  2456. throw new TypeError('"size" argument must be of type number')
  2457. } else if (size < 0) {
  2458. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  2459. }
  2460. }
  2461. function alloc(size, fill, encoding) {
  2462. assertSize(size)
  2463. if (size <= 0) {
  2464. return createBuffer(size)
  2465. }
  2466. if (fill !== undefined) {
  2467. // Only pay attention to encoding if it's a string. This
  2468. // prevents accidentally sending in a number that would
  2469. // be interpretted as a start offset.
  2470. return typeof encoding === 'string' ?
  2471. createBuffer(size).fill(fill, encoding) :
  2472. createBuffer(size).fill(fill)
  2473. }
  2474. return createBuffer(size)
  2475. }
  2476. /**
  2477. * Creates a new filled Buffer instance.
  2478. * alloc(size[, fill[, encoding]])
  2479. **/
  2480. Buffer.alloc = function(size, fill, encoding) {
  2481. return alloc(size, fill, encoding)
  2482. }
  2483. function allocUnsafe(size) {
  2484. assertSize(size)
  2485. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  2486. }
  2487. /**
  2488. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  2489. * */
  2490. Buffer.allocUnsafe = function(size) {
  2491. return allocUnsafe(size)
  2492. }
  2493. /**
  2494. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  2495. */
  2496. Buffer.allocUnsafeSlow = function(size) {
  2497. return allocUnsafe(size)
  2498. }
  2499. function fromString(string, encoding) {
  2500. if (typeof encoding !== 'string' || encoding === '') {
  2501. encoding = 'utf8'
  2502. }
  2503. if (!Buffer.isEncoding(encoding)) {
  2504. throw new TypeError('Unknown encoding: ' + encoding)
  2505. }
  2506. var length = byteLength(string, encoding) | 0
  2507. var buf = createBuffer(length)
  2508. var actual = buf.write(string, encoding)
  2509. if (actual !== length) {
  2510. // Writing a hex string, for example, that contains invalid characters will
  2511. // cause everything after the first invalid character to be ignored. (e.g.
  2512. // 'abxxcd' will be treated as 'ab')
  2513. buf = buf.slice(0, actual)
  2514. }
  2515. return buf
  2516. }
  2517. function fromArrayLike(array) {
  2518. var length = array.length < 0 ? 0 : checked(array.length) | 0
  2519. var buf = createBuffer(length)
  2520. for (var i = 0; i < length; i += 1) {
  2521. buf[i] = array[i] & 255
  2522. }
  2523. return buf
  2524. }
  2525. function fromArrayBuffer(array, byteOffset, length) {
  2526. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2527. throw new RangeError('"offset" is outside of buffer bounds')
  2528. }
  2529. if (array.byteLength < byteOffset + (length || 0)) {
  2530. throw new RangeError('"length" is outside of buffer bounds')
  2531. }
  2532. var buf
  2533. if (byteOffset === undefined && length === undefined) {
  2534. buf = new Uint8Array(array)
  2535. } else if (length === undefined) {
  2536. buf = new Uint8Array(array, byteOffset)
  2537. } else {
  2538. buf = new Uint8Array(array, byteOffset, length)
  2539. }
  2540. // Return an augmented `Uint8Array` instance
  2541. buf.__proto__ = Buffer.prototype
  2542. return buf
  2543. }
  2544. function fromObject(obj) {
  2545. if (Buffer.isBuffer(obj)) {
  2546. var len = checked(obj.length) | 0
  2547. var buf = createBuffer(len)
  2548. if (buf.length === 0) {
  2549. return buf
  2550. }
  2551. obj.copy(buf, 0, 0, len)
  2552. return buf
  2553. }
  2554. if (obj.length !== undefined) {
  2555. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  2556. return createBuffer(0)
  2557. }
  2558. return fromArrayLike(obj)
  2559. }
  2560. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  2561. return fromArrayLike(obj.data)
  2562. }
  2563. }
  2564. function checked(length) {
  2565. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  2566. // length is NaN (which is otherwise coerced to zero.)
  2567. if (length >= K_MAX_LENGTH) {
  2568. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2569. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  2570. }
  2571. return length | 0
  2572. }
  2573. function SlowBuffer(length) {
  2574. if (+length != length) { // eslint-disable-line eqeqeq
  2575. length = 0
  2576. }
  2577. return Buffer.alloc(+length)
  2578. }
  2579. Buffer.isBuffer = function isBuffer(b) {
  2580. return b != null && b._isBuffer === true &&
  2581. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  2582. }
  2583. Buffer.compare = function compare(a, b) {
  2584. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  2585. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  2586. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  2587. throw new TypeError(
  2588. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  2589. )
  2590. }
  2591. if (a === b) return 0
  2592. var x = a.length
  2593. var y = b.length
  2594. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2595. if (a[i] !== b[i]) {
  2596. x = a[i]
  2597. y = b[i]
  2598. break
  2599. }
  2600. }
  2601. if (x < y) return -1
  2602. if (y < x) return 1
  2603. return 0
  2604. }
  2605. Buffer.isEncoding = function isEncoding(encoding) {
  2606. switch (String(encoding).toLowerCase()) {
  2607. case 'hex':
  2608. case 'utf8':
  2609. case 'utf-8':
  2610. case 'ascii':
  2611. case 'latin1':
  2612. case 'binary':
  2613. case 'base64':
  2614. case 'ucs2':
  2615. case 'ucs-2':
  2616. case 'utf16le':
  2617. case 'utf-16le':
  2618. return true
  2619. default:
  2620. return false
  2621. }
  2622. }
  2623. Buffer.concat = function concat(list, length) {
  2624. if (!Array.isArray(list)) {
  2625. throw new TypeError('"list" argument must be an Array of Buffers')
  2626. }
  2627. if (list.length === 0) {
  2628. return Buffer.alloc(0)
  2629. }
  2630. var i
  2631. if (length === undefined) {
  2632. length = 0
  2633. for (i = 0; i < list.length; ++i) {
  2634. length += list[i].length
  2635. }
  2636. }
  2637. var buffer = Buffer.allocUnsafe(length)
  2638. var pos = 0
  2639. for (i = 0; i < list.length; ++i) {
  2640. var buf = list[i]
  2641. if (isInstance(buf, Uint8Array)) {
  2642. buf = Buffer.from(buf)
  2643. }
  2644. if (!Buffer.isBuffer(buf)) {
  2645. throw new TypeError('"list" argument must be an Array of Buffers')
  2646. }
  2647. buf.copy(buffer, pos)
  2648. pos += buf.length
  2649. }
  2650. return buffer
  2651. }
  2652. function byteLength(string, encoding) {
  2653. if (Buffer.isBuffer(string)) {
  2654. return string.length
  2655. }
  2656. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  2657. return string.byteLength
  2658. }
  2659. if (typeof string !== 'string') {
  2660. throw new TypeError(
  2661. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  2662. 'Received type ' + typeof string
  2663. )
  2664. }
  2665. var len = string.length
  2666. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  2667. if (!mustMatch && len === 0) return 0
  2668. // Use a for loop to avoid recursion
  2669. var loweredCase = false
  2670. for (;;) {
  2671. switch (encoding) {
  2672. case 'ascii':
  2673. case 'latin1':
  2674. case 'binary':
  2675. return len
  2676. case 'utf8':
  2677. case 'utf-8':
  2678. return utf8ToBytes(string).length
  2679. case 'ucs2':
  2680. case 'ucs-2':
  2681. case 'utf16le':
  2682. case 'utf-16le':
  2683. return len * 2
  2684. case 'hex':
  2685. return len >>> 1
  2686. case 'base64':
  2687. return base64ToBytes(string).length
  2688. default:
  2689. if (loweredCase) {
  2690. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  2691. }
  2692. encoding = ('' + encoding).toLowerCase()
  2693. loweredCase = true
  2694. }
  2695. }
  2696. }
  2697. Buffer.byteLength = byteLength
  2698. function slowToString(encoding, start, end) {
  2699. var loweredCase = false
  2700. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  2701. // property of a typed array.
  2702. // This behaves neither like String nor Uint8Array in that we set start/end
  2703. // to their upper/lower bounds if the value passed is out of range.
  2704. // undefined is handled specially as per ECMA-262 6th Edition,
  2705. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  2706. if (start === undefined || start < 0) {
  2707. start = 0
  2708. }
  2709. // Return early if start > this.length. Done here to prevent potential uint32
  2710. // coercion fail below.
  2711. if (start > this.length) {
  2712. return ''
  2713. }
  2714. if (end === undefined || end > this.length) {
  2715. end = this.length
  2716. }
  2717. if (end <= 0) {
  2718. return ''
  2719. }
  2720. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  2721. end >>>= 0
  2722. start >>>= 0
  2723. if (end <= start) {
  2724. return ''
  2725. }
  2726. if (!encoding) encoding = 'utf8'
  2727. while (true) {
  2728. switch (encoding) {
  2729. case 'hex':
  2730. return hexSlice(this, start, end)
  2731. case 'utf8':
  2732. case 'utf-8':
  2733. return utf8Slice(this, start, end)
  2734. case 'ascii':
  2735. return asciiSlice(this, start, end)
  2736. case 'latin1':
  2737. case 'binary':
  2738. return latin1Slice(this, start, end)
  2739. case 'base64':
  2740. return base64Slice(this, start, end)
  2741. case 'ucs2':
  2742. case 'ucs-2':
  2743. case 'utf16le':
  2744. case 'utf-16le':
  2745. return utf16leSlice(this, start, end)
  2746. default:
  2747. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2748. encoding = (encoding + '').toLowerCase()
  2749. loweredCase = true
  2750. }
  2751. }
  2752. }
  2753. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  2754. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  2755. // reliably in a browserify context because there could be multiple different
  2756. // copies of the 'buffer' package in use. This method works even for Buffer
  2757. // instances that were created from another copy of the `buffer` package.
  2758. // See: https://github.com/feross/buffer/issues/154
  2759. Buffer.prototype._isBuffer = true
  2760. function swap(b, n, m) {
  2761. var i = b[n]
  2762. b[n] = b[m]
  2763. b[m] = i
  2764. }
  2765. Buffer.prototype.swap16 = function swap16() {
  2766. var len = this.length
  2767. if (len % 2 !== 0) {
  2768. throw new RangeError('Buffer size must be a multiple of 16-bits')
  2769. }
  2770. for (var i = 0; i < len; i += 2) {
  2771. swap(this, i, i + 1)
  2772. }
  2773. return this
  2774. }
  2775. Buffer.prototype.swap32 = function swap32() {
  2776. var len = this.length
  2777. if (len % 4 !== 0) {
  2778. throw new RangeError('Buffer size must be a multiple of 32-bits')
  2779. }
  2780. for (var i = 0; i < len; i += 4) {
  2781. swap(this, i, i + 3)
  2782. swap(this, i + 1, i + 2)
  2783. }
  2784. return this
  2785. }
  2786. Buffer.prototype.swap64 = function swap64() {
  2787. var len = this.length
  2788. if (len % 8 !== 0) {
  2789. throw new RangeError('Buffer size must be a multiple of 64-bits')
  2790. }
  2791. for (var i = 0; i < len; i += 8) {
  2792. swap(this, i, i + 7)
  2793. swap(this, i + 1, i + 6)
  2794. swap(this, i + 2, i + 5)
  2795. swap(this, i + 3, i + 4)
  2796. }
  2797. return this
  2798. }
  2799. Buffer.prototype.toString = function toString() {
  2800. var length = this.length
  2801. if (length === 0) return ''
  2802. if (arguments.length === 0) return utf8Slice(this, 0, length)
  2803. return slowToString.apply(this, arguments)
  2804. }
  2805. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  2806. Buffer.prototype.equals = function equals(b) {
  2807. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2808. if (this === b) return true
  2809. return Buffer.compare(this, b) === 0
  2810. }
  2811. Buffer.prototype.inspect = function inspect() {
  2812. var str = ''
  2813. var max = exports.INSPECT_MAX_BYTES
  2814. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  2815. if (this.length > max) str += ' ... '
  2816. return '<Buffer ' + str + '>'
  2817. }
  2818. Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
  2819. if (isInstance(target, Uint8Array)) {
  2820. target = Buffer.from(target, target.offset, target.byteLength)
  2821. }
  2822. if (!Buffer.isBuffer(target)) {
  2823. throw new TypeError(
  2824. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  2825. 'Received type ' + (typeof target)
  2826. )
  2827. }
  2828. if (start === undefined) {
  2829. start = 0
  2830. }
  2831. if (end === undefined) {
  2832. end = target ? target.length : 0
  2833. }
  2834. if (thisStart === undefined) {
  2835. thisStart = 0
  2836. }
  2837. if (thisEnd === undefined) {
  2838. thisEnd = this.length
  2839. }
  2840. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this
  2841. .length) {
  2842. throw new RangeError('out of range index')
  2843. }
  2844. if (thisStart >= thisEnd && start >= end) {
  2845. return 0
  2846. }
  2847. if (thisStart >= thisEnd) {
  2848. return -1
  2849. }
  2850. if (start >= end) {
  2851. return 1
  2852. }
  2853. start >>>= 0
  2854. end >>>= 0
  2855. thisStart >>>= 0
  2856. thisEnd >>>= 0
  2857. if (this === target) return 0
  2858. var x = thisEnd - thisStart
  2859. var y = end - start
  2860. var len = Math.min(x, y)
  2861. var thisCopy = this.slice(thisStart, thisEnd)
  2862. var targetCopy = target.slice(start, end)
  2863. for (var i = 0; i < len; ++i) {
  2864. if (thisCopy[i] !== targetCopy[i]) {
  2865. x = thisCopy[i]
  2866. y = targetCopy[i]
  2867. break
  2868. }
  2869. }
  2870. if (x < y) return -1
  2871. if (y < x) return 1
  2872. return 0
  2873. }
  2874. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  2875. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  2876. //
  2877. // Arguments:
  2878. // - buffer - a Buffer to search
  2879. // - val - a string, Buffer, or number
  2880. // - byteOffset - an index into `buffer`; will be clamped to an int32
  2881. // - encoding - an optional encoding, relevant is val is a string
  2882. // - dir - true for indexOf, false for lastIndexOf
  2883. function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
  2884. // Empty buffer means no match
  2885. if (buffer.length === 0) return -1
  2886. // Normalize byteOffset
  2887. if (typeof byteOffset === 'string') {
  2888. encoding = byteOffset
  2889. byteOffset = 0
  2890. } else if (byteOffset > 0x7fffffff) {
  2891. byteOffset = 0x7fffffff
  2892. } else if (byteOffset < -0x80000000) {
  2893. byteOffset = -0x80000000
  2894. }
  2895. byteOffset = +byteOffset // Coerce to Number.
  2896. if (numberIsNaN(byteOffset)) {
  2897. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  2898. byteOffset = dir ? 0 : (buffer.length - 1)
  2899. }
  2900. // Normalize byteOffset: negative offsets start from the end of the buffer
  2901. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  2902. if (byteOffset >= buffer.length) {
  2903. if (dir) return -1
  2904. else byteOffset = buffer.length - 1
  2905. } else if (byteOffset < 0) {
  2906. if (dir) byteOffset = 0
  2907. else return -1
  2908. }
  2909. // Normalize val
  2910. if (typeof val === 'string') {
  2911. val = Buffer.from(val, encoding)
  2912. }
  2913. // Finally, search either indexOf (if dir is true) or lastIndexOf
  2914. if (Buffer.isBuffer(val)) {
  2915. // Special case: looking for empty string/buffer always fails
  2916. if (val.length === 0) {
  2917. return -1
  2918. }
  2919. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  2920. } else if (typeof val === 'number') {
  2921. val = val & 0xFF // Search for a byte value [0-255]
  2922. if (typeof Uint8Array.prototype.indexOf === 'function') {
  2923. if (dir) {
  2924. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  2925. } else {
  2926. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  2927. }
  2928. }
  2929. return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
  2930. }
  2931. throw new TypeError('val must be string, number or Buffer')
  2932. }
  2933. function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
  2934. var indexSize = 1
  2935. var arrLength = arr.length
  2936. var valLength = val.length
  2937. if (encoding !== undefined) {
  2938. encoding = String(encoding).toLowerCase()
  2939. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  2940. encoding === 'utf16le' || encoding === 'utf-16le') {
  2941. if (arr.length < 2 || val.length < 2) {
  2942. return -1
  2943. }
  2944. indexSize = 2
  2945. arrLength /= 2
  2946. valLength /= 2
  2947. byteOffset /= 2
  2948. }
  2949. }
  2950. function read(buf, i) {
  2951. if (indexSize === 1) {
  2952. return buf[i]
  2953. } else {
  2954. return buf.readUInt16BE(i * indexSize)
  2955. }
  2956. }
  2957. var i
  2958. if (dir) {
  2959. var foundIndex = -1
  2960. for (i = byteOffset; i < arrLength; i++) {
  2961. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  2962. if (foundIndex === -1) foundIndex = i
  2963. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  2964. } else {
  2965. if (foundIndex !== -1) i -= i - foundIndex
  2966. foundIndex = -1
  2967. }
  2968. }
  2969. } else {
  2970. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  2971. for (i = byteOffset; i >= 0; i--) {
  2972. var found = true
  2973. for (var j = 0; j < valLength; j++) {
  2974. if (read(arr, i + j) !== read(val, j)) {
  2975. found = false
  2976. break
  2977. }
  2978. }
  2979. if (found) return i
  2980. }
  2981. }
  2982. return -1
  2983. }
  2984. Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
  2985. return this.indexOf(val, byteOffset, encoding) !== -1
  2986. }
  2987. Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
  2988. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  2989. }
  2990. Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
  2991. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  2992. }
  2993. function hexWrite(buf, string, offset, length) {
  2994. offset = Number(offset) || 0
  2995. var remaining = buf.length - offset
  2996. if (!length) {
  2997. length = remaining
  2998. } else {
  2999. length = Number(length)
  3000. if (length > remaining) {
  3001. length = remaining
  3002. }
  3003. }
  3004. var strLen = string.length
  3005. if (length > strLen / 2) {
  3006. length = strLen / 2
  3007. }
  3008. for (var i = 0; i < length; ++i) {
  3009. var parsed = parseInt(string.substr(i * 2, 2), 16)
  3010. if (numberIsNaN(parsed)) return i
  3011. buf[offset + i] = parsed
  3012. }
  3013. return i
  3014. }
  3015. function utf8Write(buf, string, offset, length) {
  3016. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  3017. }
  3018. function asciiWrite(buf, string, offset, length) {
  3019. return blitBuffer(asciiToBytes(string), buf, offset, length)
  3020. }
  3021. function latin1Write(buf, string, offset, length) {
  3022. return asciiWrite(buf, string, offset, length)
  3023. }
  3024. function base64Write(buf, string, offset, length) {
  3025. return blitBuffer(base64ToBytes(string), buf, offset, length)
  3026. }
  3027. function ucs2Write(buf, string, offset, length) {
  3028. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  3029. }
  3030. Buffer.prototype.write = function write(string, offset, length, encoding) {
  3031. // Buffer#write(string)
  3032. if (offset === undefined) {
  3033. encoding = 'utf8'
  3034. length = this.length
  3035. offset = 0
  3036. // Buffer#write(string, encoding)
  3037. } else if (length === undefined && typeof offset === 'string') {
  3038. encoding = offset
  3039. length = this.length
  3040. offset = 0
  3041. // Buffer#write(string, offset[, length][, encoding])
  3042. } else if (isFinite(offset)) {
  3043. offset = offset >>> 0
  3044. if (isFinite(length)) {
  3045. length = length >>> 0
  3046. if (encoding === undefined) encoding = 'utf8'
  3047. } else {
  3048. encoding = length
  3049. length = undefined
  3050. }
  3051. } else {
  3052. throw new Error(
  3053. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  3054. )
  3055. }
  3056. var remaining = this.length - offset
  3057. if (length === undefined || length > remaining) length = remaining
  3058. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  3059. throw new RangeError('Attempt to write outside buffer bounds')
  3060. }
  3061. if (!encoding) encoding = 'utf8'
  3062. var loweredCase = false
  3063. for (;;) {
  3064. switch (encoding) {
  3065. case 'hex':
  3066. return hexWrite(this, string, offset, length)
  3067. case 'utf8':
  3068. case 'utf-8':
  3069. return utf8Write(this, string, offset, length)
  3070. case 'ascii':
  3071. return asciiWrite(this, string, offset, length)
  3072. case 'latin1':
  3073. case 'binary':
  3074. return latin1Write(this, string, offset, length)
  3075. case 'base64':
  3076. // Warning: maxLength not taken into account in base64Write
  3077. return base64Write(this, string, offset, length)
  3078. case 'ucs2':
  3079. case 'ucs-2':
  3080. case 'utf16le':
  3081. case 'utf-16le':
  3082. return ucs2Write(this, string, offset, length)
  3083. default:
  3084. if (loweredCase) throw new TypeError('Unknown encoding: ' +
  3085. encoding)
  3086. encoding = ('' + encoding).toLowerCase()
  3087. loweredCase = true
  3088. }
  3089. }
  3090. }
  3091. Buffer.prototype.toJSON = function toJSON() {
  3092. return {
  3093. type: 'Buffer',
  3094. data: Array.prototype.slice.call(this._arr || this, 0)
  3095. }
  3096. }
  3097. function base64Slice(buf, start, end) {
  3098. if (start === 0 && end === buf.length) {
  3099. return base64.fromByteArray(buf)
  3100. } else {
  3101. return base64.fromByteArray(buf.slice(start, end))
  3102. }
  3103. }
  3104. function utf8Slice(buf, start, end) {
  3105. end = Math.min(buf.length, end)
  3106. var res = []
  3107. var i = start
  3108. while (i < end) {
  3109. var firstByte = buf[i]
  3110. var codePoint = null
  3111. var bytesPerSequence = (firstByte > 0xEF) ? 4 :
  3112. (firstByte > 0xDF) ? 3 :
  3113. (firstByte > 0xBF) ? 2 :
  3114. 1
  3115. if (i + bytesPerSequence <= end) {
  3116. var secondByte, thirdByte, fourthByte, tempCodePoint
  3117. switch (bytesPerSequence) {
  3118. case 1:
  3119. if (firstByte < 0x80) {
  3120. codePoint = firstByte
  3121. }
  3122. break
  3123. case 2:
  3124. secondByte = buf[i + 1]
  3125. if ((secondByte & 0xC0) === 0x80) {
  3126. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  3127. if (tempCodePoint > 0x7F) {
  3128. codePoint = tempCodePoint
  3129. }
  3130. }
  3131. break
  3132. case 3:
  3133. secondByte = buf[i + 1]
  3134. thirdByte = buf[i + 2]
  3135. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  3136. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte &
  3137. 0x3F) << 0x6 | (thirdByte & 0x3F)
  3138. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 ||
  3139. tempCodePoint > 0xDFFF)) {
  3140. codePoint = tempCodePoint
  3141. }
  3142. }
  3143. break
  3144. case 4:
  3145. secondByte = buf[i + 1]
  3146. thirdByte = buf[i + 2]
  3147. fourthByte = buf[i + 3]
  3148. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (
  3149. fourthByte & 0xC0) === 0x80) {
  3150. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte &
  3151. 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte &
  3152. 0x3F)
  3153. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  3154. codePoint = tempCodePoint
  3155. }
  3156. }
  3157. }
  3158. }
  3159. if (codePoint === null) {
  3160. // we did not generate a valid codePoint so insert a
  3161. // replacement char (U+FFFD) and advance only 1 byte
  3162. codePoint = 0xFFFD
  3163. bytesPerSequence = 1
  3164. } else if (codePoint > 0xFFFF) {
  3165. // encode to utf16 (surrogate pair dance)
  3166. codePoint -= 0x10000
  3167. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  3168. codePoint = 0xDC00 | codePoint & 0x3FF
  3169. }
  3170. res.push(codePoint)
  3171. i += bytesPerSequence
  3172. }
  3173. return decodeCodePointsArray(res)
  3174. }
  3175. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  3176. // the lowest limit is Chrome, with 0x10000 args.
  3177. // We go 1 magnitude less, for safety
  3178. var MAX_ARGUMENTS_LENGTH = 0x1000
  3179. function decodeCodePointsArray(codePoints) {
  3180. var len = codePoints.length
  3181. if (len <= MAX_ARGUMENTS_LENGTH) {
  3182. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  3183. }
  3184. // Decode in chunks to avoid "call stack size exceeded".
  3185. var res = ''
  3186. var i = 0
  3187. while (i < len) {
  3188. res += String.fromCharCode.apply(
  3189. String,
  3190. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  3191. )
  3192. }
  3193. return res
  3194. }
  3195. function asciiSlice(buf, start, end) {
  3196. var ret = ''
  3197. end = Math.min(buf.length, end)
  3198. for (var i = start; i < end; ++i) {
  3199. ret += String.fromCharCode(buf[i] & 0x7F)
  3200. }
  3201. return ret
  3202. }
  3203. function latin1Slice(buf, start, end) {
  3204. var ret = ''
  3205. end = Math.min(buf.length, end)
  3206. for (var i = start; i < end; ++i) {
  3207. ret += String.fromCharCode(buf[i])
  3208. }
  3209. return ret
  3210. }
  3211. function hexSlice(buf, start, end) {
  3212. var len = buf.length
  3213. if (!start || start < 0) start = 0
  3214. if (!end || end < 0 || end > len) end = len
  3215. var out = ''
  3216. for (var i = start; i < end; ++i) {
  3217. out += toHex(buf[i])
  3218. }
  3219. return out
  3220. }
  3221. function utf16leSlice(buf, start, end) {
  3222. var bytes = buf.slice(start, end)
  3223. var res = ''
  3224. for (var i = 0; i < bytes.length; i += 2) {
  3225. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  3226. }
  3227. return res
  3228. }
  3229. Buffer.prototype.slice = function slice(start, end) {
  3230. var len = this.length
  3231. start = ~~start
  3232. end = end === undefined ? len : ~~end
  3233. if (start < 0) {
  3234. start += len
  3235. if (start < 0) start = 0
  3236. } else if (start > len) {
  3237. start = len
  3238. }
  3239. if (end < 0) {
  3240. end += len
  3241. if (end < 0) end = 0
  3242. } else if (end > len) {
  3243. end = len
  3244. }
  3245. if (end < start) end = start
  3246. var newBuf = this.subarray(start, end)
  3247. // Return an augmented `Uint8Array` instance
  3248. newBuf.__proto__ = Buffer.prototype
  3249. return newBuf
  3250. }
  3251. /*
  3252. * Need to make sure that buffer isn't trying to write out of bounds.
  3253. */
  3254. function checkOffset(offset, ext, length) {
  3255. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  3256. if (offset + ext > length) throw new RangeError(
  3257. 'Trying to access beyond buffer length')
  3258. }
  3259. Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
  3260. offset = offset >>> 0
  3261. byteLength = byteLength >>> 0
  3262. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3263. var val = this[offset]
  3264. var mul = 1
  3265. var i = 0
  3266. while (++i < byteLength && (mul *= 0x100)) {
  3267. val += this[offset + i] * mul
  3268. }
  3269. return val
  3270. }
  3271. Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
  3272. offset = offset >>> 0
  3273. byteLength = byteLength >>> 0
  3274. if (!noAssert) {
  3275. checkOffset(offset, byteLength, this.length)
  3276. }
  3277. var val = this[offset + --byteLength]
  3278. var mul = 1
  3279. while (byteLength > 0 && (mul *= 0x100)) {
  3280. val += this[offset + --byteLength] * mul
  3281. }
  3282. return val
  3283. }
  3284. Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
  3285. offset = offset >>> 0
  3286. if (!noAssert) checkOffset(offset, 1, this.length)
  3287. return this[offset]
  3288. }
  3289. Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
  3290. offset = offset >>> 0
  3291. if (!noAssert) checkOffset(offset, 2, this.length)
  3292. return this[offset] | (this[offset + 1] << 8)
  3293. }
  3294. Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
  3295. offset = offset >>> 0
  3296. if (!noAssert) checkOffset(offset, 2, this.length)
  3297. return (this[offset] << 8) | this[offset + 1]
  3298. }
  3299. Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
  3300. offset = offset >>> 0
  3301. if (!noAssert) checkOffset(offset, 4, this.length)
  3302. return ((this[offset]) |
  3303. (this[offset + 1] << 8) |
  3304. (this[offset + 2] << 16)) +
  3305. (this[offset + 3] * 0x1000000)
  3306. }
  3307. Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
  3308. offset = offset >>> 0
  3309. if (!noAssert) checkOffset(offset, 4, this.length)
  3310. return (this[offset] * 0x1000000) +
  3311. ((this[offset + 1] << 16) |
  3312. (this[offset + 2] << 8) |
  3313. this[offset + 3])
  3314. }
  3315. Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
  3316. offset = offset >>> 0
  3317. byteLength = byteLength >>> 0
  3318. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3319. var val = this[offset]
  3320. var mul = 1
  3321. var i = 0
  3322. while (++i < byteLength && (mul *= 0x100)) {
  3323. val += this[offset + i] * mul
  3324. }
  3325. mul *= 0x80
  3326. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3327. return val
  3328. }
  3329. Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
  3330. offset = offset >>> 0
  3331. byteLength = byteLength >>> 0
  3332. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3333. var i = byteLength
  3334. var mul = 1
  3335. var val = this[offset + --i]
  3336. while (i > 0 && (mul *= 0x100)) {
  3337. val += this[offset + --i] * mul
  3338. }
  3339. mul *= 0x80
  3340. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3341. return val
  3342. }
  3343. Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
  3344. offset = offset >>> 0
  3345. if (!noAssert) checkOffset(offset, 1, this.length)
  3346. if (!(this[offset] & 0x80)) return (this[offset])
  3347. return ((0xff - this[offset] + 1) * -1)
  3348. }
  3349. Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
  3350. offset = offset >>> 0
  3351. if (!noAssert) checkOffset(offset, 2, this.length)
  3352. var val = this[offset] | (this[offset + 1] << 8)
  3353. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3354. }
  3355. Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
  3356. offset = offset >>> 0
  3357. if (!noAssert) checkOffset(offset, 2, this.length)
  3358. var val = this[offset + 1] | (this[offset] << 8)
  3359. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3360. }
  3361. Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
  3362. offset = offset >>> 0
  3363. if (!noAssert) checkOffset(offset, 4, this.length)
  3364. return (this[offset]) |
  3365. (this[offset + 1] << 8) |
  3366. (this[offset + 2] << 16) |
  3367. (this[offset + 3] << 24)
  3368. }
  3369. Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
  3370. offset = offset >>> 0
  3371. if (!noAssert) checkOffset(offset, 4, this.length)
  3372. return (this[offset] << 24) |
  3373. (this[offset + 1] << 16) |
  3374. (this[offset + 2] << 8) |
  3375. (this[offset + 3])
  3376. }
  3377. Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
  3378. offset = offset >>> 0
  3379. if (!noAssert) checkOffset(offset, 4, this.length)
  3380. return ieee754.read(this, offset, true, 23, 4)
  3381. }
  3382. Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
  3383. offset = offset >>> 0
  3384. if (!noAssert) checkOffset(offset, 4, this.length)
  3385. return ieee754.read(this, offset, false, 23, 4)
  3386. }
  3387. Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
  3388. offset = offset >>> 0
  3389. if (!noAssert) checkOffset(offset, 8, this.length)
  3390. return ieee754.read(this, offset, true, 52, 8)
  3391. }
  3392. Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
  3393. offset = offset >>> 0
  3394. if (!noAssert) checkOffset(offset, 8, this.length)
  3395. return ieee754.read(this, offset, false, 52, 8)
  3396. }
  3397. function checkInt(buf, value, offset, ext, max, min) {
  3398. if (!Buffer.isBuffer(buf)) throw new TypeError(
  3399. '"buffer" argument must be a Buffer instance')
  3400. if (value > max || value < min) throw new RangeError(
  3401. '"value" argument is out of bounds')
  3402. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3403. }
  3404. Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength,
  3405. noAssert) {
  3406. value = +value
  3407. offset = offset >>> 0
  3408. byteLength = byteLength >>> 0
  3409. if (!noAssert) {
  3410. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3411. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3412. }
  3413. var mul = 1
  3414. var i = 0
  3415. this[offset] = value & 0xFF
  3416. while (++i < byteLength && (mul *= 0x100)) {
  3417. this[offset + i] = (value / mul) & 0xFF
  3418. }
  3419. return offset + byteLength
  3420. }
  3421. Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength,
  3422. noAssert) {
  3423. value = +value
  3424. offset = offset >>> 0
  3425. byteLength = byteLength >>> 0
  3426. if (!noAssert) {
  3427. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3428. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3429. }
  3430. var i = byteLength - 1
  3431. var mul = 1
  3432. this[offset + i] = value & 0xFF
  3433. while (--i >= 0 && (mul *= 0x100)) {
  3434. this[offset + i] = (value / mul) & 0xFF
  3435. }
  3436. return offset + byteLength
  3437. }
  3438. Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
  3439. value = +value
  3440. offset = offset >>> 0
  3441. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  3442. this[offset] = (value & 0xff)
  3443. return offset + 1
  3444. }
  3445. Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
  3446. value = +value
  3447. offset = offset >>> 0
  3448. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3449. this[offset] = (value & 0xff)
  3450. this[offset + 1] = (value >>> 8)
  3451. return offset + 2
  3452. }
  3453. Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
  3454. value = +value
  3455. offset = offset >>> 0
  3456. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3457. this[offset] = (value >>> 8)
  3458. this[offset + 1] = (value & 0xff)
  3459. return offset + 2
  3460. }
  3461. Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
  3462. value = +value
  3463. offset = offset >>> 0
  3464. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3465. this[offset + 3] = (value >>> 24)
  3466. this[offset + 2] = (value >>> 16)
  3467. this[offset + 1] = (value >>> 8)
  3468. this[offset] = (value & 0xff)
  3469. return offset + 4
  3470. }
  3471. Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
  3472. value = +value
  3473. offset = offset >>> 0
  3474. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3475. this[offset] = (value >>> 24)
  3476. this[offset + 1] = (value >>> 16)
  3477. this[offset + 2] = (value >>> 8)
  3478. this[offset + 3] = (value & 0xff)
  3479. return offset + 4
  3480. }
  3481. Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
  3482. value = +value
  3483. offset = offset >>> 0
  3484. if (!noAssert) {
  3485. var limit = Math.pow(2, (8 * byteLength) - 1)
  3486. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3487. }
  3488. var i = 0
  3489. var mul = 1
  3490. var sub = 0
  3491. this[offset] = value & 0xFF
  3492. while (++i < byteLength && (mul *= 0x100)) {
  3493. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  3494. sub = 1
  3495. }
  3496. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3497. }
  3498. return offset + byteLength
  3499. }
  3500. Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
  3501. value = +value
  3502. offset = offset >>> 0
  3503. if (!noAssert) {
  3504. var limit = Math.pow(2, (8 * byteLength) - 1)
  3505. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3506. }
  3507. var i = byteLength - 1
  3508. var mul = 1
  3509. var sub = 0
  3510. this[offset + i] = value & 0xFF
  3511. while (--i >= 0 && (mul *= 0x100)) {
  3512. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  3513. sub = 1
  3514. }
  3515. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3516. }
  3517. return offset + byteLength
  3518. }
  3519. Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
  3520. value = +value
  3521. offset = offset >>> 0
  3522. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  3523. if (value < 0) value = 0xff + value + 1
  3524. this[offset] = (value & 0xff)
  3525. return offset + 1
  3526. }
  3527. Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
  3528. value = +value
  3529. offset = offset >>> 0
  3530. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3531. this[offset] = (value & 0xff)
  3532. this[offset + 1] = (value >>> 8)
  3533. return offset + 2
  3534. }
  3535. Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
  3536. value = +value
  3537. offset = offset >>> 0
  3538. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3539. this[offset] = (value >>> 8)
  3540. this[offset + 1] = (value & 0xff)
  3541. return offset + 2
  3542. }
  3543. Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
  3544. value = +value
  3545. offset = offset >>> 0
  3546. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3547. this[offset] = (value & 0xff)
  3548. this[offset + 1] = (value >>> 8)
  3549. this[offset + 2] = (value >>> 16)
  3550. this[offset + 3] = (value >>> 24)
  3551. return offset + 4
  3552. }
  3553. Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
  3554. value = +value
  3555. offset = offset >>> 0
  3556. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3557. if (value < 0) value = 0xffffffff + value + 1
  3558. this[offset] = (value >>> 24)
  3559. this[offset + 1] = (value >>> 16)
  3560. this[offset + 2] = (value >>> 8)
  3561. this[offset + 3] = (value & 0xff)
  3562. return offset + 4
  3563. }
  3564. function checkIEEE754(buf, value, offset, ext, max, min) {
  3565. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3566. if (offset < 0) throw new RangeError('Index out of range')
  3567. }
  3568. function writeFloat(buf, value, offset, littleEndian, noAssert) {
  3569. value = +value
  3570. offset = offset >>> 0
  3571. if (!noAssert) {
  3572. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -
  3573. 3.4028234663852886e+38)
  3574. }
  3575. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  3576. return offset + 4
  3577. }
  3578. Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
  3579. return writeFloat(this, value, offset, true, noAssert)
  3580. }
  3581. Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
  3582. return writeFloat(this, value, offset, false, noAssert)
  3583. }
  3584. function writeDouble(buf, value, offset, littleEndian, noAssert) {
  3585. value = +value
  3586. offset = offset >>> 0
  3587. if (!noAssert) {
  3588. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -
  3589. 1.7976931348623157E+308)
  3590. }
  3591. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  3592. return offset + 8
  3593. }
  3594. Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
  3595. return writeDouble(this, value, offset, true, noAssert)
  3596. }
  3597. Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
  3598. return writeDouble(this, value, offset, false, noAssert)
  3599. }
  3600. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  3601. Buffer.prototype.copy = function copy(target, targetStart, start, end) {
  3602. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  3603. if (!start) start = 0
  3604. if (!end && end !== 0) end = this.length
  3605. if (targetStart >= target.length) targetStart = target.length
  3606. if (!targetStart) targetStart = 0
  3607. if (end > 0 && end < start) end = start
  3608. // Copy 0 bytes; we're done
  3609. if (end === start) return 0
  3610. if (target.length === 0 || this.length === 0) return 0
  3611. // Fatal error conditions
  3612. if (targetStart < 0) {
  3613. throw new RangeError('targetStart out of bounds')
  3614. }
  3615. if (start < 0 || start >= this.length) throw new RangeError(
  3616. 'Index out of range')
  3617. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  3618. // Are we oob?
  3619. if (end > this.length) end = this.length
  3620. if (target.length - targetStart < end - start) {
  3621. end = target.length - targetStart + start
  3622. }
  3623. var len = end - start
  3624. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  3625. // Use built-in when available, missing from IE11
  3626. this.copyWithin(targetStart, start, end)
  3627. } else if (this === target && start < targetStart && targetStart < end) {
  3628. // descending copy from end
  3629. for (var i = len - 1; i >= 0; --i) {
  3630. target[i + targetStart] = this[i + start]
  3631. }
  3632. } else {
  3633. Uint8Array.prototype.set.call(
  3634. target,
  3635. this.subarray(start, end),
  3636. targetStart
  3637. )
  3638. }
  3639. return len
  3640. }
  3641. // Usage:
  3642. // buffer.fill(number[, offset[, end]])
  3643. // buffer.fill(buffer[, offset[, end]])
  3644. // buffer.fill(string[, offset[, end]][, encoding])
  3645. Buffer.prototype.fill = function fill(val, start, end, encoding) {
  3646. // Handle string cases:
  3647. if (typeof val === 'string') {
  3648. if (typeof start === 'string') {
  3649. encoding = start
  3650. start = 0
  3651. end = this.length
  3652. } else if (typeof end === 'string') {
  3653. encoding = end
  3654. end = this.length
  3655. }
  3656. if (encoding !== undefined && typeof encoding !== 'string') {
  3657. throw new TypeError('encoding must be a string')
  3658. }
  3659. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  3660. throw new TypeError('Unknown encoding: ' + encoding)
  3661. }
  3662. if (val.length === 1) {
  3663. var code = val.charCodeAt(0)
  3664. if ((encoding === 'utf8' && code < 128) ||
  3665. encoding === 'latin1') {
  3666. // Fast path: If `val` fits into a single byte, use that numeric value.
  3667. val = code
  3668. }
  3669. }
  3670. } else if (typeof val === 'number') {
  3671. val = val & 255
  3672. }
  3673. // Invalid ranges are not set to a default, so can range check early.
  3674. if (start < 0 || this.length < start || this.length < end) {
  3675. throw new RangeError('Out of range index')
  3676. }
  3677. if (end <= start) {
  3678. return this
  3679. }
  3680. start = start >>> 0
  3681. end = end === undefined ? this.length : end >>> 0
  3682. if (!val) val = 0
  3683. var i
  3684. if (typeof val === 'number') {
  3685. for (i = start; i < end; ++i) {
  3686. this[i] = val
  3687. }
  3688. } else {
  3689. var bytes = Buffer.isBuffer(val) ?
  3690. val :
  3691. Buffer.from(val, encoding)
  3692. var len = bytes.length
  3693. if (len === 0) {
  3694. throw new TypeError('The value "' + val +
  3695. '" is invalid for argument "value"')
  3696. }
  3697. for (i = 0; i < end - start; ++i) {
  3698. this[i + start] = bytes[i % len]
  3699. }
  3700. }
  3701. return this
  3702. }
  3703. // HELPER FUNCTIONS
  3704. // ================
  3705. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  3706. function base64clean(str) {
  3707. // Node takes equal signs as end of the Base64 encoding
  3708. str = str.split('=')[0]
  3709. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  3710. str = str.trim().replace(INVALID_BASE64_RE, '')
  3711. // Node converts strings with length < 2 to ''
  3712. if (str.length < 2) return ''
  3713. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  3714. while (str.length % 4 !== 0) {
  3715. str = str + '='
  3716. }
  3717. return str
  3718. }
  3719. function toHex(n) {
  3720. if (n < 16) return '0' + n.toString(16)
  3721. return n.toString(16)
  3722. }
  3723. function utf8ToBytes(string, units) {
  3724. units = units || Infinity
  3725. var codePoint
  3726. var length = string.length
  3727. var leadSurrogate = null
  3728. var bytes = []
  3729. for (var i = 0; i < length; ++i) {
  3730. codePoint = string.charCodeAt(i)
  3731. // is surrogate component
  3732. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  3733. // last char was a lead
  3734. if (!leadSurrogate) {
  3735. // no lead yet
  3736. if (codePoint > 0xDBFF) {
  3737. // unexpected trail
  3738. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3739. continue
  3740. } else if (i + 1 === length) {
  3741. // unpaired lead
  3742. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3743. continue
  3744. }
  3745. // valid lead
  3746. leadSurrogate = codePoint
  3747. continue
  3748. }
  3749. // 2 leads in a row
  3750. if (codePoint < 0xDC00) {
  3751. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3752. leadSurrogate = codePoint
  3753. continue
  3754. }
  3755. // valid surrogate pair
  3756. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  3757. } else if (leadSurrogate) {
  3758. // valid bmp char, but last char was a lead
  3759. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3760. }
  3761. leadSurrogate = null
  3762. // encode utf8
  3763. if (codePoint < 0x80) {
  3764. if ((units -= 1) < 0) break
  3765. bytes.push(codePoint)
  3766. } else if (codePoint < 0x800) {
  3767. if ((units -= 2) < 0) break
  3768. bytes.push(
  3769. codePoint >> 0x6 | 0xC0,
  3770. codePoint & 0x3F | 0x80
  3771. )
  3772. } else if (codePoint < 0x10000) {
  3773. if ((units -= 3) < 0) break
  3774. bytes.push(
  3775. codePoint >> 0xC | 0xE0,
  3776. codePoint >> 0x6 & 0x3F | 0x80,
  3777. codePoint & 0x3F | 0x80
  3778. )
  3779. } else if (codePoint < 0x110000) {
  3780. if ((units -= 4) < 0) break
  3781. bytes.push(
  3782. codePoint >> 0x12 | 0xF0,
  3783. codePoint >> 0xC & 0x3F | 0x80,
  3784. codePoint >> 0x6 & 0x3F | 0x80,
  3785. codePoint & 0x3F | 0x80
  3786. )
  3787. } else {
  3788. throw new Error('Invalid code point')
  3789. }
  3790. }
  3791. return bytes
  3792. }
  3793. function asciiToBytes(str) {
  3794. var byteArray = []
  3795. for (var i = 0; i < str.length; ++i) {
  3796. // Node's code seems to be doing this and not & 0x7F..
  3797. byteArray.push(str.charCodeAt(i) & 0xFF)
  3798. }
  3799. return byteArray
  3800. }
  3801. function utf16leToBytes(str, units) {
  3802. var c, hi, lo
  3803. var byteArray = []
  3804. for (var i = 0; i < str.length; ++i) {
  3805. if ((units -= 2) < 0) break
  3806. c = str.charCodeAt(i)
  3807. hi = c >> 8
  3808. lo = c % 256
  3809. byteArray.push(lo)
  3810. byteArray.push(hi)
  3811. }
  3812. return byteArray
  3813. }
  3814. function base64ToBytes(str) {
  3815. return base64.toByteArray(base64clean(str))
  3816. }
  3817. function blitBuffer(src, dst, offset, length) {
  3818. for (var i = 0; i < length; ++i) {
  3819. if ((i + offset >= dst.length) || (i >= src.length)) break
  3820. dst[i + offset] = src[i]
  3821. }
  3822. return i
  3823. }
  3824. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  3825. // the `instanceof` check but they should be treated as of that type.
  3826. // See: https://github.com/feross/buffer/issues/166
  3827. function isInstance(obj, type) {
  3828. return obj instanceof type ||
  3829. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  3830. obj.constructor.name === type.name)
  3831. }
  3832. function numberIsNaN(obj) {
  3833. // For IE11 support
  3834. return obj !== obj // eslint-disable-line no-self-compare
  3835. }
  3836. }, {
  3837. "base64-js": 10,
  3838. "ieee754": 79
  3839. }],
  3840. 13: [function(require, module, exports) {
  3841. // Copyright Joyent, Inc. and other Node contributors.
  3842. //
  3843. // Permission is hereby granted, free of charge, to any person obtaining a
  3844. // copy of this software and associated documentation files (the
  3845. // "Software"), to deal in the Software without restriction, including
  3846. // without limitation the rights to use, copy, modify, merge, publish,
  3847. // distribute, sublicense, and/or sell copies of the Software, and to permit
  3848. // persons to whom the Software is furnished to do so, subject to the
  3849. // following conditions:
  3850. //
  3851. // The above copyright notice and this permission notice shall be included
  3852. // in all copies or substantial portions of the Software.
  3853. //
  3854. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  3855. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3856. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  3857. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  3858. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  3859. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  3860. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  3861. var objectCreate = Object.create || objectCreatePolyfill
  3862. var objectKeys = Object.keys || objectKeysPolyfill
  3863. var bind = Function.prototype.bind || functionBindPolyfill
  3864. function EventEmitter() {
  3865. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  3866. this._events = objectCreate(null);
  3867. this._eventsCount = 0;
  3868. }
  3869. this._maxListeners = this._maxListeners || undefined;
  3870. }
  3871. module.exports = EventEmitter;
  3872. // Backwards-compat with node 0.10.x
  3873. EventEmitter.EventEmitter = EventEmitter;
  3874. EventEmitter.prototype._events = undefined;
  3875. EventEmitter.prototype._maxListeners = undefined;
  3876. // By default EventEmitters will print a warning if more than 10 listeners are
  3877. // added to it. This is a useful default which helps finding memory leaks.
  3878. var defaultMaxListeners = 10;
  3879. var hasDefineProperty;
  3880. try {
  3881. var o = {};
  3882. if (Object.defineProperty) Object.defineProperty(o, 'x', {
  3883. value: 0
  3884. });
  3885. hasDefineProperty = o.x === 0;
  3886. } catch (err) {
  3887. hasDefineProperty = false
  3888. }
  3889. if (hasDefineProperty) {
  3890. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  3891. enumerable: true,
  3892. get: function() {
  3893. return defaultMaxListeners;
  3894. },
  3895. set: function(arg) {
  3896. // check whether the input is a positive number (whose value is zero or
  3897. // greater and not a NaN).
  3898. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  3899. throw new TypeError(
  3900. '"defaultMaxListeners" must be a positive number');
  3901. defaultMaxListeners = arg;
  3902. }
  3903. });
  3904. } else {
  3905. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  3906. }
  3907. // Obviously not all Emitters should be limited to 10. This function allows
  3908. // that to be increased. Set to zero for unlimited.
  3909. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  3910. if (typeof n !== 'number' || n < 0 || isNaN(n))
  3911. throw new TypeError('"n" argument must be a positive number');
  3912. this._maxListeners = n;
  3913. return this;
  3914. };
  3915. function $getMaxListeners(that) {
  3916. if (that._maxListeners === undefined)
  3917. return EventEmitter.defaultMaxListeners;
  3918. return that._maxListeners;
  3919. }
  3920. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  3921. return $getMaxListeners(this);
  3922. };
  3923. // These standalone emit* functions are used to optimize calling of event
  3924. // handlers for fast cases because emit() itself often has a variable number of
  3925. // arguments and can be deoptimized because of that. These functions always have
  3926. // the same number of arguments and thus do not get deoptimized, so the code
  3927. // inside them can execute faster.
  3928. function emitNone(handler, isFn, self) {
  3929. if (isFn)
  3930. handler.call(self);
  3931. else {
  3932. var len = handler.length;
  3933. var listeners = arrayClone(handler, len);
  3934. for (var i = 0; i < len; ++i)
  3935. listeners[i].call(self);
  3936. }
  3937. }
  3938. function emitOne(handler, isFn, self, arg1) {
  3939. if (isFn)
  3940. handler.call(self, arg1);
  3941. else {
  3942. var len = handler.length;
  3943. var listeners = arrayClone(handler, len);
  3944. for (var i = 0; i < len; ++i)
  3945. listeners[i].call(self, arg1);
  3946. }
  3947. }
  3948. function emitTwo(handler, isFn, self, arg1, arg2) {
  3949. if (isFn)
  3950. handler.call(self, arg1, arg2);
  3951. else {
  3952. var len = handler.length;
  3953. var listeners = arrayClone(handler, len);
  3954. for (var i = 0; i < len; ++i)
  3955. listeners[i].call(self, arg1, arg2);
  3956. }
  3957. }
  3958. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  3959. if (isFn)
  3960. handler.call(self, arg1, arg2, arg3);
  3961. else {
  3962. var len = handler.length;
  3963. var listeners = arrayClone(handler, len);
  3964. for (var i = 0; i < len; ++i)
  3965. listeners[i].call(self, arg1, arg2, arg3);
  3966. }
  3967. }
  3968. function emitMany(handler, isFn, self, args) {
  3969. if (isFn)
  3970. handler.apply(self, args);
  3971. else {
  3972. var len = handler.length;
  3973. var listeners = arrayClone(handler, len);
  3974. for (var i = 0; i < len; ++i)
  3975. listeners[i].apply(self, args);
  3976. }
  3977. }
  3978. EventEmitter.prototype.emit = function emit(type) {
  3979. var er, handler, len, args, i, events;
  3980. var doError = (type === 'error');
  3981. events = this._events;
  3982. if (events)
  3983. doError = (doError && events.error == null);
  3984. else if (!doError)
  3985. return false;
  3986. // If there is no 'error' event listener then throw.
  3987. if (doError) {
  3988. if (arguments.length > 1)
  3989. er = arguments[1];
  3990. if (er instanceof Error) {
  3991. throw er; // Unhandled 'error' event
  3992. } else {
  3993. // At least give some kind of context to the user
  3994. var err = new Error('Unhandled "error" event. (' + er + ')');
  3995. err.context = er;
  3996. throw err;
  3997. }
  3998. return false;
  3999. }
  4000. handler = events[type];
  4001. if (!handler)
  4002. return false;
  4003. var isFn = typeof handler === 'function';
  4004. len = arguments.length;
  4005. switch (len) {
  4006. // fast cases
  4007. case 1:
  4008. emitNone(handler, isFn, this);
  4009. break;
  4010. case 2:
  4011. emitOne(handler, isFn, this, arguments[1]);
  4012. break;
  4013. case 3:
  4014. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  4015. break;
  4016. case 4:
  4017. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[
  4018. 3]);
  4019. break;
  4020. // slower
  4021. default:
  4022. args = new Array(len - 1);
  4023. for (i = 1; i < len; i++)
  4024. args[i - 1] = arguments[i];
  4025. emitMany(handler, isFn, this, args);
  4026. }
  4027. return true;
  4028. };
  4029. function _addListener(target, type, listener, prepend) {
  4030. var m;
  4031. var events;
  4032. var existing;
  4033. if (typeof listener !== 'function')
  4034. throw new TypeError('"listener" argument must be a function');
  4035. events = target._events;
  4036. if (!events) {
  4037. events = target._events = objectCreate(null);
  4038. target._eventsCount = 0;
  4039. } else {
  4040. // To avoid recursion in the case that type === "newListener"! Before
  4041. // adding it to the listeners, first emit "newListener".
  4042. if (events.newListener) {
  4043. target.emit('newListener', type,
  4044. listener.listener ? listener.listener : listener);
  4045. // Re-assign `events` because a newListener handler could have caused the
  4046. // this._events to be assigned to a new object
  4047. events = target._events;
  4048. }
  4049. existing = events[type];
  4050. }
  4051. if (!existing) {
  4052. // Optimize the case of one listener. Don't need the extra array object.
  4053. existing = events[type] = listener;
  4054. ++target._eventsCount;
  4055. } else {
  4056. if (typeof existing === 'function') {
  4057. // Adding the second element, need to change to array.
  4058. existing = events[type] =
  4059. prepend ? [listener, existing] : [existing, listener];
  4060. } else {
  4061. // If we've already got an array, just append.
  4062. if (prepend) {
  4063. existing.unshift(listener);
  4064. } else {
  4065. existing.push(listener);
  4066. }
  4067. }
  4068. // Check for listener leak
  4069. if (!existing.warned) {
  4070. m = $getMaxListeners(target);
  4071. if (m && m > 0 && existing.length > m) {
  4072. existing.warned = true;
  4073. var w = new Error('Possible EventEmitter memory leak detected. ' +
  4074. existing.length + ' "' + String(type) + '" listeners ' +
  4075. 'added. Use emitter.setMaxListeners() to ' +
  4076. 'increase limit.');
  4077. w.name = 'MaxListenersExceededWarning';
  4078. w.emitter = target;
  4079. w.type = type;
  4080. w.count = existing.length;
  4081. if (typeof console === 'object' && console.warn) {
  4082. console.warn('%s: %s', w.name, w.message);
  4083. }
  4084. }
  4085. }
  4086. }
  4087. return target;
  4088. }
  4089. EventEmitter.prototype.addListener = function addListener(type, listener) {
  4090. return _addListener(this, type, listener, false);
  4091. };
  4092. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  4093. EventEmitter.prototype.prependListener =
  4094. function prependListener(type, listener) {
  4095. return _addListener(this, type, listener, true);
  4096. };
  4097. function onceWrapper() {
  4098. if (!this.fired) {
  4099. this.target.removeListener(this.type, this.wrapFn);
  4100. this.fired = true;
  4101. switch (arguments.length) {
  4102. case 0:
  4103. return this.listener.call(this.target);
  4104. case 1:
  4105. return this.listener.call(this.target, arguments[0]);
  4106. case 2:
  4107. return this.listener.call(this.target, arguments[0], arguments[1]);
  4108. case 3:
  4109. return this.listener.call(this.target, arguments[0], arguments[1],
  4110. arguments[2]);
  4111. default:
  4112. var args = new Array(arguments.length);
  4113. for (var i = 0; i < args.length; ++i)
  4114. args[i] = arguments[i];
  4115. this.listener.apply(this.target, args);
  4116. }
  4117. }
  4118. }
  4119. function _onceWrap(target, type, listener) {
  4120. var state = {
  4121. fired: false,
  4122. wrapFn: undefined,
  4123. target: target,
  4124. type: type,
  4125. listener: listener
  4126. };
  4127. var wrapped = bind.call(onceWrapper, state);
  4128. wrapped.listener = listener;
  4129. state.wrapFn = wrapped;
  4130. return wrapped;
  4131. }
  4132. EventEmitter.prototype.once = function once(type, listener) {
  4133. if (typeof listener !== 'function')
  4134. throw new TypeError('"listener" argument must be a function');
  4135. this.on(type, _onceWrap(this, type, listener));
  4136. return this;
  4137. };
  4138. EventEmitter.prototype.prependOnceListener =
  4139. function prependOnceListener(type, listener) {
  4140. if (typeof listener !== 'function')
  4141. throw new TypeError('"listener" argument must be a function');
  4142. this.prependListener(type, _onceWrap(this, type, listener));
  4143. return this;
  4144. };
  4145. // Emits a 'removeListener' event if and only if the listener was removed.
  4146. EventEmitter.prototype.removeListener =
  4147. function removeListener(type, listener) {
  4148. var list, events, position, i, originalListener;
  4149. if (typeof listener !== 'function')
  4150. throw new TypeError('"listener" argument must be a function');
  4151. events = this._events;
  4152. if (!events)
  4153. return this;
  4154. list = events[type];
  4155. if (!list)
  4156. return this;
  4157. if (list === listener || list.listener === listener) {
  4158. if (--this._eventsCount === 0)
  4159. this._events = objectCreate(null);
  4160. else {
  4161. delete events[type];
  4162. if (events.removeListener)
  4163. this.emit('removeListener', type, list.listener || listener);
  4164. }
  4165. } else if (typeof list !== 'function') {
  4166. position = -1;
  4167. for (i = list.length - 1; i >= 0; i--) {
  4168. if (list[i] === listener || list[i].listener === listener) {
  4169. originalListener = list[i].listener;
  4170. position = i;
  4171. break;
  4172. }
  4173. }
  4174. if (position < 0)
  4175. return this;
  4176. if (position === 0)
  4177. list.shift();
  4178. else
  4179. spliceOne(list, position);
  4180. if (list.length === 1)
  4181. events[type] = list[0];
  4182. if (events.removeListener)
  4183. this.emit('removeListener', type, originalListener || listener);
  4184. }
  4185. return this;
  4186. };
  4187. EventEmitter.prototype.removeAllListeners =
  4188. function removeAllListeners(type) {
  4189. var listeners, events, i;
  4190. events = this._events;
  4191. if (!events)
  4192. return this;
  4193. // not listening for removeListener, no need to emit
  4194. if (!events.removeListener) {
  4195. if (arguments.length === 0) {
  4196. this._events = objectCreate(null);
  4197. this._eventsCount = 0;
  4198. } else if (events[type]) {
  4199. if (--this._eventsCount === 0)
  4200. this._events = objectCreate(null);
  4201. else
  4202. delete events[type];
  4203. }
  4204. return this;
  4205. }
  4206. // emit removeListener for all listeners on all events
  4207. if (arguments.length === 0) {
  4208. var keys = objectKeys(events);
  4209. var key;
  4210. for (i = 0; i < keys.length; ++i) {
  4211. key = keys[i];
  4212. if (key === 'removeListener') continue;
  4213. this.removeAllListeners(key);
  4214. }
  4215. this.removeAllListeners('removeListener');
  4216. this._events = objectCreate(null);
  4217. this._eventsCount = 0;
  4218. return this;
  4219. }
  4220. listeners = events[type];
  4221. if (typeof listeners === 'function') {
  4222. this.removeListener(type, listeners);
  4223. } else if (listeners) {
  4224. // LIFO order
  4225. for (i = listeners.length - 1; i >= 0; i--) {
  4226. this.removeListener(type, listeners[i]);
  4227. }
  4228. }
  4229. return this;
  4230. };
  4231. function _listeners(target, type, unwrap) {
  4232. var events = target._events;
  4233. if (!events)
  4234. return [];
  4235. var evlistener = events[type];
  4236. if (!evlistener)
  4237. return [];
  4238. if (typeof evlistener === 'function')
  4239. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  4240. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener
  4241. .length);
  4242. }
  4243. EventEmitter.prototype.listeners = function listeners(type) {
  4244. return _listeners(this, type, true);
  4245. };
  4246. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  4247. return _listeners(this, type, false);
  4248. };
  4249. EventEmitter.listenerCount = function(emitter, type) {
  4250. if (typeof emitter.listenerCount === 'function') {
  4251. return emitter.listenerCount(type);
  4252. } else {
  4253. return listenerCount.call(emitter, type);
  4254. }
  4255. };
  4256. EventEmitter.prototype.listenerCount = listenerCount;
  4257. function listenerCount(type) {
  4258. var events = this._events;
  4259. if (events) {
  4260. var evlistener = events[type];
  4261. if (typeof evlistener === 'function') {
  4262. return 1;
  4263. } else if (evlistener) {
  4264. return evlistener.length;
  4265. }
  4266. }
  4267. return 0;
  4268. }
  4269. EventEmitter.prototype.eventNames = function eventNames() {
  4270. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  4271. };
  4272. // About 1.5x faster than the two-arg version of Array#splice().
  4273. function spliceOne(list, index) {
  4274. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  4275. list[i] = list[k];
  4276. list.pop();
  4277. }
  4278. function arrayClone(arr, n) {
  4279. var copy = new Array(n);
  4280. for (var i = 0; i < n; ++i)
  4281. copy[i] = arr[i];
  4282. return copy;
  4283. }
  4284. function unwrapListeners(arr) {
  4285. var ret = new Array(arr.length);
  4286. for (var i = 0; i < ret.length; ++i) {
  4287. ret[i] = arr[i].listener || arr[i];
  4288. }
  4289. return ret;
  4290. }
  4291. function objectCreatePolyfill(proto) {
  4292. var F = function() {};
  4293. F.prototype = proto;
  4294. return new F;
  4295. }
  4296. function objectKeysPolyfill(obj) {
  4297. var keys = [];
  4298. for (var k in obj)
  4299. if (Object.prototype.hasOwnProperty.call(obj, k)) {
  4300. keys.push(k);
  4301. }
  4302. return k;
  4303. }
  4304. function functionBindPolyfill(context) {
  4305. var fn = this;
  4306. return function() {
  4307. return fn.apply(context, arguments);
  4308. };
  4309. }
  4310. }, {}],
  4311. 14: [function(require, module, exports) {
  4312. (function(Buffer) {
  4313. // Copyright Joyent, Inc. and other Node contributors.
  4314. //
  4315. // Permission is hereby granted, free of charge, to any person obtaining a
  4316. // copy of this software and associated documentation files (the
  4317. // "Software"), to deal in the Software without restriction, including
  4318. // without limitation the rights to use, copy, modify, merge, publish,
  4319. // distribute, sublicense, and/or sell copies of the Software, and to permit
  4320. // persons to whom the Software is furnished to do so, subject to the
  4321. // following conditions:
  4322. //
  4323. // The above copyright notice and this permission notice shall be included
  4324. // in all copies or substantial portions of the Software.
  4325. //
  4326. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4327. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4328. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  4329. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  4330. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  4331. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  4332. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  4333. // NOTE: These type checking functions intentionally don't use `instanceof`
  4334. // because it is fragile and can be easily faked with `Object.create()`.
  4335. function isArray(arg) {
  4336. if (Array.isArray) {
  4337. return Array.isArray(arg);
  4338. }
  4339. return objectToString(arg) === '[object Array]';
  4340. }
  4341. exports.isArray = isArray;
  4342. function isBoolean(arg) {
  4343. return typeof arg === 'boolean';
  4344. }
  4345. exports.isBoolean = isBoolean;
  4346. function isNull(arg) {
  4347. return arg === null;
  4348. }
  4349. exports.isNull = isNull;
  4350. function isNullOrUndefined(arg) {
  4351. return arg == null;
  4352. }
  4353. exports.isNullOrUndefined = isNullOrUndefined;
  4354. function isNumber(arg) {
  4355. return typeof arg === 'number';
  4356. }
  4357. exports.isNumber = isNumber;
  4358. function isString(arg) {
  4359. return typeof arg === 'string';
  4360. }
  4361. exports.isString = isString;
  4362. function isSymbol(arg) {
  4363. return typeof arg === 'symbol';
  4364. }
  4365. exports.isSymbol = isSymbol;
  4366. function isUndefined(arg) {
  4367. return arg === void 0;
  4368. }
  4369. exports.isUndefined = isUndefined;
  4370. function isRegExp(re) {
  4371. return objectToString(re) === '[object RegExp]';
  4372. }
  4373. exports.isRegExp = isRegExp;
  4374. function isObject(arg) {
  4375. return typeof arg === 'object' && arg !== null;
  4376. }
  4377. exports.isObject = isObject;
  4378. function isDate(d) {
  4379. return objectToString(d) === '[object Date]';
  4380. }
  4381. exports.isDate = isDate;
  4382. function isError(e) {
  4383. return (objectToString(e) === '[object Error]' || e instanceof Error);
  4384. }
  4385. exports.isError = isError;
  4386. function isFunction(arg) {
  4387. return typeof arg === 'function';
  4388. }
  4389. exports.isFunction = isFunction;
  4390. function isPrimitive(arg) {
  4391. return arg === null ||
  4392. typeof arg === 'boolean' ||
  4393. typeof arg === 'number' ||
  4394. typeof arg === 'string' ||
  4395. typeof arg === 'symbol' || // ES6 symbol
  4396. typeof arg === 'undefined';
  4397. }
  4398. exports.isPrimitive = isPrimitive;
  4399. exports.isBuffer = Buffer.isBuffer;
  4400. function objectToString(o) {
  4401. return Object.prototype.toString.call(o);
  4402. }
  4403. }).call(this, {
  4404. "isBuffer": require("../../is-buffer/index.js")
  4405. })
  4406. }, {
  4407. "../../is-buffer/index.js": 81
  4408. }],
  4409. 15: [function(require, module, exports) {
  4410. 'use strict';
  4411. var copy = require('es5-ext/object/copy'),
  4412. normalizeOptions = require('es5-ext/object/normalize-options'),
  4413. ensureCallable = require('es5-ext/object/valid-callable'),
  4414. map = require('es5-ext/object/map'),
  4415. callable = require('es5-ext/object/valid-callable'),
  4416. validValue = require('es5-ext/object/valid-value')
  4417. ,
  4418. bind = Function.prototype.bind,
  4419. defineProperty = Object.defineProperty,
  4420. hasOwnProperty = Object.prototype.hasOwnProperty,
  4421. define;
  4422. define = function(name, desc, options) {
  4423. var value = validValue(desc) && callable(desc.value),
  4424. dgs;
  4425. dgs = copy(desc);
  4426. delete dgs.writable;
  4427. delete dgs.value;
  4428. dgs.get = function() {
  4429. if (!options.overwriteDefinition && hasOwnProperty.call(this, name))
  4430. return value;
  4431. desc.value = bind.call(value, options.resolveContext ? options
  4432. .resolveContext(this) : this);
  4433. defineProperty(this, name, desc);
  4434. return this[name];
  4435. };
  4436. return dgs;
  4437. };
  4438. module.exports = function(props /*, options*/ ) {
  4439. var options = normalizeOptions(arguments[1]);
  4440. if (options.resolveContext != null) ensureCallable(options.resolveContext);
  4441. return map(props, function(desc, name) {
  4442. return define(name, desc, options);
  4443. });
  4444. };
  4445. }, {
  4446. "es5-ext/object/copy": 39,
  4447. "es5-ext/object/map": 48,
  4448. "es5-ext/object/normalize-options": 49,
  4449. "es5-ext/object/valid-callable": 54,
  4450. "es5-ext/object/valid-value": 55
  4451. }],
  4452. 16: [function(require, module, exports) {
  4453. 'use strict';
  4454. var assign = require('es5-ext/object/assign'),
  4455. normalizeOpts = require('es5-ext/object/normalize-options'),
  4456. isCallable = require('es5-ext/object/is-callable'),
  4457. contains = require('es5-ext/string/#/contains')
  4458. ,
  4459. d;
  4460. d = module.exports = function(dscr, value /*, options*/ ) {
  4461. var c, e, w, options, desc;
  4462. if ((arguments.length < 2) || (typeof dscr !== 'string')) {
  4463. options = value;
  4464. value = dscr;
  4465. dscr = null;
  4466. } else {
  4467. options = arguments[2];
  4468. }
  4469. if (dscr == null) {
  4470. c = w = true;
  4471. e = false;
  4472. } else {
  4473. c = contains.call(dscr, 'c');
  4474. e = contains.call(dscr, 'e');
  4475. w = contains.call(dscr, 'w');
  4476. }
  4477. desc = {
  4478. value: value,
  4479. configurable: c,
  4480. enumerable: e,
  4481. writable: w
  4482. };
  4483. return !options ? desc : assign(normalizeOpts(options), desc);
  4484. };
  4485. d.gs = function(dscr, get, set /*, options*/ ) {
  4486. var c, e, options, desc;
  4487. if (typeof dscr !== 'string') {
  4488. options = set;
  4489. set = get;
  4490. get = dscr;
  4491. dscr = null;
  4492. } else {
  4493. options = arguments[3];
  4494. }
  4495. if (get == null) {
  4496. get = undefined;
  4497. } else if (!isCallable(get)) {
  4498. options = get;
  4499. get = set = undefined;
  4500. } else if (set == null) {
  4501. set = undefined;
  4502. } else if (!isCallable(set)) {
  4503. options = set;
  4504. set = undefined;
  4505. }
  4506. if (dscr == null) {
  4507. c = true;
  4508. e = false;
  4509. } else {
  4510. c = contains.call(dscr, 'c');
  4511. e = contains.call(dscr, 'e');
  4512. }
  4513. desc = {
  4514. get: get,
  4515. set: set,
  4516. configurable: c,
  4517. enumerable: e
  4518. };
  4519. return !options ? desc : assign(normalizeOpts(options), desc);
  4520. };
  4521. }, {
  4522. "es5-ext/object/assign": 36,
  4523. "es5-ext/object/is-callable": 42,
  4524. "es5-ext/object/normalize-options": 49,
  4525. "es5-ext/string/#/contains": 56
  4526. }],
  4527. 17: [function(require, module, exports) {
  4528. (function(process, Buffer) {
  4529. var stream = require('readable-stream')
  4530. var eos = require('end-of-stream')
  4531. var inherits = require('inherits')
  4532. var shift = require('stream-shift')
  4533. var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from) ?
  4534. Buffer.from([0]) :
  4535. new Buffer([0])
  4536. var onuncork = function(self, fn) {
  4537. if (self._corked) self.once('uncork', fn)
  4538. else fn()
  4539. }
  4540. var autoDestroy = function(self, err) {
  4541. if (self._autoDestroy) self.destroy(err)
  4542. }
  4543. var destroyer = function(self, end) {
  4544. return function(err) {
  4545. if (err) autoDestroy(self, err.message === 'premature close' ?
  4546. null : err)
  4547. else if (end && !self._ended) self.end()
  4548. }
  4549. }
  4550. var end = function(ws, fn) {
  4551. if (!ws) return fn()
  4552. if (ws._writableState && ws._writableState.finished) return fn()
  4553. if (ws._writableState) return ws.end(fn)
  4554. ws.end()
  4555. fn()
  4556. }
  4557. var toStreams2 = function(rs) {
  4558. return new(stream.Readable)({
  4559. objectMode: true,
  4560. highWaterMark: 16
  4561. }).wrap(rs)
  4562. }
  4563. var Duplexify = function(writable, readable, opts) {
  4564. if (!(this instanceof Duplexify)) return new Duplexify(writable,
  4565. readable, opts)
  4566. stream.Duplex.call(this, opts)
  4567. this._writable = null
  4568. this._readable = null
  4569. this._readable2 = null
  4570. this._autoDestroy = !opts || opts.autoDestroy !== false
  4571. this._forwardDestroy = !opts || opts.destroy !== false
  4572. this._forwardEnd = !opts || opts.end !== false
  4573. this._corked = 1 // start corked
  4574. this._ondrain = null
  4575. this._drained = false
  4576. this._forwarding = false
  4577. this._unwrite = null
  4578. this._unread = null
  4579. this._ended = false
  4580. this.destroyed = false
  4581. if (writable) this.setWritable(writable)
  4582. if (readable) this.setReadable(readable)
  4583. }
  4584. inherits(Duplexify, stream.Duplex)
  4585. Duplexify.obj = function(writable, readable, opts) {
  4586. if (!opts) opts = {}
  4587. opts.objectMode = true
  4588. opts.highWaterMark = 16
  4589. return new Duplexify(writable, readable, opts)
  4590. }
  4591. Duplexify.prototype.cork = function() {
  4592. if (++this._corked === 1) this.emit('cork')
  4593. }
  4594. Duplexify.prototype.uncork = function() {
  4595. if (this._corked && --this._corked === 0) this.emit('uncork')
  4596. }
  4597. Duplexify.prototype.setWritable = function(writable) {
  4598. if (this._unwrite) this._unwrite()
  4599. if (this.destroyed) {
  4600. if (writable && writable.destroy) writable.destroy()
  4601. return
  4602. }
  4603. if (writable === null || writable === false) {
  4604. this.end()
  4605. return
  4606. }
  4607. var self = this
  4608. var unend = eos(writable, {
  4609. writable: true,
  4610. readable: false
  4611. }, destroyer(this, this._forwardEnd))
  4612. var ondrain = function() {
  4613. var ondrain = self._ondrain
  4614. self._ondrain = null
  4615. if (ondrain) ondrain()
  4616. }
  4617. var clear = function() {
  4618. self._writable.removeListener('drain', ondrain)
  4619. unend()
  4620. }
  4621. if (this._unwrite) process.nextTick(
  4622. ondrain) // force a drain on stream reset to avoid livelocks
  4623. this._writable = writable
  4624. this._writable.on('drain', ondrain)
  4625. this._unwrite = clear
  4626. this.uncork() // always uncork setWritable
  4627. }
  4628. Duplexify.prototype.setReadable = function(readable) {
  4629. if (this._unread) this._unread()
  4630. if (this.destroyed) {
  4631. if (readable && readable.destroy) readable.destroy()
  4632. return
  4633. }
  4634. if (readable === null || readable === false) {
  4635. this.push(null)
  4636. this.resume()
  4637. return
  4638. }
  4639. var self = this
  4640. var unend = eos(readable, {
  4641. writable: false,
  4642. readable: true
  4643. }, destroyer(this))
  4644. var onreadable = function() {
  4645. self._forward()
  4646. }
  4647. var onend = function() {
  4648. self.push(null)
  4649. }
  4650. var clear = function() {
  4651. self._readable2.removeListener('readable', onreadable)
  4652. self._readable2.removeListener('end', onend)
  4653. unend()
  4654. }
  4655. this._drained = true
  4656. this._readable = readable
  4657. this._readable2 = readable._readableState ? readable : toStreams2(
  4658. readable)
  4659. this._readable2.on('readable', onreadable)
  4660. this._readable2.on('end', onend)
  4661. this._unread = clear
  4662. this._forward()
  4663. }
  4664. Duplexify.prototype._read = function() {
  4665. this._drained = true
  4666. this._forward()
  4667. }
  4668. Duplexify.prototype._forward = function() {
  4669. if (this._forwarding || !this._readable2 || !this._drained) return
  4670. this._forwarding = true
  4671. var data
  4672. while (this._drained && (data = shift(this._readable2)) !== null) {
  4673. if (this.destroyed) continue
  4674. this._drained = this.push(data)
  4675. }
  4676. this._forwarding = false
  4677. }
  4678. Duplexify.prototype.destroy = function(err) {
  4679. if (this.destroyed) return
  4680. this.destroyed = true
  4681. var self = this
  4682. process.nextTick(function() {
  4683. self._destroy(err)
  4684. })
  4685. }
  4686. Duplexify.prototype._destroy = function(err) {
  4687. if (err) {
  4688. var ondrain = this._ondrain
  4689. this._ondrain = null
  4690. if (ondrain) ondrain(err)
  4691. else this.emit('error', err)
  4692. }
  4693. if (this._forwardDestroy) {
  4694. if (this._readable && this._readable.destroy) this._readable
  4695. .destroy()
  4696. if (this._writable && this._writable.destroy) this._writable
  4697. .destroy()
  4698. }
  4699. this.emit('close')
  4700. }
  4701. Duplexify.prototype._write = function(data, enc, cb) {
  4702. if (this.destroyed) return cb()
  4703. if (this._corked) return onuncork(this, this._write.bind(this, data,
  4704. enc, cb))
  4705. if (data === SIGNAL_FLUSH) return this._finish(cb)
  4706. if (!this._writable) return cb()
  4707. if (this._writable.write(data) === false) this._ondrain = cb
  4708. else cb()
  4709. }
  4710. Duplexify.prototype._finish = function(cb) {
  4711. var self = this
  4712. this.emit('preend')
  4713. onuncork(this, function() {
  4714. end(self._forwardEnd && self._writable, function() {
  4715. // haxx to not emit prefinish twice
  4716. if (self._writableState.prefinished === false)
  4717. self._writableState.prefinished = true
  4718. self.emit('prefinish')
  4719. onuncork(self, cb)
  4720. })
  4721. })
  4722. }
  4723. Duplexify.prototype.end = function(data, enc, cb) {
  4724. if (typeof data === 'function') return this.end(null, null, data)
  4725. if (typeof enc === 'function') return this.end(data, null, enc)
  4726. this._ended = true
  4727. if (data) this.write(data)
  4728. if (!this._writableState.ending) this.write(SIGNAL_FLUSH)
  4729. return stream.Writable.prototype.end.call(this, cb)
  4730. }
  4731. module.exports = Duplexify
  4732. }).call(this, require('_process'), require("buffer").Buffer)
  4733. }, {
  4734. "_process": 92,
  4735. "buffer": 12,
  4736. "end-of-stream": 18,
  4737. "inherits": 80,
  4738. "readable-stream": 108,
  4739. "stream-shift": 111
  4740. }],
  4741. 18: [function(require, module, exports) {
  4742. var once = require('once');
  4743. var noop = function() {};
  4744. var isRequest = function(stream) {
  4745. return stream.setHeader && typeof stream.abort === 'function';
  4746. };
  4747. var isChildProcess = function(stream) {
  4748. return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
  4749. };
  4750. var eos = function(stream, opts, callback) {
  4751. if (typeof opts === 'function') return eos(stream, null, opts);
  4752. if (!opts) opts = {};
  4753. callback = once(callback || noop);
  4754. var ws = stream._writableState;
  4755. var rs = stream._readableState;
  4756. var readable = opts.readable || (opts.readable !== false && stream.readable);
  4757. var writable = opts.writable || (opts.writable !== false && stream.writable);
  4758. var onlegacyfinish = function() {
  4759. if (!stream.writable) onfinish();
  4760. };
  4761. var onfinish = function() {
  4762. writable = false;
  4763. if (!readable) callback.call(stream);
  4764. };
  4765. var onend = function() {
  4766. readable = false;
  4767. if (!writable) callback.call(stream);
  4768. };
  4769. var onexit = function(exitCode) {
  4770. callback.call(stream, exitCode ? new Error('exited with error code: ' +
  4771. exitCode) : null);
  4772. };
  4773. var onerror = function(err) {
  4774. callback.call(stream, err);
  4775. };
  4776. var onclose = function() {
  4777. if (readable && !(rs && rs.ended)) return callback.call(stream,
  4778. new Error('premature close'));
  4779. if (writable && !(ws && ws.ended)) return callback.call(stream,
  4780. new Error('premature close'));
  4781. };
  4782. var onrequest = function() {
  4783. stream.req.on('finish', onfinish);
  4784. };
  4785. if (isRequest(stream)) {
  4786. stream.on('complete', onfinish);
  4787. stream.on('abort', onclose);
  4788. if (stream.req) onrequest();
  4789. else stream.on('request', onrequest);
  4790. } else if (writable && !ws) { // legacy streams
  4791. stream.on('end', onlegacyfinish);
  4792. stream.on('close', onlegacyfinish);
  4793. }
  4794. if (isChildProcess(stream)) stream.on('exit', onexit);
  4795. stream.on('end', onend);
  4796. stream.on('finish', onfinish);
  4797. if (opts.error !== false) stream.on('error', onerror);
  4798. stream.on('close', onclose);
  4799. return function() {
  4800. stream.removeListener('complete', onfinish);
  4801. stream.removeListener('abort', onclose);
  4802. stream.removeListener('request', onrequest);
  4803. if (stream.req) stream.req.removeListener('finish', onfinish);
  4804. stream.removeListener('end', onlegacyfinish);
  4805. stream.removeListener('close', onlegacyfinish);
  4806. stream.removeListener('finish', onfinish);
  4807. stream.removeListener('exit', onexit);
  4808. stream.removeListener('end', onend);
  4809. stream.removeListener('error', onerror);
  4810. stream.removeListener('close', onclose);
  4811. };
  4812. };
  4813. module.exports = eos;
  4814. }, {
  4815. "once": 90
  4816. }],
  4817. 19: [function(require, module, exports) {
  4818. // Inspired by Google Closure:
  4819. // http://closure-library.googlecode.com/svn/docs/
  4820. // closure_goog_array_array.js.html#goog.array.clear
  4821. "use strict";
  4822. var value = require("../../object/valid-value");
  4823. module.exports = function() {
  4824. value(this).length = 0;
  4825. return this;
  4826. };
  4827. }, {
  4828. "../../object/valid-value": 55
  4829. }],
  4830. 20: [function(require, module, exports) {
  4831. "use strict";
  4832. var numberIsNaN = require("../../number/is-nan"),
  4833. toPosInt = require("../../number/to-pos-integer"),
  4834. value = require("../../object/valid-value"),
  4835. indexOf = Array.prototype.indexOf,
  4836. objHasOwnProperty = Object.prototype.hasOwnProperty,
  4837. abs = Math.abs,
  4838. floor = Math.floor;
  4839. module.exports = function(searchElement /*, fromIndex*/ ) {
  4840. var i, length, fromIndex, val;
  4841. if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments);
  4842. length = toPosInt(value(this).length);
  4843. fromIndex = arguments[1];
  4844. if (isNaN(fromIndex)) fromIndex = 0;
  4845. else if (fromIndex >= 0) fromIndex = floor(fromIndex);
  4846. else fromIndex = toPosInt(this.length) - floor(abs(fromIndex));
  4847. for (i = fromIndex; i < length; ++i) {
  4848. if (objHasOwnProperty.call(this, i)) {
  4849. val = this[i];
  4850. if (numberIsNaN(val)) return i; // Jslint: ignore
  4851. }
  4852. }
  4853. return -1;
  4854. };
  4855. }, {
  4856. "../../number/is-nan": 30,
  4857. "../../number/to-pos-integer": 34,
  4858. "../../object/valid-value": 55
  4859. }],
  4860. 21: [function(require, module, exports) {
  4861. "use strict";
  4862. module.exports = require("./is-implemented")() ?
  4863. Array.from :
  4864. require("./shim");
  4865. }, {
  4866. "./is-implemented": 22,
  4867. "./shim": 23
  4868. }],
  4869. 22: [function(require, module, exports) {
  4870. "use strict";
  4871. module.exports = function() {
  4872. var from = Array.from,
  4873. arr, result;
  4874. if (typeof from !== "function") return false;
  4875. arr = ["raz", "dwa"];
  4876. result = from(arr);
  4877. return Boolean(result && (result !== arr) && (result[1] === "dwa"));
  4878. };
  4879. }, {}],
  4880. 23: [function(require, module, exports) {
  4881. "use strict";
  4882. var iteratorSymbol = require("es6-symbol").iterator,
  4883. isArguments = require("../../function/is-arguments"),
  4884. isFunction = require("../../function/is-function"),
  4885. toPosInt = require("../../number/to-pos-integer"),
  4886. callable = require("../../object/valid-callable"),
  4887. validValue = require("../../object/valid-value"),
  4888. isValue = require("../../object/is-value"),
  4889. isString = require("../../string/is-string"),
  4890. isArray = Array.isArray,
  4891. call = Function.prototype.call,
  4892. desc = {
  4893. configurable: true,
  4894. enumerable: true,
  4895. writable: true,
  4896. value: null
  4897. },
  4898. defineProperty = Object.defineProperty;
  4899. // eslint-disable-next-line complexity
  4900. module.exports = function(arrayLike /*, mapFn, thisArg*/ ) {
  4901. var mapFn = arguments[1],
  4902. thisArg = arguments[2],
  4903. Context, i, j, arr, length, code, iterator, result, getIterator, value;
  4904. arrayLike = Object(validValue(arrayLike));
  4905. if (isValue(mapFn)) callable(mapFn);
  4906. if (!this || this === Array || !isFunction(this)) {
  4907. // Result: Plain array
  4908. if (!mapFn) {
  4909. if (isArguments(arrayLike)) {
  4910. // Source: Arguments
  4911. length = arrayLike.length;
  4912. if (length !== 1) return Array.apply(null, arrayLike);
  4913. arr = new Array(1);
  4914. arr[0] = arrayLike[0];
  4915. return arr;
  4916. }
  4917. if (isArray(arrayLike)) {
  4918. // Source: Array
  4919. arr = new Array(length = arrayLike.length);
  4920. for (i = 0; i < length; ++i) arr[i] = arrayLike[i];
  4921. return arr;
  4922. }
  4923. }
  4924. arr = [];
  4925. } else {
  4926. // Result: Non plain array
  4927. Context = this;
  4928. }
  4929. if (!isArray(arrayLike)) {
  4930. if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) {
  4931. // Source: Iterator
  4932. iterator = callable(getIterator).call(arrayLike);
  4933. if (Context) arr = new Context();
  4934. result = iterator.next();
  4935. i = 0;
  4936. while (!result.done) {
  4937. value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result
  4938. .value;
  4939. if (Context) {
  4940. desc.value = value;
  4941. defineProperty(arr, i, desc);
  4942. } else {
  4943. arr[i] = value;
  4944. }
  4945. result = iterator.next();
  4946. ++i;
  4947. }
  4948. length = i;
  4949. } else if (isString(arrayLike)) {
  4950. // Source: String
  4951. length = arrayLike.length;
  4952. if (Context) arr = new Context();
  4953. for (i = 0, j = 0; i < length; ++i) {
  4954. value = arrayLike[i];
  4955. if (i + 1 < length) {
  4956. code = value.charCodeAt(0);
  4957. // eslint-disable-next-line max-depth
  4958. if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i];
  4959. }
  4960. value = mapFn ? call.call(mapFn, thisArg, value, j) : value;
  4961. if (Context) {
  4962. desc.value = value;
  4963. defineProperty(arr, j, desc);
  4964. } else {
  4965. arr[j] = value;
  4966. }
  4967. ++j;
  4968. }
  4969. length = j;
  4970. }
  4971. }
  4972. if (length === undefined) {
  4973. // Source: array or array-like
  4974. length = toPosInt(arrayLike.length);
  4975. if (Context) arr = new Context(length);
  4976. for (i = 0; i < length; ++i) {
  4977. value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[
  4978. i];
  4979. if (Context) {
  4980. desc.value = value;
  4981. defineProperty(arr, i, desc);
  4982. } else {
  4983. arr[i] = value;
  4984. }
  4985. }
  4986. }
  4987. if (Context) {
  4988. desc.value = null;
  4989. arr.length = length;
  4990. }
  4991. return arr;
  4992. };
  4993. }, {
  4994. "../../function/is-arguments": 24,
  4995. "../../function/is-function": 25,
  4996. "../../number/to-pos-integer": 34,
  4997. "../../object/is-value": 44,
  4998. "../../object/valid-callable": 54,
  4999. "../../object/valid-value": 55,
  5000. "../../string/is-string": 59,
  5001. "es6-symbol": 73
  5002. }],
  5003. 24: [function(require, module, exports) {
  5004. "use strict";
  5005. var objToString = Object.prototype.toString,
  5006. id = objToString.call(
  5007. (function() {
  5008. return arguments;
  5009. })()
  5010. );
  5011. module.exports = function(value) {
  5012. return objToString.call(value) === id;
  5013. };
  5014. }, {}],
  5015. 25: [function(require, module, exports) {
  5016. "use strict";
  5017. var objToString = Object.prototype.toString,
  5018. id = objToString.call(require("./noop"));
  5019. module.exports = function(value) {
  5020. return typeof value === "function" && objToString.call(value) === id;
  5021. };
  5022. }, {
  5023. "./noop": 26
  5024. }],
  5025. 26: [function(require, module, exports) {
  5026. "use strict";
  5027. // eslint-disable-next-line no-empty-function
  5028. module.exports = function() {};
  5029. }, {}],
  5030. 27: [function(require, module, exports) {
  5031. "use strict";
  5032. module.exports = require("./is-implemented")() ?
  5033. Math.sign :
  5034. require("./shim");
  5035. }, {
  5036. "./is-implemented": 28,
  5037. "./shim": 29
  5038. }],
  5039. 28: [function(require, module, exports) {
  5040. "use strict";
  5041. module.exports = function() {
  5042. var sign = Math.sign;
  5043. if (typeof sign !== "function") return false;
  5044. return (sign(10) === 1) && (sign(-20) === -1);
  5045. };
  5046. }, {}],
  5047. 29: [function(require, module, exports) {
  5048. "use strict";
  5049. module.exports = function(value) {
  5050. value = Number(value);
  5051. if (isNaN(value) || (value === 0)) return value;
  5052. return value > 0 ? 1 : -1;
  5053. };
  5054. }, {}],
  5055. 30: [function(require, module, exports) {
  5056. "use strict";
  5057. module.exports = require("./is-implemented")() ?
  5058. Number.isNaN :
  5059. require("./shim");
  5060. }, {
  5061. "./is-implemented": 31,
  5062. "./shim": 32
  5063. }],
  5064. 31: [function(require, module, exports) {
  5065. "use strict";
  5066. module.exports = function() {
  5067. var numberIsNaN = Number.isNaN;
  5068. if (typeof numberIsNaN !== "function") return false;
  5069. return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34);
  5070. };
  5071. }, {}],
  5072. 32: [function(require, module, exports) {
  5073. "use strict";
  5074. module.exports = function(value) {
  5075. // eslint-disable-next-line no-self-compare
  5076. return value !== value;
  5077. };
  5078. }, {}],
  5079. 33: [function(require, module, exports) {
  5080. "use strict";
  5081. var sign = require("../math/sign")
  5082. ,
  5083. abs = Math.abs,
  5084. floor = Math.floor;
  5085. module.exports = function(value) {
  5086. if (isNaN(value)) return 0;
  5087. value = Number(value);
  5088. if ((value === 0) || !isFinite(value)) return value;
  5089. return sign(value) * floor(abs(value));
  5090. };
  5091. }, {
  5092. "../math/sign": 27
  5093. }],
  5094. 34: [function(require, module, exports) {
  5095. "use strict";
  5096. var toInteger = require("./to-integer")
  5097. ,
  5098. max = Math.max;
  5099. module.exports = function(value) {
  5100. return max(0, toInteger(value));
  5101. };
  5102. }, {
  5103. "./to-integer": 33
  5104. }],
  5105. 35: [function(require, module, exports) {
  5106. // Internal method, used by iteration functions.
  5107. // Calls a function for each key-value pair found in object
  5108. // Optionally takes compareFn to iterate object in specific order
  5109. "use strict";
  5110. var callable = require("./valid-callable"),
  5111. value = require("./valid-value"),
  5112. bind = Function.prototype.bind,
  5113. call = Function.prototype.call,
  5114. keys = Object.keys,
  5115. objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable;
  5116. module.exports = function(method, defVal) {
  5117. return function(obj, cb /*, thisArg, compareFn*/ ) {
  5118. var list, thisArg = arguments[2],
  5119. compareFn = arguments[3];
  5120. obj = Object(value(obj));
  5121. callable(cb);
  5122. list = keys(obj);
  5123. if (compareFn) {
  5124. list.sort(typeof compareFn === "function" ? bind.call(compareFn,
  5125. obj) : undefined);
  5126. }
  5127. if (typeof method !== "function") method = list[method];
  5128. return call.call(method, list, function(key, index) {
  5129. if (!objPropertyIsEnumerable.call(obj, key)) return defVal;
  5130. return call.call(cb, thisArg, obj[key], key, obj, index);
  5131. });
  5132. };
  5133. };
  5134. }, {
  5135. "./valid-callable": 54,
  5136. "./valid-value": 55
  5137. }],
  5138. 36: [function(require, module, exports) {
  5139. "use strict";
  5140. module.exports = require("./is-implemented")() ?
  5141. Object.assign :
  5142. require("./shim");
  5143. }, {
  5144. "./is-implemented": 37,
  5145. "./shim": 38
  5146. }],
  5147. 37: [function(require, module, exports) {
  5148. "use strict";
  5149. module.exports = function() {
  5150. var assign = Object.assign,
  5151. obj;
  5152. if (typeof assign !== "function") return false;
  5153. obj = {
  5154. foo: "raz"
  5155. };
  5156. assign(obj, {
  5157. bar: "dwa"
  5158. }, {
  5159. trzy: "trzy"
  5160. });
  5161. return (obj.foo + obj.bar + obj.trzy) === "razdwatrzy";
  5162. };
  5163. }, {}],
  5164. 38: [function(require, module, exports) {
  5165. "use strict";
  5166. var keys = require("../keys"),
  5167. value = require("../valid-value"),
  5168. max = Math.max;
  5169. module.exports = function(dest, src /*, …srcn*/ ) {
  5170. var error, i, length = max(arguments.length, 2),
  5171. assign;
  5172. dest = Object(value(dest));
  5173. assign = function(key) {
  5174. try {
  5175. dest[key] = src[key];
  5176. } catch (e) {
  5177. if (!error) error = e;
  5178. }
  5179. };
  5180. for (i = 1; i < length; ++i) {
  5181. src = arguments[i];
  5182. keys(src).forEach(assign);
  5183. }
  5184. if (error !== undefined) throw error;
  5185. return dest;
  5186. };
  5187. }, {
  5188. "../keys": 45,
  5189. "../valid-value": 55
  5190. }],
  5191. 39: [function(require, module, exports) {
  5192. "use strict";
  5193. var aFrom = require("../array/from"),
  5194. assign = require("./assign"),
  5195. value = require("./valid-value");
  5196. module.exports = function(obj /*, propertyNames, options*/ ) {
  5197. var copy = Object(value(obj)),
  5198. propertyNames = arguments[1],
  5199. options = Object(arguments[2]);
  5200. if (copy !== obj && !propertyNames) return copy;
  5201. var result = {};
  5202. if (propertyNames) {
  5203. aFrom(propertyNames, function(propertyName) {
  5204. if (options.ensure || propertyName in obj) result[
  5205. propertyName] = obj[propertyName];
  5206. });
  5207. } else {
  5208. assign(result, obj);
  5209. }
  5210. return result;
  5211. };
  5212. }, {
  5213. "../array/from": 21,
  5214. "./assign": 36,
  5215. "./valid-value": 55
  5216. }],
  5217. 40: [function(require, module, exports) {
  5218. // Workaround for http://code.google.com/p/v8/issues/detail?id=2804
  5219. "use strict";
  5220. var create = Object.create,
  5221. shim;
  5222. if (!require("./set-prototype-of/is-implemented")()) {
  5223. shim = require("./set-prototype-of/shim");
  5224. }
  5225. module.exports = (function() {
  5226. var nullObject, polyProps, desc;
  5227. if (!shim) return create;
  5228. if (shim.level !== 1) return create;
  5229. nullObject = {};
  5230. polyProps = {};
  5231. desc = {
  5232. configurable: false,
  5233. enumerable: false,
  5234. writable: true,
  5235. value: undefined
  5236. };
  5237. Object.getOwnPropertyNames(Object.prototype).forEach(function(name) {
  5238. if (name === "__proto__") {
  5239. polyProps[name] = {
  5240. configurable: true,
  5241. enumerable: false,
  5242. writable: true,
  5243. value: undefined
  5244. };
  5245. return;
  5246. }
  5247. polyProps[name] = desc;
  5248. });
  5249. Object.defineProperties(nullObject, polyProps);
  5250. Object.defineProperty(shim, "nullPolyfill", {
  5251. configurable: false,
  5252. enumerable: false,
  5253. writable: false,
  5254. value: nullObject
  5255. });
  5256. return function(prototype, props) {
  5257. return create(prototype === null ? nullObject : prototype, props);
  5258. };
  5259. }());
  5260. }, {
  5261. "./set-prototype-of/is-implemented": 52,
  5262. "./set-prototype-of/shim": 53
  5263. }],
  5264. 41: [function(require, module, exports) {
  5265. "use strict";
  5266. module.exports = require("./_iterate")("forEach");
  5267. }, {
  5268. "./_iterate": 35
  5269. }],
  5270. 42: [function(require, module, exports) {
  5271. // Deprecated
  5272. "use strict";
  5273. module.exports = function(obj) {
  5274. return typeof obj === "function";
  5275. };
  5276. }, {}],
  5277. 43: [function(require, module, exports) {
  5278. "use strict";
  5279. var isValue = require("./is-value");
  5280. var map = {
  5281. function: true,
  5282. object: true
  5283. };
  5284. module.exports = function(value) {
  5285. return (isValue(value) && map[typeof value]) || false;
  5286. };
  5287. }, {
  5288. "./is-value": 44
  5289. }],
  5290. 44: [function(require, module, exports) {
  5291. "use strict";
  5292. var _undefined = require("../function/noop")(); // Support ES3 engines
  5293. module.exports = function(val) {
  5294. return (val !== _undefined) && (val !== null);
  5295. };
  5296. }, {
  5297. "../function/noop": 26
  5298. }],
  5299. 45: [function(require, module, exports) {
  5300. "use strict";
  5301. module.exports = require("./is-implemented")() ? Object.keys : require("./shim");
  5302. }, {
  5303. "./is-implemented": 46,
  5304. "./shim": 47
  5305. }],
  5306. 46: [function(require, module, exports) {
  5307. "use strict";
  5308. module.exports = function() {
  5309. try {
  5310. Object.keys("primitive");
  5311. return true;
  5312. } catch (e) {
  5313. return false;
  5314. }
  5315. };
  5316. }, {}],
  5317. 47: [function(require, module, exports) {
  5318. "use strict";
  5319. var isValue = require("../is-value");
  5320. var keys = Object.keys;
  5321. module.exports = function(object) {
  5322. return keys(isValue(object) ? Object(object) : object);
  5323. };
  5324. }, {
  5325. "../is-value": 44
  5326. }],
  5327. 48: [function(require, module, exports) {
  5328. "use strict";
  5329. var callable = require("./valid-callable"),
  5330. forEach = require("./for-each"),
  5331. call = Function.prototype.call;
  5332. module.exports = function(obj, cb /*, thisArg*/ ) {
  5333. var result = {},
  5334. thisArg = arguments[2];
  5335. callable(cb);
  5336. forEach(obj, function(value, key, targetObj, index) {
  5337. result[key] = call.call(cb, thisArg, value, key, targetObj, index);
  5338. });
  5339. return result;
  5340. };
  5341. }, {
  5342. "./for-each": 41,
  5343. "./valid-callable": 54
  5344. }],
  5345. 49: [function(require, module, exports) {
  5346. "use strict";
  5347. var isValue = require("./is-value");
  5348. var forEach = Array.prototype.forEach,
  5349. create = Object.create;
  5350. var process = function(src, obj) {
  5351. var key;
  5352. for (key in src) obj[key] = src[key];
  5353. };
  5354. // eslint-disable-next-line no-unused-vars
  5355. module.exports = function(opts1 /*, …options*/ ) {
  5356. var result = create(null);
  5357. forEach.call(arguments, function(options) {
  5358. if (!isValue(options)) return;
  5359. process(Object(options), result);
  5360. });
  5361. return result;
  5362. };
  5363. }, {
  5364. "./is-value": 44
  5365. }],
  5366. 50: [function(require, module, exports) {
  5367. "use strict";
  5368. var forEach = Array.prototype.forEach,
  5369. create = Object.create;
  5370. // eslint-disable-next-line no-unused-vars
  5371. module.exports = function(arg /*, …args*/ ) {
  5372. var set = create(null);
  5373. forEach.call(arguments, function(name) {
  5374. set[name] = true;
  5375. });
  5376. return set;
  5377. };
  5378. }, {}],
  5379. 51: [function(require, module, exports) {
  5380. "use strict";
  5381. module.exports = require("./is-implemented")() ?
  5382. Object.setPrototypeOf :
  5383. require("./shim");
  5384. }, {
  5385. "./is-implemented": 52,
  5386. "./shim": 53
  5387. }],
  5388. 52: [function(require, module, exports) {
  5389. "use strict";
  5390. var create = Object.create,
  5391. getPrototypeOf = Object.getPrototypeOf,
  5392. plainObject = {};
  5393. module.exports = function( /* CustomCreate*/ ) {
  5394. var setPrototypeOf = Object.setPrototypeOf,
  5395. customCreate = arguments[0] || create;
  5396. if (typeof setPrototypeOf !== "function") return false;
  5397. return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) ===
  5398. plainObject;
  5399. };
  5400. }, {}],
  5401. 53: [function(require, module, exports) {
  5402. /* eslint no-proto: "off" */
  5403. // Big thanks to @WebReflection for sorting this out
  5404. // https://gist.github.com/WebReflection/5593554
  5405. "use strict";
  5406. var isObject = require("../is-object"),
  5407. value = require("../valid-value"),
  5408. objIsPrototypeOf = Object.prototype.isPrototypeOf,
  5409. defineProperty = Object.defineProperty,
  5410. nullDesc = {
  5411. configurable: true,
  5412. enumerable: false,
  5413. writable: true,
  5414. value: undefined
  5415. },
  5416. validate;
  5417. validate = function(obj, prototype) {
  5418. value(obj);
  5419. if (prototype === null || isObject(prototype)) return obj;
  5420. throw new TypeError("Prototype must be null or an object");
  5421. };
  5422. module.exports = (function(status) {
  5423. var fn, set;
  5424. if (!status) return null;
  5425. if (status.level === 2) {
  5426. if (status.set) {
  5427. set = status.set;
  5428. fn = function(obj, prototype) {
  5429. set.call(validate(obj, prototype), prototype);
  5430. return obj;
  5431. };
  5432. } else {
  5433. fn = function(obj, prototype) {
  5434. validate(obj, prototype).__proto__ = prototype;
  5435. return obj;
  5436. };
  5437. }
  5438. } else {
  5439. fn = function self(obj, prototype) {
  5440. var isNullBase;
  5441. validate(obj, prototype);
  5442. isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj);
  5443. if (isNullBase) delete self.nullPolyfill.__proto__;
  5444. if (prototype === null) prototype = self.nullPolyfill;
  5445. obj.__proto__ = prototype;
  5446. if (isNullBase) defineProperty(self.nullPolyfill, "__proto__",
  5447. nullDesc);
  5448. return obj;
  5449. };
  5450. }
  5451. return Object.defineProperty(fn, "level", {
  5452. configurable: false,
  5453. enumerable: false,
  5454. writable: false,
  5455. value: status.level
  5456. });
  5457. }(
  5458. (function() {
  5459. var tmpObj1 = Object.create(null),
  5460. tmpObj2 = {},
  5461. set, desc = Object.getOwnPropertyDescriptor(Object.prototype,
  5462. "__proto__");
  5463. if (desc) {
  5464. try {
  5465. set = desc.set; // Opera crashes at this point
  5466. set.call(tmpObj1, tmpObj2);
  5467. } catch (ignore) {}
  5468. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return {
  5469. set: set,
  5470. level: 2
  5471. };
  5472. }
  5473. tmpObj1.__proto__ = tmpObj2;
  5474. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return {
  5475. level: 2
  5476. };
  5477. tmpObj1 = {};
  5478. tmpObj1.__proto__ = tmpObj2;
  5479. if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return {
  5480. level: 1
  5481. };
  5482. return false;
  5483. })()
  5484. ));
  5485. require("../create");
  5486. }, {
  5487. "../create": 40,
  5488. "../is-object": 43,
  5489. "../valid-value": 55
  5490. }],
  5491. 54: [function(require, module, exports) {
  5492. "use strict";
  5493. module.exports = function(fn) {
  5494. if (typeof fn !== "function") throw new TypeError(fn + " is not a function");
  5495. return fn;
  5496. };
  5497. }, {}],
  5498. 55: [function(require, module, exports) {
  5499. "use strict";
  5500. var isValue = require("./is-value");
  5501. module.exports = function(value) {
  5502. if (!isValue(value)) throw new TypeError("Cannot use null or undefined");
  5503. return value;
  5504. };
  5505. }, {
  5506. "./is-value": 44
  5507. }],
  5508. 56: [function(require, module, exports) {
  5509. "use strict";
  5510. module.exports = require("./is-implemented")() ?
  5511. String.prototype.contains :
  5512. require("./shim");
  5513. }, {
  5514. "./is-implemented": 57,
  5515. "./shim": 58
  5516. }],
  5517. 57: [function(require, module, exports) {
  5518. "use strict";
  5519. var str = "razdwatrzy";
  5520. module.exports = function() {
  5521. if (typeof str.contains !== "function") return false;
  5522. return (str.contains("dwa") === true) && (str.contains("foo") === false);
  5523. };
  5524. }, {}],
  5525. 58: [function(require, module, exports) {
  5526. "use strict";
  5527. var indexOf = String.prototype.indexOf;
  5528. module.exports = function(searchString /*, position*/ ) {
  5529. return indexOf.call(this, searchString, arguments[1]) > -1;
  5530. };
  5531. }, {}],
  5532. 59: [function(require, module, exports) {
  5533. "use strict";
  5534. var objToString = Object.prototype.toString,
  5535. id = objToString.call("");
  5536. module.exports = function(value) {
  5537. return (
  5538. typeof value === "string" ||
  5539. (value &&
  5540. typeof value === "object" &&
  5541. (value instanceof String || objToString.call(value) === id)) ||
  5542. false
  5543. );
  5544. };
  5545. }, {}],
  5546. 60: [function(require, module, exports) {
  5547. "use strict";
  5548. var setPrototypeOf = require("es5-ext/object/set-prototype-of"),
  5549. contains = require("es5-ext/string/#/contains"),
  5550. d = require("d"),
  5551. Symbol = require("es6-symbol"),
  5552. Iterator = require("./");
  5553. var defineProperty = Object.defineProperty,
  5554. ArrayIterator;
  5555. ArrayIterator = module.exports = function(arr, kind) {
  5556. if (!(this instanceof ArrayIterator)) throw new TypeError(
  5557. "Constructor requires 'new'");
  5558. Iterator.call(this, arr);
  5559. if (!kind) kind = "value";
  5560. else if (contains.call(kind, "key+value")) kind = "key+value";
  5561. else if (contains.call(kind, "key")) kind = "key";
  5562. else kind = "value";
  5563. defineProperty(this, "__kind__", d("", kind));
  5564. };
  5565. if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator);
  5566. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  5567. delete ArrayIterator.prototype.constructor;
  5568. ArrayIterator.prototype = Object.create(Iterator.prototype, {
  5569. _resolve: d(function(i) {
  5570. if (this.__kind__ === "value") return this.__list__[i];
  5571. if (this.__kind__ === "key+value") return [i, this.__list__[i]];
  5572. return i;
  5573. })
  5574. });
  5575. defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator"));
  5576. }, {
  5577. "./": 63,
  5578. "d": 16,
  5579. "es5-ext/object/set-prototype-of": 51,
  5580. "es5-ext/string/#/contains": 56,
  5581. "es6-symbol": 73
  5582. }],
  5583. 61: [function(require, module, exports) {
  5584. "use strict";
  5585. var isArguments = require("es5-ext/function/is-arguments"),
  5586. callable = require("es5-ext/object/valid-callable"),
  5587. isString = require("es5-ext/string/is-string"),
  5588. get = require("./get");
  5589. var isArray = Array.isArray,
  5590. call = Function.prototype.call,
  5591. some = Array.prototype.some;
  5592. module.exports = function(iterable, cb /*, thisArg*/ ) {
  5593. var mode, thisArg = arguments[2],
  5594. result, doBreak, broken, i, length, char, code;
  5595. if (isArray(iterable) || isArguments(iterable)) mode = "array";
  5596. else if (isString(iterable)) mode = "string";
  5597. else iterable = get(iterable);
  5598. callable(cb);
  5599. doBreak = function() {
  5600. broken = true;
  5601. };
  5602. if (mode === "array") {
  5603. some.call(iterable, function(value) {
  5604. call.call(cb, thisArg, value, doBreak);
  5605. return broken;
  5606. });
  5607. return;
  5608. }
  5609. if (mode === "string") {
  5610. length = iterable.length;
  5611. for (i = 0; i < length; ++i) {
  5612. char = iterable[i];
  5613. if (i + 1 < length) {
  5614. code = char.charCodeAt(0);
  5615. if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i];
  5616. }
  5617. call.call(cb, thisArg, char, doBreak);
  5618. if (broken) break;
  5619. }
  5620. return;
  5621. }
  5622. result = iterable.next();
  5623. while (!result.done) {
  5624. call.call(cb, thisArg, result.value, doBreak);
  5625. if (broken) return;
  5626. result = iterable.next();
  5627. }
  5628. };
  5629. }, {
  5630. "./get": 62,
  5631. "es5-ext/function/is-arguments": 24,
  5632. "es5-ext/object/valid-callable": 54,
  5633. "es5-ext/string/is-string": 59
  5634. }],
  5635. 62: [function(require, module, exports) {
  5636. "use strict";
  5637. var isArguments = require("es5-ext/function/is-arguments"),
  5638. isString = require("es5-ext/string/is-string"),
  5639. ArrayIterator = require("./array"),
  5640. StringIterator = require("./string"),
  5641. iterable = require("./valid-iterable"),
  5642. iteratorSymbol = require("es6-symbol").iterator;
  5643. module.exports = function(obj) {
  5644. if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[
  5645. iteratorSymbol]();
  5646. if (isArguments(obj)) return new ArrayIterator(obj);
  5647. if (isString(obj)) return new StringIterator(obj);
  5648. return new ArrayIterator(obj);
  5649. };
  5650. }, {
  5651. "./array": 60,
  5652. "./string": 65,
  5653. "./valid-iterable": 66,
  5654. "es5-ext/function/is-arguments": 24,
  5655. "es5-ext/string/is-string": 59,
  5656. "es6-symbol": 73
  5657. }],
  5658. 63: [function(require, module, exports) {
  5659. "use strict";
  5660. var clear = require("es5-ext/array/#/clear"),
  5661. assign = require("es5-ext/object/assign"),
  5662. callable = require("es5-ext/object/valid-callable"),
  5663. value = require("es5-ext/object/valid-value"),
  5664. d = require("d"),
  5665. autoBind = require("d/auto-bind"),
  5666. Symbol = require("es6-symbol");
  5667. var defineProperty = Object.defineProperty,
  5668. defineProperties = Object.defineProperties,
  5669. Iterator;
  5670. module.exports = Iterator = function(list, context) {
  5671. if (!(this instanceof Iterator)) throw new TypeError(
  5672. "Constructor requires 'new'");
  5673. defineProperties(this, {
  5674. __list__: d("w", value(list)),
  5675. __context__: d("w", context),
  5676. __nextIndex__: d("w", 0)
  5677. });
  5678. if (!context) return;
  5679. callable(context.on);
  5680. context.on("_add", this._onAdd);
  5681. context.on("_delete", this._onDelete);
  5682. context.on("_clear", this._onClear);
  5683. };
  5684. // Internal %IteratorPrototype% doesn't expose its constructor
  5685. delete Iterator.prototype.constructor;
  5686. defineProperties(
  5687. Iterator.prototype,
  5688. assign({
  5689. _next: d(function() {
  5690. var i;
  5691. if (!this.__list__) return undefined;
  5692. if (this.__redo__) {
  5693. i = this.__redo__.shift();
  5694. if (i !== undefined) return i;
  5695. }
  5696. if (this.__nextIndex__ < this.__list__.length) return this
  5697. .__nextIndex__++;
  5698. this._unBind();
  5699. return undefined;
  5700. }),
  5701. next: d(function() {
  5702. return this._createResult(this._next());
  5703. }),
  5704. _createResult: d(function(i) {
  5705. if (i === undefined) return {
  5706. done: true,
  5707. value: undefined
  5708. };
  5709. return {
  5710. done: false,
  5711. value: this._resolve(i)
  5712. };
  5713. }),
  5714. _resolve: d(function(i) {
  5715. return this.__list__[i];
  5716. }),
  5717. _unBind: d(function() {
  5718. this.__list__ = null;
  5719. delete this.__redo__;
  5720. if (!this.__context__) return;
  5721. this.__context__.off("_add", this._onAdd);
  5722. this.__context__.off("_delete", this._onDelete);
  5723. this.__context__.off("_clear", this._onClear);
  5724. this.__context__ = null;
  5725. }),
  5726. toString: d(function() {
  5727. return "[object " + (this[Symbol.toStringTag] || "Object") +
  5728. "]";
  5729. })
  5730. },
  5731. autoBind({
  5732. _onAdd: d(function(index) {
  5733. if (index >= this.__nextIndex__) return;
  5734. ++this.__nextIndex__;
  5735. if (!this.__redo__) {
  5736. defineProperty(this, "__redo__", d("c", [index]));
  5737. return;
  5738. }
  5739. this.__redo__.forEach(function(redo, i) {
  5740. if (redo >= index) this.__redo__[i] = ++
  5741. redo;
  5742. }, this);
  5743. this.__redo__.push(index);
  5744. }),
  5745. _onDelete: d(function(index) {
  5746. var i;
  5747. if (index >= this.__nextIndex__) return;
  5748. --this.__nextIndex__;
  5749. if (!this.__redo__) return;
  5750. i = this.__redo__.indexOf(index);
  5751. if (i !== -1) this.__redo__.splice(i, 1);
  5752. this.__redo__.forEach(function(redo, j) {
  5753. if (redo > index) this.__redo__[j] = --redo;
  5754. }, this);
  5755. }),
  5756. _onClear: d(function() {
  5757. if (this.__redo__) clear.call(this.__redo__);
  5758. this.__nextIndex__ = 0;
  5759. })
  5760. })
  5761. )
  5762. );
  5763. defineProperty(
  5764. Iterator.prototype,
  5765. Symbol.iterator,
  5766. d(function() {
  5767. return this;
  5768. })
  5769. );
  5770. }, {
  5771. "d": 16,
  5772. "d/auto-bind": 15,
  5773. "es5-ext/array/#/clear": 19,
  5774. "es5-ext/object/assign": 36,
  5775. "es5-ext/object/valid-callable": 54,
  5776. "es5-ext/object/valid-value": 55,
  5777. "es6-symbol": 73
  5778. }],
  5779. 64: [function(require, module, exports) {
  5780. "use strict";
  5781. var isArguments = require("es5-ext/function/is-arguments"),
  5782. isValue = require("es5-ext/object/is-value"),
  5783. isString = require("es5-ext/string/is-string");
  5784. var iteratorSymbol = require("es6-symbol").iterator,
  5785. isArray = Array.isArray;
  5786. module.exports = function(value) {
  5787. if (!isValue(value)) return false;
  5788. if (isArray(value)) return true;
  5789. if (isString(value)) return true;
  5790. if (isArguments(value)) return true;
  5791. return typeof value[iteratorSymbol] === "function";
  5792. };
  5793. }, {
  5794. "es5-ext/function/is-arguments": 24,
  5795. "es5-ext/object/is-value": 44,
  5796. "es5-ext/string/is-string": 59,
  5797. "es6-symbol": 73
  5798. }],
  5799. 65: [function(require, module, exports) {
  5800. // Thanks @mathiasbynens
  5801. // http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols
  5802. "use strict";
  5803. var setPrototypeOf = require("es5-ext/object/set-prototype-of"),
  5804. d = require("d"),
  5805. Symbol = require("es6-symbol"),
  5806. Iterator = require("./");
  5807. var defineProperty = Object.defineProperty,
  5808. StringIterator;
  5809. StringIterator = module.exports = function(str) {
  5810. if (!(this instanceof StringIterator)) throw new TypeError(
  5811. "Constructor requires 'new'");
  5812. str = String(str);
  5813. Iterator.call(this, str);
  5814. defineProperty(this, "__length__", d("", str.length));
  5815. };
  5816. if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator);
  5817. // Internal %ArrayIteratorPrototype% doesn't expose its constructor
  5818. delete StringIterator.prototype.constructor;
  5819. StringIterator.prototype = Object.create(Iterator.prototype, {
  5820. _next: d(function() {
  5821. if (!this.__list__) return undefined;
  5822. if (this.__nextIndex__ < this.__length__) return this
  5823. .__nextIndex__++;
  5824. this._unBind();
  5825. return undefined;
  5826. }),
  5827. _resolve: d(function(i) {
  5828. var char = this.__list__[i],
  5829. code;
  5830. if (this.__nextIndex__ === this.__length__) return char;
  5831. code = char.charCodeAt(0);
  5832. if (code >= 0xd800 && code <= 0xdbff) return char + this
  5833. .__list__[this.__nextIndex__++];
  5834. return char;
  5835. })
  5836. });
  5837. defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator"));
  5838. }, {
  5839. "./": 63,
  5840. "d": 16,
  5841. "es5-ext/object/set-prototype-of": 51,
  5842. "es6-symbol": 73
  5843. }],
  5844. 66: [function(require, module, exports) {
  5845. "use strict";
  5846. var isIterable = require("./is-iterable");
  5847. module.exports = function(value) {
  5848. if (!isIterable(value)) throw new TypeError(value + " is not iterable");
  5849. return value;
  5850. };
  5851. }, {
  5852. "./is-iterable": 64
  5853. }],
  5854. 67: [function(require, module, exports) {
  5855. 'use strict';
  5856. module.exports = require('./is-implemented')() ? Map : require('./polyfill');
  5857. }, {
  5858. "./is-implemented": 68,
  5859. "./polyfill": 72
  5860. }],
  5861. 68: [function(require, module, exports) {
  5862. 'use strict';
  5863. module.exports = function() {
  5864. var map, iterator, result;
  5865. if (typeof Map !== 'function') return false;
  5866. try {
  5867. // WebKit doesn't support arguments and crashes
  5868. map = new Map([
  5869. ['raz', 'one'],
  5870. ['dwa', 'two'],
  5871. ['trzy', 'three']
  5872. ]);
  5873. } catch (e) {
  5874. return false;
  5875. }
  5876. if (String(map) !== '[object Map]') return false;
  5877. if (map.size !== 3) return false;
  5878. if (typeof map.clear !== 'function') return false;
  5879. if (typeof map.delete !== 'function') return false;
  5880. if (typeof map.entries !== 'function') return false;
  5881. if (typeof map.forEach !== 'function') return false;
  5882. if (typeof map.get !== 'function') return false;
  5883. if (typeof map.has !== 'function') return false;
  5884. if (typeof map.keys !== 'function') return false;
  5885. if (typeof map.set !== 'function') return false;
  5886. if (typeof map.values !== 'function') return false;
  5887. iterator = map.entries();
  5888. result = iterator.next();
  5889. if (result.done !== false) return false;
  5890. if (!result.value) return false;
  5891. if (result.value[0] !== 'raz') return false;
  5892. if (result.value[1] !== 'one') return false;
  5893. return true;
  5894. };
  5895. }, {}],
  5896. 69: [function(require, module, exports) {
  5897. // Exports true if environment provides native `Map` implementation,
  5898. // whatever that is.
  5899. 'use strict';
  5900. module.exports = (function() {
  5901. if (typeof Map === 'undefined') return false;
  5902. return (Object.prototype.toString.call(new Map()) === '[object Map]');
  5903. }());
  5904. }, {}],
  5905. 70: [function(require, module, exports) {
  5906. 'use strict';
  5907. module.exports = require('es5-ext/object/primitive-set')('key',
  5908. 'value', 'key+value');
  5909. }, {
  5910. "es5-ext/object/primitive-set": 50
  5911. }],
  5912. 71: [function(require, module, exports) {
  5913. 'use strict';
  5914. var setPrototypeOf = require('es5-ext/object/set-prototype-of'),
  5915. d = require('d'),
  5916. Iterator = require('es6-iterator'),
  5917. toStringTagSymbol = require('es6-symbol').toStringTag,
  5918. kinds = require('./iterator-kinds')
  5919. ,
  5920. defineProperties = Object.defineProperties,
  5921. unBind = Iterator.prototype._unBind,
  5922. MapIterator;
  5923. MapIterator = module.exports = function(map, kind) {
  5924. if (!(this instanceof MapIterator)) return new MapIterator(map, kind);
  5925. Iterator.call(this, map.__mapKeysData__, map);
  5926. if (!kind || !kinds[kind]) kind = 'key+value';
  5927. defineProperties(this, {
  5928. __kind__: d('', kind),
  5929. __values__: d('w', map.__mapValuesData__)
  5930. });
  5931. };
  5932. if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator);
  5933. MapIterator.prototype = Object.create(Iterator.prototype, {
  5934. constructor: d(MapIterator),
  5935. _resolve: d(function(i) {
  5936. if (this.__kind__ === 'value') return this.__values__[i];
  5937. if (this.__kind__ === 'key') return this.__list__[i];
  5938. return [this.__list__[i], this.__values__[i]];
  5939. }),
  5940. _unBind: d(function() {
  5941. this.__values__ = null;
  5942. unBind.call(this);
  5943. }),
  5944. toString: d(function() {
  5945. return '[object Map Iterator]';
  5946. })
  5947. });
  5948. Object.defineProperty(MapIterator.prototype, toStringTagSymbol,
  5949. d('c', 'Map Iterator'));
  5950. }, {
  5951. "./iterator-kinds": 70,
  5952. "d": 16,
  5953. "es5-ext/object/set-prototype-of": 51,
  5954. "es6-iterator": 63,
  5955. "es6-symbol": 73
  5956. }],
  5957. 72: [function(require, module, exports) {
  5958. 'use strict';
  5959. var clear = require('es5-ext/array/#/clear'),
  5960. eIndexOf = require('es5-ext/array/#/e-index-of'),
  5961. setPrototypeOf = require('es5-ext/object/set-prototype-of'),
  5962. callable = require('es5-ext/object/valid-callable'),
  5963. validValue = require('es5-ext/object/valid-value'),
  5964. d = require('d'),
  5965. ee = require('event-emitter'),
  5966. Symbol = require('es6-symbol'),
  5967. iterator = require('es6-iterator/valid-iterable'),
  5968. forOf = require('es6-iterator/for-of'),
  5969. Iterator = require('./lib/iterator'),
  5970. isNative = require('./is-native-implemented')
  5971. ,
  5972. call = Function.prototype.call,
  5973. defineProperties = Object.defineProperties,
  5974. getPrototypeOf = Object.getPrototypeOf,
  5975. MapPoly;
  5976. module.exports = MapPoly = function( /*iterable*/ ) {
  5977. var iterable = arguments[0],
  5978. keys, values, self;
  5979. if (!(this instanceof MapPoly)) throw new TypeError(
  5980. 'Constructor requires \'new\'');
  5981. if (isNative && setPrototypeOf && (Map !== MapPoly)) {
  5982. self = setPrototypeOf(new Map(), getPrototypeOf(this));
  5983. } else {
  5984. self = this;
  5985. }
  5986. if (iterable != null) iterator(iterable);
  5987. defineProperties(self, {
  5988. __mapKeysData__: d('c', keys = []),
  5989. __mapValuesData__: d('c', values = [])
  5990. });
  5991. if (!iterable) return self;
  5992. forOf(iterable, function(value) {
  5993. var key = validValue(value)[0];
  5994. value = value[1];
  5995. if (eIndexOf.call(keys, key) !== -1) return;
  5996. keys.push(key);
  5997. values.push(value);
  5998. }, self);
  5999. return self;
  6000. };
  6001. if (isNative) {
  6002. if (setPrototypeOf) setPrototypeOf(MapPoly, Map);
  6003. MapPoly.prototype = Object.create(Map.prototype, {
  6004. constructor: d(MapPoly)
  6005. });
  6006. }
  6007. ee(defineProperties(MapPoly.prototype, {
  6008. clear: d(function() {
  6009. if (!this.__mapKeysData__.length) return;
  6010. clear.call(this.__mapKeysData__);
  6011. clear.call(this.__mapValuesData__);
  6012. this.emit('_clear');
  6013. }),
  6014. delete: d(function(key) {
  6015. var index = eIndexOf.call(this.__mapKeysData__, key);
  6016. if (index === -1) return false;
  6017. this.__mapKeysData__.splice(index, 1);
  6018. this.__mapValuesData__.splice(index, 1);
  6019. this.emit('_delete', index, key);
  6020. return true;
  6021. }),
  6022. entries: d(function() {
  6023. return new Iterator(this, 'key+value');
  6024. }),
  6025. forEach: d(function(cb /*, thisArg*/ ) {
  6026. var thisArg = arguments[1],
  6027. iterator, result;
  6028. callable(cb);
  6029. iterator = this.entries();
  6030. result = iterator._next();
  6031. while (result !== undefined) {
  6032. call.call(cb, thisArg, this.__mapValuesData__[result],
  6033. this.__mapKeysData__[result], this);
  6034. result = iterator._next();
  6035. }
  6036. }),
  6037. get: d(function(key) {
  6038. var index = eIndexOf.call(this.__mapKeysData__, key);
  6039. if (index === -1) return;
  6040. return this.__mapValuesData__[index];
  6041. }),
  6042. has: d(function(key) {
  6043. return (eIndexOf.call(this.__mapKeysData__, key) !== -1);
  6044. }),
  6045. keys: d(function() {
  6046. return new Iterator(this, 'key');
  6047. }),
  6048. set: d(function(key, value) {
  6049. var index = eIndexOf.call(this.__mapKeysData__, key),
  6050. emit;
  6051. if (index === -1) {
  6052. index = this.__mapKeysData__.push(key) - 1;
  6053. emit = true;
  6054. }
  6055. this.__mapValuesData__[index] = value;
  6056. if (emit) this.emit('_add', index, key);
  6057. return this;
  6058. }),
  6059. size: d.gs(function() {
  6060. return this.__mapKeysData__.length;
  6061. }),
  6062. values: d(function() {
  6063. return new Iterator(this, 'value');
  6064. }),
  6065. toString: d(function() {
  6066. return '[object Map]';
  6067. })
  6068. }));
  6069. Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function() {
  6070. return this.entries();
  6071. }));
  6072. Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map'));
  6073. }, {
  6074. "./is-native-implemented": 69,
  6075. "./lib/iterator": 71,
  6076. "d": 16,
  6077. "es5-ext/array/#/clear": 19,
  6078. "es5-ext/array/#/e-index-of": 20,
  6079. "es5-ext/object/set-prototype-of": 51,
  6080. "es5-ext/object/valid-callable": 54,
  6081. "es5-ext/object/valid-value": 55,
  6082. "es6-iterator/for-of": 61,
  6083. "es6-iterator/valid-iterable": 66,
  6084. "es6-symbol": 73,
  6085. "event-emitter": 78
  6086. }],
  6087. 73: [function(require, module, exports) {
  6088. 'use strict';
  6089. module.exports = require('./is-implemented')() ? Symbol : require('./polyfill');
  6090. }, {
  6091. "./is-implemented": 74,
  6092. "./polyfill": 76
  6093. }],
  6094. 74: [function(require, module, exports) {
  6095. 'use strict';
  6096. var validTypes = {
  6097. object: true,
  6098. symbol: true
  6099. };
  6100. module.exports = function() {
  6101. var symbol;
  6102. if (typeof Symbol !== 'function') return false;
  6103. symbol = Symbol('test symbol');
  6104. try {
  6105. String(symbol);
  6106. } catch (e) {
  6107. return false;
  6108. }
  6109. // Return 'true' also for polyfills
  6110. if (!validTypes[typeof Symbol.iterator]) return false;
  6111. if (!validTypes[typeof Symbol.toPrimitive]) return false;
  6112. if (!validTypes[typeof Symbol.toStringTag]) return false;
  6113. return true;
  6114. };
  6115. }, {}],
  6116. 75: [function(require, module, exports) {
  6117. 'use strict';
  6118. module.exports = function(x) {
  6119. if (!x) return false;
  6120. if (typeof x === 'symbol') return true;
  6121. if (!x.constructor) return false;
  6122. if (x.constructor.name !== 'Symbol') return false;
  6123. return (x[x.constructor.toStringTag] === 'Symbol');
  6124. };
  6125. }, {}],
  6126. 76: [function(require, module, exports) {
  6127. // ES2015 Symbol polyfill for environments that do not (or partially) support it
  6128. 'use strict';
  6129. var d = require('d'),
  6130. validateSymbol = require('./validate-symbol')
  6131. ,
  6132. create = Object.create,
  6133. defineProperties = Object.defineProperties,
  6134. defineProperty = Object.defineProperty,
  6135. objPrototype = Object.prototype,
  6136. NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = create(null),
  6137. isNativeSafe;
  6138. if (typeof Symbol === 'function') {
  6139. NativeSymbol = Symbol;
  6140. try {
  6141. String(NativeSymbol());
  6142. isNativeSafe = true;
  6143. } catch (ignore) {}
  6144. }
  6145. var generateName = (function() {
  6146. var created = create(null);
  6147. return function(desc) {
  6148. var postfix = 0,
  6149. name, ie11BugWorkaround;
  6150. while (created[desc + (postfix || '')]) ++postfix;
  6151. desc += (postfix || '');
  6152. created[desc] = true;
  6153. name = '@@' + desc;
  6154. defineProperty(objPrototype, name, d.gs(null, function(value) {
  6155. // For IE11 issue see:
  6156. // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/
  6157. // ie11-broken-getters-on-dom-objects
  6158. // https://github.com/medikoo/es6-symbol/issues/12
  6159. if (ie11BugWorkaround) return;
  6160. ie11BugWorkaround = true;
  6161. defineProperty(this, name, d(value));
  6162. ie11BugWorkaround = false;
  6163. }));
  6164. return name;
  6165. };
  6166. }());
  6167. // Internal constructor (not one exposed) for creating Symbol instances.
  6168. // This one is used to ensure that `someSymbol instanceof Symbol` always return false
  6169. HiddenSymbol = function Symbol(description) {
  6170. if (this instanceof HiddenSymbol) throw new TypeError(
  6171. 'Symbol is not a constructor');
  6172. return SymbolPolyfill(description);
  6173. };
  6174. // Exposed `Symbol` constructor
  6175. // (returns instances of HiddenSymbol)
  6176. module.exports = SymbolPolyfill = function Symbol(description) {
  6177. var symbol;
  6178. if (this instanceof Symbol) throw new TypeError('Symbol is not a constructor');
  6179. if (isNativeSafe) return NativeSymbol(description);
  6180. symbol = create(HiddenSymbol.prototype);
  6181. description = (description === undefined ? '' : String(description));
  6182. return defineProperties(symbol, {
  6183. __description__: d('', description),
  6184. __name__: d('', generateName(description))
  6185. });
  6186. };
  6187. defineProperties(SymbolPolyfill, {
  6188. for: d(function(key) {
  6189. if (globalSymbols[key]) return globalSymbols[key];
  6190. return (globalSymbols[key] = SymbolPolyfill(String(key)));
  6191. }),
  6192. keyFor: d(function(s) {
  6193. var key;
  6194. validateSymbol(s);
  6195. for (key in globalSymbols)
  6196. if (globalSymbols[key] === s) return key;
  6197. }),
  6198. // To ensure proper interoperability with other native functions (e.g. Array.from)
  6199. // fallback to eventual native implementation of given symbol
  6200. hasInstance: d('', (NativeSymbol && NativeSymbol.hasInstance) ||
  6201. SymbolPolyfill('hasInstance')),
  6202. isConcatSpreadable: d('', (NativeSymbol && NativeSymbol
  6203. .isConcatSpreadable) ||
  6204. SymbolPolyfill('isConcatSpreadable')),
  6205. iterator: d('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill(
  6206. 'iterator')),
  6207. match: d('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill(
  6208. 'match')),
  6209. replace: d('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill(
  6210. 'replace')),
  6211. search: d('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill(
  6212. 'search')),
  6213. species: d('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill(
  6214. 'species')),
  6215. split: d('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill(
  6216. 'split')),
  6217. toPrimitive: d('', (NativeSymbol && NativeSymbol.toPrimitive) ||
  6218. SymbolPolyfill('toPrimitive')),
  6219. toStringTag: d('', (NativeSymbol && NativeSymbol.toStringTag) ||
  6220. SymbolPolyfill('toStringTag')),
  6221. unscopables: d('', (NativeSymbol && NativeSymbol.unscopables) ||
  6222. SymbolPolyfill('unscopables'))
  6223. });
  6224. // Internal tweaks for real symbol producer
  6225. defineProperties(HiddenSymbol.prototype, {
  6226. constructor: d(SymbolPolyfill),
  6227. toString: d('', function() {
  6228. return this.__name__;
  6229. })
  6230. });
  6231. // Proper implementation of methods exposed on Symbol.prototype
  6232. // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype
  6233. defineProperties(SymbolPolyfill.prototype, {
  6234. toString: d(function() {
  6235. return 'Symbol (' + validateSymbol(this).__description__ + ')';
  6236. }),
  6237. valueOf: d(function() {
  6238. return validateSymbol(this);
  6239. })
  6240. });
  6241. defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('', function() {
  6242. var symbol = validateSymbol(this);
  6243. if (typeof symbol === 'symbol') return symbol;
  6244. return symbol.toString();
  6245. }));
  6246. defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol'));
  6247. // Proper implementaton of toPrimitive and toStringTag for returned symbol instances
  6248. defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag,
  6249. d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]));
  6250. // Note: It's important to define `toPrimitive` as last one, as some implementations
  6251. // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols)
  6252. // And that may invoke error in definition flow:
  6253. // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149
  6254. defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive,
  6255. d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]));
  6256. }, {
  6257. "./validate-symbol": 77,
  6258. "d": 16
  6259. }],
  6260. 77: [function(require, module, exports) {
  6261. 'use strict';
  6262. var isSymbol = require('./is-symbol');
  6263. module.exports = function(value) {
  6264. if (!isSymbol(value)) throw new TypeError(value + " is not a symbol");
  6265. return value;
  6266. };
  6267. }, {
  6268. "./is-symbol": 75
  6269. }],
  6270. 78: [function(require, module, exports) {
  6271. 'use strict';
  6272. var d = require('d'),
  6273. callable = require('es5-ext/object/valid-callable')
  6274. ,
  6275. apply = Function.prototype.apply,
  6276. call = Function.prototype.call,
  6277. create = Object.create,
  6278. defineProperty = Object.defineProperty,
  6279. defineProperties = Object.defineProperties,
  6280. hasOwnProperty = Object.prototype.hasOwnProperty,
  6281. descriptor = {
  6282. configurable: true,
  6283. enumerable: false,
  6284. writable: true
  6285. }
  6286. ,
  6287. on, once, off, emit, methods, descriptors, base;
  6288. on = function(type, listener) {
  6289. var data;
  6290. callable(listener);
  6291. if (!hasOwnProperty.call(this, '__ee__')) {
  6292. data = descriptor.value = create(null);
  6293. defineProperty(this, '__ee__', descriptor);
  6294. descriptor.value = null;
  6295. } else {
  6296. data = this.__ee__;
  6297. }
  6298. if (!data[type]) data[type] = listener;
  6299. else if (typeof data[type] === 'object') data[type].push(listener);
  6300. else data[type] = [data[type], listener];
  6301. return this;
  6302. };
  6303. once = function(type, listener) {
  6304. var once, self;
  6305. callable(listener);
  6306. self = this;
  6307. on.call(this, type, once = function() {
  6308. off.call(self, type, once);
  6309. apply.call(listener, this, arguments);
  6310. });
  6311. once.__eeOnceListener__ = listener;
  6312. return this;
  6313. };
  6314. off = function(type, listener) {
  6315. var data, listeners, candidate, i;
  6316. callable(listener);
  6317. if (!hasOwnProperty.call(this, '__ee__')) return this;
  6318. data = this.__ee__;
  6319. if (!data[type]) return this;
  6320. listeners = data[type];
  6321. if (typeof listeners === 'object') {
  6322. for (i = 0;
  6323. (candidate = listeners[i]); ++i) {
  6324. if ((candidate === listener) ||
  6325. (candidate.__eeOnceListener__ === listener)) {
  6326. if (listeners.length === 2) data[type] = listeners[i ? 0 : 1];
  6327. else listeners.splice(i, 1);
  6328. }
  6329. }
  6330. } else {
  6331. if ((listeners === listener) ||
  6332. (listeners.__eeOnceListener__ === listener)) {
  6333. delete data[type];
  6334. }
  6335. }
  6336. return this;
  6337. };
  6338. emit = function(type) {
  6339. var i, l, listener, listeners, args;
  6340. if (!hasOwnProperty.call(this, '__ee__')) return;
  6341. listeners = this.__ee__[type];
  6342. if (!listeners) return;
  6343. if (typeof listeners === 'object') {
  6344. l = arguments.length;
  6345. args = new Array(l - 1);
  6346. for (i = 1; i < l; ++i) args[i - 1] = arguments[i];
  6347. listeners = listeners.slice();
  6348. for (i = 0;
  6349. (listener = listeners[i]); ++i) {
  6350. apply.call(listener, this, args);
  6351. }
  6352. } else {
  6353. switch (arguments.length) {
  6354. case 1:
  6355. call.call(listeners, this);
  6356. break;
  6357. case 2:
  6358. call.call(listeners, this, arguments[1]);
  6359. break;
  6360. case 3:
  6361. call.call(listeners, this, arguments[1], arguments[2]);
  6362. break;
  6363. default:
  6364. l = arguments.length;
  6365. args = new Array(l - 1);
  6366. for (i = 1; i < l; ++i) {
  6367. args[i - 1] = arguments[i];
  6368. }
  6369. apply.call(listeners, this, args);
  6370. }
  6371. }
  6372. };
  6373. methods = {
  6374. on: on,
  6375. once: once,
  6376. off: off,
  6377. emit: emit
  6378. };
  6379. descriptors = {
  6380. on: d(on),
  6381. once: d(once),
  6382. off: d(off),
  6383. emit: d(emit)
  6384. };
  6385. base = defineProperties({}, descriptors);
  6386. module.exports = exports = function(o) {
  6387. return (o == null) ? create(base) : defineProperties(Object(o), descriptors);
  6388. };
  6389. exports.methods = methods;
  6390. }, {
  6391. "d": 16,
  6392. "es5-ext/object/valid-callable": 54
  6393. }],
  6394. 79: [function(require, module, exports) {
  6395. exports.read = function(buffer, offset, isLE, mLen, nBytes) {
  6396. var e, m
  6397. var eLen = (nBytes * 8) - mLen - 1
  6398. var eMax = (1 << eLen) - 1
  6399. var eBias = eMax >> 1
  6400. var nBits = -7
  6401. var i = isLE ? (nBytes - 1) : 0
  6402. var d = isLE ? -1 : 1
  6403. var s = buffer[offset + i]
  6404. i += d
  6405. e = s & ((1 << (-nBits)) - 1)
  6406. s >>= (-nBits)
  6407. nBits += eLen
  6408. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  6409. m = e & ((1 << (-nBits)) - 1)
  6410. e >>= (-nBits)
  6411. nBits += mLen
  6412. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  6413. if (e === 0) {
  6414. e = 1 - eBias
  6415. } else if (e === eMax) {
  6416. return m ? NaN : ((s ? -1 : 1) * Infinity)
  6417. } else {
  6418. m = m + Math.pow(2, mLen)
  6419. e = e - eBias
  6420. }
  6421. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  6422. }
  6423. exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
  6424. var e, m, c
  6425. var eLen = (nBytes * 8) - mLen - 1
  6426. var eMax = (1 << eLen) - 1
  6427. var eBias = eMax >> 1
  6428. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  6429. var i = isLE ? 0 : (nBytes - 1)
  6430. var d = isLE ? 1 : -1
  6431. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  6432. value = Math.abs(value)
  6433. if (isNaN(value) || value === Infinity) {
  6434. m = isNaN(value) ? 1 : 0
  6435. e = eMax
  6436. } else {
  6437. e = Math.floor(Math.log(value) / Math.LN2)
  6438. if (value * (c = Math.pow(2, -e)) < 1) {
  6439. e--
  6440. c *= 2
  6441. }
  6442. if (e + eBias >= 1) {
  6443. value += rt / c
  6444. } else {
  6445. value += rt * Math.pow(2, 1 - eBias)
  6446. }
  6447. if (value * c >= 2) {
  6448. e++
  6449. c /= 2
  6450. }
  6451. if (e + eBias >= eMax) {
  6452. m = 0
  6453. e = eMax
  6454. } else if (e + eBias >= 1) {
  6455. m = ((value * c) - 1) * Math.pow(2, mLen)
  6456. e = e + eBias
  6457. } else {
  6458. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  6459. e = 0
  6460. }
  6461. }
  6462. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  6463. e = (e << mLen) | m
  6464. eLen += mLen
  6465. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  6466. buffer[offset + i - d] |= s * 128
  6467. }
  6468. }, {}],
  6469. 80: [function(require, module, exports) {
  6470. if (typeof Object.create === 'function') {
  6471. // implementation from standard node.js 'util' module
  6472. module.exports = function inherits(ctor, superCtor) {
  6473. ctor.super_ = superCtor
  6474. ctor.prototype = Object.create(superCtor.prototype, {
  6475. constructor: {
  6476. value: ctor,
  6477. enumerable: false,
  6478. writable: true,
  6479. configurable: true
  6480. }
  6481. });
  6482. };
  6483. } else {
  6484. // old school shim for old browsers
  6485. module.exports = function inherits(ctor, superCtor) {
  6486. ctor.super_ = superCtor
  6487. var TempCtor = function() {}
  6488. TempCtor.prototype = superCtor.prototype
  6489. ctor.prototype = new TempCtor()
  6490. ctor.prototype.constructor = ctor
  6491. }
  6492. }
  6493. }, {}],
  6494. 81: [function(require, module, exports) {
  6495. /*!
  6496. * Determine if an object is a Buffer
  6497. *
  6498. * @author Feross Aboukhadijeh <https://feross.org>
  6499. * @license MIT
  6500. */
  6501. // The _isBuffer check is for Safari 5-7 support, because it's missing
  6502. // Object.prototype.constructor. Remove this eventually
  6503. module.exports = function(obj) {
  6504. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  6505. }
  6506. function isBuffer(obj) {
  6507. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj
  6508. .constructor.isBuffer(obj)
  6509. }
  6510. // For Node v0.10 support. Remove this eventually.
  6511. function isSlowBuffer(obj) {
  6512. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' &&
  6513. isBuffer(obj.slice(0, 0))
  6514. }
  6515. }, {}],
  6516. 82: [function(require, module, exports) {
  6517. 'use strict'
  6518. var Buffer = require('safe-buffer').Buffer
  6519. /* Protocol - protocol constants */
  6520. var protocol = module.exports
  6521. /* Command code => mnemonic */
  6522. protocol.types = {
  6523. 0: 'reserved',
  6524. 1: 'connect',
  6525. 2: 'connack',
  6526. 3: 'publish',
  6527. 4: 'puback',
  6528. 5: 'pubrec',
  6529. 6: 'pubrel',
  6530. 7: 'pubcomp',
  6531. 8: 'subscribe',
  6532. 9: 'suback',
  6533. 10: 'unsubscribe',
  6534. 11: 'unsuback',
  6535. 12: 'pingreq',
  6536. 13: 'pingresp',
  6537. 14: 'disconnect',
  6538. 15: 'auth'
  6539. }
  6540. /* Mnemonic => Command code */
  6541. protocol.codes = {}
  6542. for (var k in protocol.types) {
  6543. var v = protocol.types[k]
  6544. protocol.codes[v] = k
  6545. }
  6546. /* Header */
  6547. protocol.CMD_SHIFT = 4
  6548. protocol.CMD_MASK = 0xF0
  6549. protocol.DUP_MASK = 0x08
  6550. protocol.QOS_MASK = 0x03
  6551. protocol.QOS_SHIFT = 1
  6552. protocol.RETAIN_MASK = 0x01
  6553. /* Length */
  6554. protocol.LENGTH_MASK = 0x7F
  6555. protocol.LENGTH_FIN_MASK = 0x80
  6556. /* Connack */
  6557. protocol.SESSIONPRESENT_MASK = 0x01
  6558. protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])
  6559. protocol.CONNACK_HEADER = Buffer.from([protocol.codes['connack'] << protocol.CMD_SHIFT])
  6560. /* Connect */
  6561. protocol.USERNAME_MASK = 0x80
  6562. protocol.PASSWORD_MASK = 0x40
  6563. protocol.WILL_RETAIN_MASK = 0x20
  6564. protocol.WILL_QOS_MASK = 0x18
  6565. protocol.WILL_QOS_SHIFT = 3
  6566. protocol.WILL_FLAG_MASK = 0x04
  6567. protocol.CLEAN_SESSION_MASK = 0x02
  6568. protocol.CONNECT_HEADER = Buffer.from([protocol.codes['connect'] << protocol.CMD_SHIFT])
  6569. /* Properties */
  6570. protocol.properties = {
  6571. sessionExpiryInterval: 17,
  6572. willDelayInterval: 24,
  6573. receiveMaximum: 33,
  6574. maximumPacketSize: 39,
  6575. topicAliasMaximum: 34,
  6576. requestResponseInformation: 25,
  6577. requestProblemInformation: 23,
  6578. userProperties: 38,
  6579. authenticationMethod: 21,
  6580. authenticationData: 22,
  6581. payloadFormatIndicator: 1,
  6582. messageExpiryInterval: 2,
  6583. contentType: 3,
  6584. responseTopic: 8,
  6585. correlationData: 9,
  6586. maximumQoS: 36,
  6587. retainAvailable: 37,
  6588. assignedClientIdentifier: 18,
  6589. reasonString: 31,
  6590. wildcardSubscriptionAvailable: 40,
  6591. subscriptionIdentifiersAvailable: 41,
  6592. sharedSubscriptionAvailable: 42,
  6593. serverKeepAlive: 19,
  6594. responseInformation: 26,
  6595. serverReference: 28,
  6596. topicAlias: 35,
  6597. subscriptionIdentifier: 11
  6598. }
  6599. protocol.propertiesCodes = {}
  6600. for (var prop in protocol.properties) {
  6601. var id = protocol.properties[prop]
  6602. protocol.propertiesCodes[id] = prop
  6603. }
  6604. protocol.propertiesTypes = {
  6605. sessionExpiryInterval: 'int32',
  6606. willDelayInterval: 'int32',
  6607. receiveMaximum: 'int16',
  6608. maximumPacketSize: 'int32',
  6609. topicAliasMaximum: 'int16',
  6610. requestResponseInformation: 'byte',
  6611. requestProblemInformation: 'byte',
  6612. userProperties: 'pair',
  6613. authenticationMethod: 'string',
  6614. authenticationData: 'binary',
  6615. payloadFormatIndicator: 'byte',
  6616. messageExpiryInterval: 'int32',
  6617. contentType: 'string',
  6618. responseTopic: 'string',
  6619. correlationData: 'binary',
  6620. maximumQoS: 'int8',
  6621. retainAvailable: 'byte',
  6622. assignedClientIdentifier: 'string',
  6623. reasonString: 'string',
  6624. wildcardSubscriptionAvailable: 'byte',
  6625. subscriptionIdentifiersAvailable: 'byte',
  6626. sharedSubscriptionAvailable: 'byte',
  6627. serverKeepAlive: 'int32',
  6628. responseInformation: 'string',
  6629. serverReference: 'string',
  6630. topicAlias: 'int16',
  6631. subscriptionIdentifier: 'var'
  6632. }
  6633. function genHeader(type) {
  6634. return [0, 1, 2].map(function(qos) {
  6635. return [0, 1].map(function(dup) {
  6636. return [0, 1].map(function(retain) {
  6637. var buf = new Buffer(1)
  6638. buf.writeUInt8(
  6639. protocol.codes[type] << protocol
  6640. .CMD_SHIFT |
  6641. (dup ? protocol.DUP_MASK : 0) |
  6642. qos << protocol.QOS_SHIFT | retain, 0,
  6643. true)
  6644. return buf
  6645. })
  6646. })
  6647. })
  6648. }
  6649. /* Publish */
  6650. protocol.PUBLISH_HEADER = genHeader('publish')
  6651. /* Subscribe */
  6652. protocol.SUBSCRIBE_HEADER = genHeader('subscribe')
  6653. protocol.SUBSCRIBE_OPTIONS_QOS_MASK = 0x03
  6654. protocol.SUBSCRIBE_OPTIONS_NL_MASK = 0x01
  6655. protocol.SUBSCRIBE_OPTIONS_NL_SHIFT = 2
  6656. protocol.SUBSCRIBE_OPTIONS_RAP_MASK = 0x01
  6657. protocol.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3
  6658. protocol.SUBSCRIBE_OPTIONS_RH_MASK = 0x03
  6659. protocol.SUBSCRIBE_OPTIONS_RH_SHIFT = 4
  6660. protocol.SUBSCRIBE_OPTIONS_RH = [0x00, 0x10, 0x20]
  6661. protocol.SUBSCRIBE_OPTIONS_NL = 0x04
  6662. protocol.SUBSCRIBE_OPTIONS_RAP = 0x08
  6663. protocol.SUBSCRIBE_OPTIONS_QOS = [0x00, 0x01, 0x02]
  6664. /* Unsubscribe */
  6665. protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')
  6666. /* Confirmations */
  6667. protocol.ACKS = {
  6668. unsuback: genHeader('unsuback'),
  6669. puback: genHeader('puback'),
  6670. pubcomp: genHeader('pubcomp'),
  6671. pubrel: genHeader('pubrel'),
  6672. pubrec: genHeader('pubrec')
  6673. }
  6674. protocol.SUBACK_HEADER = Buffer.from([protocol.codes['suback'] << protocol.CMD_SHIFT])
  6675. /* Protocol versions */
  6676. protocol.VERSION3 = Buffer.from([3])
  6677. protocol.VERSION4 = Buffer.from([4])
  6678. protocol.VERSION5 = Buffer.from([5])
  6679. /* QoS */
  6680. protocol.QOS = [0, 1, 2].map(function(qos) {
  6681. return Buffer.from([qos])
  6682. })
  6683. /* Empty packets */
  6684. protocol.EMPTY = {
  6685. pingreq: Buffer.from([protocol.codes['pingreq'] << 4, 0]),
  6686. pingresp: Buffer.from([protocol.codes['pingresp'] << 4, 0]),
  6687. disconnect: Buffer.from([protocol.codes['disconnect'] << 4, 0])
  6688. }
  6689. }, {
  6690. "safe-buffer": 110
  6691. }],
  6692. 83: [function(require, module, exports) {
  6693. 'use strict'
  6694. var Buffer = require('safe-buffer').Buffer
  6695. var writeToStream = require('./writeToStream')
  6696. var EE = require('events').EventEmitter
  6697. var inherits = require('inherits')
  6698. function generate(packet, opts) {
  6699. var stream = new Accumulator()
  6700. writeToStream(packet, stream, opts)
  6701. return stream.concat()
  6702. }
  6703. function Accumulator() {
  6704. this._array = new Array(20)
  6705. this._i = 0
  6706. }
  6707. inherits(Accumulator, EE)
  6708. Accumulator.prototype.write = function(chunk) {
  6709. this._array[this._i++] = chunk
  6710. return true
  6711. }
  6712. Accumulator.prototype.concat = function() {
  6713. var length = 0
  6714. var lengths = new Array(this._array.length)
  6715. var list = this._array
  6716. var pos = 0
  6717. var i
  6718. var result
  6719. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  6720. if (typeof list[i] !== 'string') lengths[i] = list[i].length
  6721. else lengths[i] = Buffer.byteLength(list[i])
  6722. length += lengths[i]
  6723. }
  6724. result = Buffer.allocUnsafe(length)
  6725. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  6726. if (typeof list[i] !== 'string') {
  6727. list[i].copy(result, pos)
  6728. pos += lengths[i]
  6729. } else {
  6730. result.write(list[i], pos)
  6731. pos += lengths[i]
  6732. }
  6733. }
  6734. return result
  6735. }
  6736. module.exports = generate
  6737. }, {
  6738. "./writeToStream": 89,
  6739. "events": 13,
  6740. "inherits": 80,
  6741. "safe-buffer": 110
  6742. }],
  6743. 84: [function(require, module, exports) {
  6744. 'use strict'
  6745. exports.parser = require('./parser')
  6746. exports.generate = require('./generate')
  6747. exports.writeToStream = require('./writeToStream')
  6748. }, {
  6749. "./generate": 83,
  6750. "./parser": 88,
  6751. "./writeToStream": 89
  6752. }],
  6753. 85: [function(require, module, exports) {
  6754. var DuplexStream = require('readable-stream/duplex'),
  6755. util = require('util'),
  6756. Buffer = require('safe-buffer').Buffer
  6757. function BufferList(callback) {
  6758. if (!(this instanceof BufferList))
  6759. return new BufferList(callback)
  6760. this._bufs = []
  6761. this.length = 0
  6762. if (typeof callback == 'function') {
  6763. this._callback = callback
  6764. var piper = function piper(err) {
  6765. if (this._callback) {
  6766. this._callback(err)
  6767. this._callback = null
  6768. }
  6769. }.bind(this)
  6770. this.on('pipe', function onPipe(src) {
  6771. src.on('error', piper)
  6772. })
  6773. this.on('unpipe', function onUnpipe(src) {
  6774. src.removeListener('error', piper)
  6775. })
  6776. } else {
  6777. this.append(callback)
  6778. }
  6779. DuplexStream.call(this)
  6780. }
  6781. util.inherits(BufferList, DuplexStream)
  6782. BufferList.prototype._offset = function _offset(offset) {
  6783. var tot = 0,
  6784. i = 0,
  6785. _t
  6786. if (offset === 0) return [0, 0]
  6787. for (; i < this._bufs.length; i++) {
  6788. _t = tot + this._bufs[i].length
  6789. if (offset < _t || i == this._bufs.length - 1)
  6790. return [i, offset - tot]
  6791. tot = _t
  6792. }
  6793. }
  6794. BufferList.prototype.append = function append(buf) {
  6795. var i = 0
  6796. if (Buffer.isBuffer(buf)) {
  6797. this._appendBuffer(buf);
  6798. } else if (Array.isArray(buf)) {
  6799. for (; i < buf.length; i++)
  6800. this.append(buf[i])
  6801. } else if (buf instanceof BufferList) {
  6802. // unwrap argument into individual BufferLists
  6803. for (; i < buf._bufs.length; i++)
  6804. this.append(buf._bufs[i])
  6805. } else if (buf != null) {
  6806. // coerce number arguments to strings, since Buffer(number) does
  6807. // uninitialized memory allocation
  6808. if (typeof buf == 'number')
  6809. buf = buf.toString()
  6810. this._appendBuffer(Buffer.from(buf));
  6811. }
  6812. return this
  6813. }
  6814. BufferList.prototype._appendBuffer = function appendBuffer(buf) {
  6815. this._bufs.push(buf)
  6816. this.length += buf.length
  6817. }
  6818. BufferList.prototype._write = function _write(buf, encoding, callback) {
  6819. this._appendBuffer(buf)
  6820. if (typeof callback == 'function')
  6821. callback()
  6822. }
  6823. BufferList.prototype._read = function _read(size) {
  6824. if (!this.length)
  6825. return this.push(null)
  6826. size = Math.min(size, this.length)
  6827. this.push(this.slice(0, size))
  6828. this.consume(size)
  6829. }
  6830. BufferList.prototype.end = function end(chunk) {
  6831. DuplexStream.prototype.end.call(this, chunk)
  6832. if (this._callback) {
  6833. this._callback(null, this.slice())
  6834. this._callback = null
  6835. }
  6836. }
  6837. BufferList.prototype.get = function get(index) {
  6838. return this.slice(index, index + 1)[0]
  6839. }
  6840. BufferList.prototype.slice = function slice(start, end) {
  6841. if (typeof start == 'number' && start < 0)
  6842. start += this.length
  6843. if (typeof end == 'number' && end < 0)
  6844. end += this.length
  6845. return this.copy(null, 0, start, end)
  6846. }
  6847. BufferList.prototype.copy = function copy(dst, dstStart, srcStart, srcEnd) {
  6848. if (typeof srcStart != 'number' || srcStart < 0)
  6849. srcStart = 0
  6850. if (typeof srcEnd != 'number' || srcEnd > this.length)
  6851. srcEnd = this.length
  6852. if (srcStart >= this.length)
  6853. return dst || Buffer.alloc(0)
  6854. if (srcEnd <= 0)
  6855. return dst || Buffer.alloc(0)
  6856. var copy = !!dst,
  6857. off = this._offset(srcStart),
  6858. len = srcEnd - srcStart,
  6859. bytes = len,
  6860. bufoff = (copy && dstStart) || 0,
  6861. start = off[1],
  6862. l, i
  6863. // copy/slice everything
  6864. if (srcStart === 0 && srcEnd == this.length) {
  6865. if (!copy) { // slice, but full concat if multiple buffers
  6866. return this._bufs.length === 1 ?
  6867. this._bufs[0] :
  6868. Buffer.concat(this._bufs, this.length)
  6869. }
  6870. // copy, need to copy individual buffers
  6871. for (i = 0; i < this._bufs.length; i++) {
  6872. this._bufs[i].copy(dst, bufoff)
  6873. bufoff += this._bufs[i].length
  6874. }
  6875. return dst
  6876. }
  6877. // easy, cheap case where it's a subset of one of the buffers
  6878. if (bytes <= this._bufs[off[0]].length - start) {
  6879. return copy ?
  6880. this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) :
  6881. this._bufs[off[0]].slice(start, start + bytes)
  6882. }
  6883. if (!copy) // a slice, we need something to copy in to
  6884. dst = Buffer.allocUnsafe(len)
  6885. for (i = off[0]; i < this._bufs.length; i++) {
  6886. l = this._bufs[i].length - start
  6887. if (bytes > l) {
  6888. this._bufs[i].copy(dst, bufoff, start)
  6889. } else {
  6890. this._bufs[i].copy(dst, bufoff, start, start + bytes)
  6891. break
  6892. }
  6893. bufoff += l
  6894. bytes -= l
  6895. if (start)
  6896. start = 0
  6897. }
  6898. return dst
  6899. }
  6900. BufferList.prototype.shallowSlice = function shallowSlice(start, end) {
  6901. start = start || 0
  6902. end = end || this.length
  6903. if (start < 0)
  6904. start += this.length
  6905. if (end < 0)
  6906. end += this.length
  6907. var startOffset = this._offset(start),
  6908. endOffset = this._offset(end),
  6909. buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
  6910. if (endOffset[1] == 0)
  6911. buffers.pop()
  6912. else
  6913. buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0,
  6914. endOffset[1])
  6915. if (startOffset[1] != 0)
  6916. buffers[0] = buffers[0].slice(startOffset[1])
  6917. return new BufferList(buffers)
  6918. }
  6919. BufferList.prototype.toString = function toString(encoding, start, end) {
  6920. return this.slice(start, end).toString(encoding)
  6921. }
  6922. BufferList.prototype.consume = function consume(bytes) {
  6923. while (this._bufs.length) {
  6924. if (bytes >= this._bufs[0].length) {
  6925. bytes -= this._bufs[0].length
  6926. this.length -= this._bufs[0].length
  6927. this._bufs.shift()
  6928. } else {
  6929. this._bufs[0] = this._bufs[0].slice(bytes)
  6930. this.length -= bytes
  6931. break
  6932. }
  6933. }
  6934. return this
  6935. }
  6936. BufferList.prototype.duplicate = function duplicate() {
  6937. var i = 0,
  6938. copy = new BufferList()
  6939. for (; i < this._bufs.length; i++)
  6940. copy.append(this._bufs[i])
  6941. return copy
  6942. }
  6943. BufferList.prototype.destroy = function destroy() {
  6944. this._bufs.length = 0
  6945. this.length = 0
  6946. this.push(null)
  6947. }
  6948. ;
  6949. (function() {
  6950. var methods = {
  6951. 'readDoubleBE': 8,
  6952. 'readDoubleLE': 8,
  6953. 'readFloatBE': 4,
  6954. 'readFloatLE': 4,
  6955. 'readInt32BE': 4,
  6956. 'readInt32LE': 4,
  6957. 'readUInt32BE': 4,
  6958. 'readUInt32LE': 4,
  6959. 'readInt16BE': 2,
  6960. 'readInt16LE': 2,
  6961. 'readUInt16BE': 2,
  6962. 'readUInt16LE': 2,
  6963. 'readInt8': 1,
  6964. 'readUInt8': 1
  6965. }
  6966. for (var m in methods) {
  6967. (function(m) {
  6968. BufferList.prototype[m] = function(offset) {
  6969. return this.slice(offset, offset + methods[m])[m](0)
  6970. }
  6971. }(m))
  6972. }
  6973. }())
  6974. module.exports = BufferList
  6975. }, {
  6976. "readable-stream/duplex": 97,
  6977. "safe-buffer": 110,
  6978. "util": 117
  6979. }],
  6980. 86: [function(require, module, exports) {
  6981. 'use strict'
  6982. var Buffer = require('safe-buffer').Buffer
  6983. var max = 65536
  6984. var cache = {}
  6985. function generateBuffer(i) {
  6986. var buffer = Buffer.allocUnsafe(2)
  6987. buffer.writeUInt8(i >> 8, 0)
  6988. buffer.writeUInt8(i & 0x00FF, 0 + 1)
  6989. return buffer
  6990. }
  6991. function generateCache() {
  6992. for (var i = 0; i < max; i++) {
  6993. cache[i] = generateBuffer(i)
  6994. }
  6995. }
  6996. /**
  6997. * calcVariableByteIntLength - calculate the variable byte integer
  6998. * length field
  6999. *
  7000. * @api private
  7001. */
  7002. function calcVariableByteIntLength(length) {
  7003. if (length >= 0 && length < 128) return 1
  7004. else if (length >= 128 && length < 16384) return 2
  7005. else if (length >= 16384 && length < 2097152) return 3
  7006. else if (length >= 2097152 && length < 268435456) return 4
  7007. else return 0
  7008. }
  7009. function genBufVariableByteInt(num) {
  7010. var digit = 0
  7011. var pos = 0
  7012. var length = calcVariableByteIntLength(num)
  7013. var buffer = Buffer.allocUnsafe(length)
  7014. do {
  7015. digit = num % 128 | 0
  7016. num = num / 128 | 0
  7017. if (num > 0) digit = digit | 0x80
  7018. buffer.writeUInt8(digit, pos++)
  7019. } while (num > 0)
  7020. return {
  7021. data: buffer,
  7022. length: length
  7023. }
  7024. }
  7025. function generate4ByteBuffer(num) {
  7026. var buffer = Buffer.allocUnsafe(4)
  7027. buffer.writeUInt32BE(num, 0)
  7028. return buffer
  7029. }
  7030. module.exports = {
  7031. cache: cache,
  7032. generateCache: generateCache,
  7033. generateNumber: generateBuffer,
  7034. genBufVariableByteInt: genBufVariableByteInt,
  7035. generate4ByteBuffer: generate4ByteBuffer
  7036. }
  7037. }, {
  7038. "safe-buffer": 110
  7039. }],
  7040. 87: [function(require, module, exports) {
  7041. function Packet() {
  7042. this.cmd = null
  7043. this.retain = false
  7044. this.qos = 0
  7045. this.dup = false
  7046. this.length = -1
  7047. this.topic = null
  7048. this.payload = null
  7049. }
  7050. module.exports = Packet
  7051. }, {}],
  7052. 88: [function(require, module, exports) {
  7053. 'use strict'
  7054. var bl = require('bl')
  7055. var inherits = require('inherits')
  7056. var EE = require('events').EventEmitter
  7057. var Packet = require('./packet')
  7058. var constants = require('./constants')
  7059. function Parser(opt) {
  7060. if (!(this instanceof Parser)) return new Parser(opt)
  7061. this.settings = opt || {}
  7062. this._states = [
  7063. '_parseHeader',
  7064. '_parseLength',
  7065. '_parsePayload',
  7066. '_newPacket'
  7067. ]
  7068. this._resetState()
  7069. }
  7070. inherits(Parser, EE)
  7071. Parser.prototype._resetState = function() {
  7072. this.packet = new Packet()
  7073. this.error = null
  7074. this._list = bl()
  7075. this._stateCounter = 0
  7076. }
  7077. Parser.prototype.parse = function(buf) {
  7078. if (this.error) this._resetState()
  7079. this._list.append(buf)
  7080. while ((this.packet.length !== -1 || this._list.length > 0) &&
  7081. this[this._states[this._stateCounter]]() &&
  7082. !this.error) {
  7083. this._stateCounter++
  7084. if (this._stateCounter >= this._states.length) this._stateCounter = 0
  7085. }
  7086. return this._list.length
  7087. }
  7088. Parser.prototype._parseHeader = function() {
  7089. // There is at least one byte in the buffer
  7090. var zero = this._list.readUInt8(0)
  7091. this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]
  7092. this.packet.retain = (zero & constants.RETAIN_MASK) !== 0
  7093. this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK
  7094. this.packet.dup = (zero & constants.DUP_MASK) !== 0
  7095. this._list.consume(1)
  7096. return true
  7097. }
  7098. Parser.prototype._parseLength = function() {
  7099. // There is at least one byte in the list
  7100. var result = this._parseVarByteNum(true)
  7101. if (result) {
  7102. this.packet.length = result.value
  7103. this._list.consume(result.bytes)
  7104. }
  7105. return !!result
  7106. }
  7107. Parser.prototype._parsePayload = function() {
  7108. var result = false
  7109. // Do we have a payload? Do we have enough data to complete the payload?
  7110. // PINGs have no payload
  7111. if (this.packet.length === 0 || this._list.length >= this.packet.length) {
  7112. this._pos = 0
  7113. switch (this.packet.cmd) {
  7114. case 'connect':
  7115. this._parseConnect()
  7116. break
  7117. case 'connack':
  7118. this._parseConnack()
  7119. break
  7120. case 'publish':
  7121. this._parsePublish()
  7122. break
  7123. case 'puback':
  7124. case 'pubrec':
  7125. case 'pubrel':
  7126. case 'pubcomp':
  7127. this._parseConfirmation()
  7128. break
  7129. case 'subscribe':
  7130. this._parseSubscribe()
  7131. break
  7132. case 'suback':
  7133. this._parseSuback()
  7134. break
  7135. case 'unsubscribe':
  7136. this._parseUnsubscribe()
  7137. break
  7138. case 'unsuback':
  7139. this._parseUnsuback()
  7140. break
  7141. case 'pingreq':
  7142. case 'pingresp':
  7143. // These are empty, nothing to do
  7144. break
  7145. case 'disconnect':
  7146. this._parseDisconnect()
  7147. break
  7148. case 'auth':
  7149. this._parseAuth()
  7150. break
  7151. default:
  7152. this._emitError(new Error('Not supported'))
  7153. }
  7154. result = true
  7155. }
  7156. return result
  7157. }
  7158. Parser.prototype._parseConnect = function() {
  7159. var protocolId // Protocol ID
  7160. var clientId // Client ID
  7161. var topic // Will topic
  7162. var payload // Will payload
  7163. var password // Password
  7164. var username // Username
  7165. var flags = {}
  7166. var packet = this.packet
  7167. // Parse protocolId
  7168. protocolId = this._parseString()
  7169. if (protocolId === null) return this._emitError(new Error(
  7170. 'Cannot parse protocolId'))
  7171. if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {
  7172. return this._emitError(new Error('Invalid protocolId'))
  7173. }
  7174. packet.protocolId = protocolId
  7175. // Parse constants version number
  7176. if (this._pos >= this._list.length) return this._emitError(new Error(
  7177. 'Packet too short'))
  7178. packet.protocolVersion = this._list.readUInt8(this._pos)
  7179. if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4 && packet
  7180. .protocolVersion !== 5) {
  7181. return this._emitError(new Error('Invalid protocol version'))
  7182. }
  7183. this._pos++
  7184. if (this._pos >= this._list.length) {
  7185. return this._emitError(new Error('Packet too short'))
  7186. }
  7187. // Parse connect flags
  7188. flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)
  7189. flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)
  7190. flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)
  7191. if (flags.will) {
  7192. packet.will = {}
  7193. packet.will.retain = (this._list.readUInt8(this._pos) & constants
  7194. .WILL_RETAIN_MASK) !== 0
  7195. packet.will.qos = (this._list.readUInt8(this._pos) &
  7196. constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT
  7197. }
  7198. packet.clean = (this._list.readUInt8(this._pos) & constants
  7199. .CLEAN_SESSION_MASK) !== 0
  7200. this._pos++
  7201. // Parse keepalive
  7202. packet.keepalive = this._parseNum()
  7203. if (packet.keepalive === -1) return this._emitError(new Error(
  7204. 'Packet too short'))
  7205. // parse properties
  7206. if (packet.protocolVersion === 5) {
  7207. var properties = this._parseProperties()
  7208. if (Object.getOwnPropertyNames(properties).length) {
  7209. packet.properties = properties
  7210. }
  7211. }
  7212. // Parse clientId
  7213. clientId = this._parseString()
  7214. if (clientId === null) return this._emitError(new Error('Packet too short'))
  7215. packet.clientId = clientId
  7216. if (flags.will) {
  7217. if (packet.protocolVersion === 5) {
  7218. var willProperties = this._parseProperties()
  7219. if (Object.getOwnPropertyNames(willProperties).length) {
  7220. packet.will.properties = willProperties
  7221. }
  7222. }
  7223. // Parse will topic
  7224. topic = this._parseString()
  7225. if (topic === null) return this._emitError(new Error(
  7226. 'Cannot parse will topic'))
  7227. packet.will.topic = topic
  7228. // Parse will payload
  7229. payload = this._parseBuffer()
  7230. if (payload === null) return this._emitError(new Error(
  7231. 'Cannot parse will payload'))
  7232. packet.will.payload = payload
  7233. }
  7234. // Parse username
  7235. if (flags.username) {
  7236. username = this._parseString()
  7237. if (username === null) return this._emitError(new Error(
  7238. 'Cannot parse username'))
  7239. packet.username = username
  7240. }
  7241. // Parse password
  7242. if (flags.password) {
  7243. password = this._parseBuffer()
  7244. if (password === null) return this._emitError(new Error(
  7245. 'Cannot parse password'))
  7246. packet.password = password
  7247. }
  7248. // need for right parse auth packet and self set up
  7249. this.settings = packet
  7250. return packet
  7251. }
  7252. Parser.prototype._parseConnack = function() {
  7253. var packet = this.packet
  7254. if (this._list.length < 2) return null
  7255. packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants
  7256. .SESSIONPRESENT_MASK)
  7257. if (this.settings.protocolVersion === 5) {
  7258. packet.reasonCode = this._list.readUInt8(this._pos++)
  7259. } else {
  7260. packet.returnCode = this._list.readUInt8(this._pos++)
  7261. }
  7262. if (packet.returnCode === -1 || packet.reasonCode === -1) return this
  7263. ._emitError(new Error('Cannot parse return code'))
  7264. // mqtt 5 properties
  7265. if (this.settings.protocolVersion === 5) {
  7266. var properties = this._parseProperties()
  7267. if (Object.getOwnPropertyNames(properties).length) {
  7268. packet.properties = properties
  7269. }
  7270. }
  7271. }
  7272. Parser.prototype._parsePublish = function() {
  7273. var packet = this.packet
  7274. packet.topic = this._parseString()
  7275. if (packet.topic === null) return this._emitError(new Error(
  7276. 'Cannot parse topic'))
  7277. // Parse messageId
  7278. if (packet.qos > 0)
  7279. if (!this._parseMessageId()) {
  7280. return
  7281. }
  7282. // Properties mqtt 5
  7283. if (this.settings.protocolVersion === 5) {
  7284. var properties = this._parseProperties()
  7285. if (Object.getOwnPropertyNames(properties).length) {
  7286. packet.properties = properties
  7287. }
  7288. }
  7289. packet.payload = this._list.slice(this._pos, packet.length)
  7290. }
  7291. Parser.prototype._parseSubscribe = function() {
  7292. var packet = this.packet
  7293. var topic
  7294. var options
  7295. var qos
  7296. var rh
  7297. var rap
  7298. var nl
  7299. var subscription
  7300. if (packet.qos !== 1) {
  7301. return this._emitError(new Error('Wrong subscribe header'))
  7302. }
  7303. packet.subscriptions = []
  7304. if (!this._parseMessageId()) {
  7305. return
  7306. }
  7307. // Properties mqtt 5
  7308. if (this.settings.protocolVersion === 5) {
  7309. var properties = this._parseProperties()
  7310. if (Object.getOwnPropertyNames(properties).length) {
  7311. packet.properties = properties
  7312. }
  7313. }
  7314. while (this._pos < packet.length) {
  7315. // Parse topic
  7316. topic = this._parseString()
  7317. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  7318. options = this._parseByte()
  7319. qos = options & constants.SUBSCRIBE_OPTIONS_QOS_MASK
  7320. nl = ((options >> constants.SUBSCRIBE_OPTIONS_NL_SHIFT) & constants
  7321. .SUBSCRIBE_OPTIONS_NL_MASK) !== 0
  7322. rap = ((options >> constants.SUBSCRIBE_OPTIONS_RAP_SHIFT) & constants
  7323. .SUBSCRIBE_OPTIONS_RAP_MASK) !== 0
  7324. rh = (options >> constants.SUBSCRIBE_OPTIONS_RH_SHIFT) & constants
  7325. .SUBSCRIBE_OPTIONS_RH_MASK
  7326. subscription = {
  7327. topic: topic,
  7328. qos: qos
  7329. }
  7330. // mqtt 5 options
  7331. if (this.settings.protocolVersion === 5) {
  7332. subscription.nl = nl
  7333. subscription.rap = rap
  7334. subscription.rh = rh
  7335. }
  7336. // Push pair to subscriptions
  7337. packet.subscriptions.push(subscription)
  7338. }
  7339. }
  7340. Parser.prototype._parseSuback = function() {
  7341. var packet = this.packet
  7342. this.packet.granted = []
  7343. if (!this._parseMessageId()) {
  7344. return
  7345. }
  7346. // Properties mqtt 5
  7347. if (this.settings.protocolVersion === 5) {
  7348. var properties = this._parseProperties()
  7349. if (Object.getOwnPropertyNames(properties).length) {
  7350. packet.properties = properties
  7351. }
  7352. }
  7353. // Parse granted QoSes
  7354. while (this._pos < this.packet.length) {
  7355. this.packet.granted.push(this._list.readUInt8(this._pos++))
  7356. }
  7357. }
  7358. Parser.prototype._parseUnsubscribe = function() {
  7359. var packet = this.packet
  7360. packet.unsubscriptions = []
  7361. // Parse messageId
  7362. if (!this._parseMessageId()) {
  7363. return
  7364. }
  7365. // Properties mqtt 5
  7366. if (this.settings.protocolVersion === 5) {
  7367. var properties = this._parseProperties()
  7368. if (Object.getOwnPropertyNames(properties).length) {
  7369. packet.properties = properties
  7370. }
  7371. }
  7372. while (this._pos < packet.length) {
  7373. var topic
  7374. // Parse topic
  7375. topic = this._parseString()
  7376. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  7377. // Push topic to unsubscriptions
  7378. packet.unsubscriptions.push(topic)
  7379. }
  7380. }
  7381. Parser.prototype._parseUnsuback = function() {
  7382. var packet = this.packet
  7383. if (!this._parseMessageId()) return this._emitError(new Error(
  7384. 'Cannot parse messageId'))
  7385. // Properties mqtt 5
  7386. if (this.settings.protocolVersion === 5) {
  7387. var properties = this._parseProperties()
  7388. if (Object.getOwnPropertyNames(properties).length) {
  7389. packet.properties = properties
  7390. }
  7391. // Parse granted QoSes
  7392. packet.granted = []
  7393. while (this._pos < this.packet.length) {
  7394. this.packet.granted.push(this._list.readUInt8(this._pos++))
  7395. }
  7396. }
  7397. }
  7398. // parse packets like puback, pubrec, pubrel, pubcomp
  7399. Parser.prototype._parseConfirmation = function() {
  7400. var packet = this.packet
  7401. this._parseMessageId()
  7402. if (this.settings.protocolVersion === 5) {
  7403. if (packet.length > 2) {
  7404. // response code
  7405. packet.reasonCode = this._parseByte()
  7406. // properies mqtt 5
  7407. var properties = this._parseProperties()
  7408. if (Object.getOwnPropertyNames(properties).length) {
  7409. packet.properties = properties
  7410. }
  7411. }
  7412. }
  7413. return true
  7414. }
  7415. // parse disconnect packet
  7416. Parser.prototype._parseDisconnect = function() {
  7417. var packet = this.packet
  7418. if (this.settings.protocolVersion === 5) {
  7419. // response code
  7420. packet.reasonCode = this._parseByte()
  7421. // properies mqtt 5
  7422. var properties = this._parseProperties()
  7423. if (Object.getOwnPropertyNames(properties).length) {
  7424. packet.properties = properties
  7425. }
  7426. }
  7427. return true
  7428. }
  7429. // parse auth packet
  7430. Parser.prototype._parseAuth = function() {
  7431. var packet = this.packet
  7432. if (this.settings.protocolVersion !== 5) {
  7433. return this._emitError(new Error(
  7434. 'Not supported auth packet for this version MQTT'))
  7435. }
  7436. // response code
  7437. packet.reasonCode = this._parseByte()
  7438. // properies mqtt 5
  7439. var properties = this._parseProperties()
  7440. if (Object.getOwnPropertyNames(properties).length) {
  7441. packet.properties = properties
  7442. }
  7443. return true
  7444. }
  7445. Parser.prototype._parseMessageId = function() {
  7446. var packet = this.packet
  7447. packet.messageId = this._parseNum()
  7448. if (packet.messageId === null) {
  7449. this._emitError(new Error('Cannot parse messageId'))
  7450. return false
  7451. }
  7452. return true
  7453. }
  7454. Parser.prototype._parseString = function(maybeBuffer) {
  7455. var length = this._parseNum()
  7456. var result
  7457. var end = length + this._pos
  7458. if (length === -1 || end > this._list.length || end > this.packet.length)
  7459. return null
  7460. result = this._list.toString('utf8', this._pos, end)
  7461. this._pos += length
  7462. return result
  7463. }
  7464. Parser.prototype._parseStringPair = function() {
  7465. return {
  7466. name: this._parseString(),
  7467. value: this._parseString()
  7468. }
  7469. }
  7470. Parser.prototype._parseBuffer = function() {
  7471. var length = this._parseNum()
  7472. var result
  7473. var end = length + this._pos
  7474. if (length === -1 || end > this._list.length || end > this.packet.length)
  7475. return null
  7476. result = this._list.slice(this._pos, end)
  7477. this._pos += length
  7478. return result
  7479. }
  7480. Parser.prototype._parseNum = function() {
  7481. if (this._list.length - this._pos < 2) return -1
  7482. var result = this._list.readUInt16BE(this._pos)
  7483. this._pos += 2
  7484. return result
  7485. }
  7486. Parser.prototype._parse4ByteNum = function() {
  7487. if (this._list.length - this._pos < 4) return -1
  7488. var result = this._list.readUInt32BE(this._pos)
  7489. this._pos += 4
  7490. return result
  7491. }
  7492. Parser.prototype._parseVarByteNum = function(fullInfoFlag) {
  7493. var bytes = 0
  7494. var mul = 1
  7495. var length = 0
  7496. var result = true
  7497. var current
  7498. var padding = this._pos ? this._pos : 0
  7499. while (bytes < 5) {
  7500. current = this._list.readUInt8(padding + bytes++)
  7501. length += mul * (current & constants.LENGTH_MASK)
  7502. mul *= 0x80
  7503. if ((current & constants.LENGTH_FIN_MASK) === 0) break
  7504. if (this._list.length <= bytes) {
  7505. result = false
  7506. break
  7507. }
  7508. }
  7509. if (padding) {
  7510. this._pos += bytes
  7511. }
  7512. result = result ?
  7513. fullInfoFlag ? {
  7514. bytes: bytes,
  7515. value: length
  7516. } : length :
  7517. false
  7518. return result
  7519. }
  7520. Parser.prototype._parseByte = function() {
  7521. var result = this._list.readUInt8(this._pos)
  7522. this._pos++
  7523. return result
  7524. }
  7525. Parser.prototype._parseByType = function(type) {
  7526. switch (type) {
  7527. case 'byte': {
  7528. return this._parseByte() !== 0
  7529. }
  7530. case 'int8': {
  7531. return this._parseByte()
  7532. }
  7533. case 'int16': {
  7534. return this._parseNum()
  7535. }
  7536. case 'int32': {
  7537. return this._parse4ByteNum()
  7538. }
  7539. case 'var': {
  7540. return this._parseVarByteNum()
  7541. }
  7542. case 'string': {
  7543. return this._parseString()
  7544. }
  7545. case 'pair': {
  7546. return this._parseStringPair()
  7547. }
  7548. case 'binary': {
  7549. return this._parseBuffer()
  7550. }
  7551. }
  7552. }
  7553. Parser.prototype._parseProperties = function() {
  7554. var length = this._parseVarByteNum()
  7555. var start = this._pos
  7556. var end = start + length
  7557. var result = {}
  7558. while (this._pos < end) {
  7559. var type = this._parseByte()
  7560. var name = constants.propertiesCodes[type]
  7561. if (!name) {
  7562. this._emitError(new Error('Unknown property'))
  7563. return false
  7564. }
  7565. // user properties process
  7566. if (name === 'userProperties') {
  7567. if (!result[name]) {
  7568. result[name] = {}
  7569. }
  7570. var currentUserProperty = this._parseByType(constants.propertiesTypes[
  7571. name])
  7572. result[name][currentUserProperty.name] = currentUserProperty.value
  7573. continue
  7574. }
  7575. result[name] = this._parseByType(constants.propertiesTypes[name])
  7576. }
  7577. return result
  7578. }
  7579. Parser.prototype._newPacket = function() {
  7580. if (this.packet) {
  7581. this._list.consume(this.packet.length)
  7582. this.emit('packet', this.packet)
  7583. }
  7584. this.packet = new Packet()
  7585. this._pos = 0
  7586. return true
  7587. }
  7588. Parser.prototype._emitError = function(err) {
  7589. this.error = err
  7590. this.emit('error', err)
  7591. }
  7592. module.exports = Parser
  7593. }, {
  7594. "./constants": 82,
  7595. "./packet": 87,
  7596. "bl": 85,
  7597. "events": 13,
  7598. "inherits": 80
  7599. }],
  7600. 89: [function(require, module, exports) {
  7601. 'use strict'
  7602. var protocol = require('./constants')
  7603. var Buffer = require('safe-buffer').Buffer
  7604. var empty = Buffer.allocUnsafe(0)
  7605. var zeroBuf = Buffer.from([0])
  7606. var numbers = require('./numbers')
  7607. var nextTick = require('process-nextick-args').nextTick
  7608. var numCache = numbers.cache
  7609. var generateNumber = numbers.generateNumber
  7610. var generateCache = numbers.generateCache
  7611. var genBufVariableByteInt = numbers.genBufVariableByteInt
  7612. var generate4ByteBuffer = numbers.generate4ByteBuffer
  7613. var writeNumber = writeNumberCached
  7614. var toGenerate = true
  7615. function generate(packet, stream, opts) {
  7616. if (stream.cork) {
  7617. stream.cork()
  7618. nextTick(uncork, stream)
  7619. }
  7620. if (toGenerate) {
  7621. toGenerate = false
  7622. generateCache()
  7623. }
  7624. switch (packet.cmd) {
  7625. case 'connect':
  7626. return connect(packet, stream, opts)
  7627. case 'connack':
  7628. return connack(packet, stream, opts)
  7629. case 'publish':
  7630. return publish(packet, stream, opts)
  7631. case 'puback':
  7632. case 'pubrec':
  7633. case 'pubrel':
  7634. case 'pubcomp':
  7635. return confirmation(packet, stream, opts)
  7636. case 'subscribe':
  7637. return subscribe(packet, stream, opts)
  7638. case 'suback':
  7639. return suback(packet, stream, opts)
  7640. case 'unsubscribe':
  7641. return unsubscribe(packet, stream, opts)
  7642. case 'unsuback':
  7643. return unsuback(packet, stream, opts)
  7644. case 'pingreq':
  7645. case 'pingresp':
  7646. return emptyPacket(packet, stream, opts)
  7647. case 'disconnect':
  7648. return disconnect(packet, stream, opts)
  7649. case 'auth':
  7650. return auth(packet, stream, opts)
  7651. default:
  7652. stream.emit('error', new Error('Unknown command'))
  7653. return false
  7654. }
  7655. }
  7656. /**
  7657. * Controls numbers cache.
  7658. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache
  7659. */
  7660. Object.defineProperty(generate, 'cacheNumbers', {
  7661. get: function() {
  7662. return writeNumber === writeNumberCached
  7663. },
  7664. set: function(value) {
  7665. if (value) {
  7666. if (!numCache || Object.keys(numCache).length === 0)
  7667. toGenerate = true
  7668. writeNumber = writeNumberCached
  7669. } else {
  7670. toGenerate = false
  7671. writeNumber = writeNumberGenerated
  7672. }
  7673. }
  7674. })
  7675. function uncork(stream) {
  7676. stream.uncork()
  7677. }
  7678. function connect(packet, stream, opts) {
  7679. var settings = packet || {}
  7680. var protocolId = settings.protocolId || 'MQTT'
  7681. var protocolVersion = settings.protocolVersion || 4
  7682. var will = settings.will
  7683. var clean = settings.clean
  7684. var keepalive = settings.keepalive || 0
  7685. var clientId = settings.clientId || ''
  7686. var username = settings.username
  7687. var password = settings.password
  7688. /* mqtt5 new oprions */
  7689. var properties = settings.properties
  7690. if (clean === undefined) clean = true
  7691. var length = 0
  7692. // Must be a string and non-falsy
  7693. if (!protocolId ||
  7694. (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {
  7695. stream.emit('error', new Error('Invalid protocolId'))
  7696. return false
  7697. } else length += protocolId.length + 2
  7698. // Must be 3 or 4 or 5
  7699. if (protocolVersion !== 3 && protocolVersion !== 4 && protocolVersion !== 5) {
  7700. stream.emit('error', new Error('Invalid protocol version'))
  7701. return false
  7702. } else length += 1
  7703. // ClientId might be omitted in 3.1.1, but only if cleanSession is set to 1
  7704. if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&
  7705. (clientId || protocolVersion === 4) && (clientId || clean)) {
  7706. length += clientId.length + 2
  7707. } else {
  7708. if (protocolVersion < 4) {
  7709. stream.emit('error', new Error('clientId must be supplied before 3.1.1'))
  7710. return false
  7711. }
  7712. if ((clean * 1) === 0) {
  7713. stream.emit('error', new Error(
  7714. 'clientId must be given if cleanSession set to 0'))
  7715. return false
  7716. }
  7717. }
  7718. // Must be a two byte number
  7719. if (typeof keepalive !== 'number' ||
  7720. keepalive < 0 ||
  7721. keepalive > 65535 ||
  7722. keepalive % 1 !== 0) {
  7723. stream.emit('error', new Error('Invalid keepalive'))
  7724. return false
  7725. } else length += 2
  7726. // Connect flags
  7727. length += 1
  7728. // Properties
  7729. if (protocolVersion === 5) {
  7730. var propertiesData = getProperties(stream, properties)
  7731. length += propertiesData.length
  7732. }
  7733. // If will exists...
  7734. if (will) {
  7735. // It must be an object
  7736. if (typeof will !== 'object') {
  7737. stream.emit('error', new Error('Invalid will'))
  7738. return false
  7739. }
  7740. // It must have topic typeof string
  7741. if (!will.topic || typeof will.topic !== 'string') {
  7742. stream.emit('error', new Error('Invalid will topic'))
  7743. return false
  7744. } else {
  7745. length += Buffer.byteLength(will.topic) + 2
  7746. }
  7747. // Payload
  7748. if (will.payload) {
  7749. if (will.payload.length >= 0) {
  7750. if (typeof will.payload === 'string') {
  7751. length += Buffer.byteLength(will.payload) + 2
  7752. } else {
  7753. length += will.payload.length + 2
  7754. }
  7755. } else {
  7756. stream.emit('error', new Error('Invalid will payload'))
  7757. return false
  7758. }
  7759. // will properties
  7760. var willProperties = {}
  7761. if (protocolVersion === 5) {
  7762. willProperties = getProperties(stream, will.properties)
  7763. length += willProperties.length
  7764. }
  7765. }
  7766. }
  7767. // Username
  7768. var providedUsername = false
  7769. if (username != null) {
  7770. if (isStringOrBuffer(username)) {
  7771. providedUsername = true
  7772. length += Buffer.byteLength(username) + 2
  7773. } else {
  7774. stream.emit('error', new Error('Invalid username'))
  7775. return false
  7776. }
  7777. }
  7778. // Password
  7779. if (password != null) {
  7780. if (!providedUsername) {
  7781. stream.emit('error', new Error('Username is required to use password'))
  7782. return false
  7783. }
  7784. if (isStringOrBuffer(password)) {
  7785. length += byteLength(password) + 2
  7786. } else {
  7787. stream.emit('error', new Error('Invalid password'))
  7788. return false
  7789. }
  7790. }
  7791. // Generate header
  7792. stream.write(protocol.CONNECT_HEADER)
  7793. // Generate length
  7794. writeVarByteInt(stream, length)
  7795. // Generate protocol ID
  7796. writeStringOrBuffer(stream, protocolId)
  7797. stream.write(
  7798. protocolVersion === 4 ?
  7799. protocol.VERSION4 :
  7800. protocolVersion === 5 ?
  7801. protocol.VERSION5 :
  7802. protocol.VERSION3
  7803. )
  7804. // Connect flags
  7805. var flags = 0
  7806. flags |= (username != null) ? protocol.USERNAME_MASK : 0
  7807. flags |= (password != null) ? protocol.PASSWORD_MASK : 0
  7808. flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0
  7809. flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0
  7810. flags |= will ? protocol.WILL_FLAG_MASK : 0
  7811. flags |= clean ? protocol.CLEAN_SESSION_MASK : 0
  7812. stream.write(Buffer.from([flags]))
  7813. // Keepalive
  7814. writeNumber(stream, keepalive)
  7815. // Properties
  7816. if (protocolVersion === 5) {
  7817. propertiesData.write()
  7818. }
  7819. // Client ID
  7820. writeStringOrBuffer(stream, clientId)
  7821. // Will
  7822. if (will) {
  7823. if (protocolVersion === 5) {
  7824. willProperties.write()
  7825. }
  7826. writeString(stream, will.topic)
  7827. writeStringOrBuffer(stream, will.payload)
  7828. }
  7829. // Username and password
  7830. if (username != null) {
  7831. writeStringOrBuffer(stream, username)
  7832. }
  7833. if (password != null) {
  7834. writeStringOrBuffer(stream, password)
  7835. }
  7836. // This is a small packet that happens only once on a stream
  7837. // We assume the stream is always free to receive more data after this
  7838. return true
  7839. }
  7840. function connack(packet, stream, opts) {
  7841. var version = opts ? opts.protocolVersion : 4
  7842. var settings = packet || {}
  7843. var rc = version === 5 ? settings.reasonCode : settings.returnCode
  7844. var properties = settings.properties
  7845. var length = 2 // length of rc and sessionHeader
  7846. // Check return code
  7847. if (typeof rc !== 'number') {
  7848. stream.emit('error', new Error('Invalid return code'))
  7849. return false
  7850. }
  7851. // mqtt5 properties
  7852. var propertiesData = null
  7853. if (version === 5) {
  7854. propertiesData = getProperties(stream, properties)
  7855. length += propertiesData.length
  7856. }
  7857. stream.write(protocol.CONNACK_HEADER)
  7858. // length
  7859. writeVarByteInt(stream, length)
  7860. stream.write(settings.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)
  7861. stream.write(Buffer.from([rc]))
  7862. if (propertiesData != null) {
  7863. propertiesData.write()
  7864. }
  7865. return true
  7866. }
  7867. function publish(packet, stream, opts) {
  7868. var version = opts ? opts.protocolVersion : 4
  7869. var settings = packet || {}
  7870. var qos = settings.qos || 0
  7871. var retain = settings.retain ? protocol.RETAIN_MASK : 0
  7872. var topic = settings.topic
  7873. var payload = settings.payload || empty
  7874. var id = settings.messageId
  7875. var properties = settings.properties
  7876. var length = 0
  7877. // Topic must be a non-empty string or Buffer
  7878. if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2
  7879. else if (Buffer.isBuffer(topic)) length += topic.length + 2
  7880. else {
  7881. stream.emit('error', new Error('Invalid topic'))
  7882. return false
  7883. }
  7884. // Get the payload length
  7885. if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)
  7886. else length += payload.length
  7887. // Message ID must a number if qos > 0
  7888. if (qos && typeof id !== 'number') {
  7889. stream.emit('error', new Error('Invalid messageId'))
  7890. return false
  7891. } else if (qos) length += 2
  7892. // mqtt5 properties
  7893. var propertiesData = null
  7894. if (version === 5) {
  7895. propertiesData = getProperties(stream, properties)
  7896. length += propertiesData.length
  7897. }
  7898. // Header
  7899. stream.write(protocol.PUBLISH_HEADER[qos][settings.dup ? 1 : 0][retain ? 1 : 0])
  7900. // Remaining length
  7901. writeVarByteInt(stream, length)
  7902. // Topic
  7903. writeNumber(stream, byteLength(topic))
  7904. stream.write(topic)
  7905. // Message ID
  7906. if (qos > 0) writeNumber(stream, id)
  7907. // Properties
  7908. if (propertiesData != null) {
  7909. propertiesData.write()
  7910. }
  7911. // Payload
  7912. return stream.write(payload)
  7913. }
  7914. /* Puback, pubrec, pubrel and pubcomp */
  7915. function confirmation(packet, stream, opts) {
  7916. var version = opts ? opts.protocolVersion : 4
  7917. var settings = packet || {}
  7918. var type = settings.cmd || 'puback'
  7919. var id = settings.messageId
  7920. var dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0
  7921. var qos = 0
  7922. var reasonCode = settings.reasonCode
  7923. var properties = settings.properties
  7924. var length = version === 5 ? 3 : 2
  7925. if (type === 'pubrel') qos = 1
  7926. // Check message ID
  7927. if (typeof id !== 'number') {
  7928. stream.emit('error', new Error('Invalid messageId'))
  7929. return false
  7930. }
  7931. // properies mqtt 5
  7932. var propertiesData = null
  7933. if (version === 5) {
  7934. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts,
  7935. length)
  7936. if (!propertiesData) {
  7937. return false
  7938. }
  7939. length += propertiesData.length
  7940. }
  7941. // Header
  7942. stream.write(protocol.ACKS[type][qos][dup][0])
  7943. // Length
  7944. writeVarByteInt(stream, length)
  7945. // Message ID
  7946. writeNumber(stream, id)
  7947. // reason code in header
  7948. if (version === 5) {
  7949. stream.write(Buffer.from([reasonCode]))
  7950. }
  7951. // properies mqtt 5
  7952. if (propertiesData !== null) {
  7953. propertiesData.write()
  7954. }
  7955. return true
  7956. }
  7957. function subscribe(packet, stream, opts) {
  7958. var version = opts ? opts.protocolVersion : 4
  7959. var settings = packet || {}
  7960. var dup = settings.dup ? protocol.DUP_MASK : 0
  7961. var id = settings.messageId
  7962. var subs = settings.subscriptions
  7963. var properties = settings.properties
  7964. var length = 0
  7965. // Check message ID
  7966. if (typeof id !== 'number') {
  7967. stream.emit('error', new Error('Invalid messageId'))
  7968. return false
  7969. } else length += 2
  7970. // properies mqtt 5
  7971. var propertiesData = null
  7972. if (version === 5) {
  7973. propertiesData = getProperties(stream, properties)
  7974. length += propertiesData.length
  7975. }
  7976. // Check subscriptions
  7977. if (typeof subs === 'object' && subs.length) {
  7978. for (var i = 0; i < subs.length; i += 1) {
  7979. var itopic = subs[i].topic
  7980. var iqos = subs[i].qos
  7981. if (typeof itopic !== 'string') {
  7982. stream.emit('error', new Error('Invalid subscriptions - invalid topic'))
  7983. return false
  7984. }
  7985. if (typeof iqos !== 'number') {
  7986. stream.emit('error', new Error('Invalid subscriptions - invalid qos'))
  7987. return false
  7988. }
  7989. if (version === 5) {
  7990. var nl = subs[i].nl || false
  7991. if (typeof nl !== 'boolean') {
  7992. stream.emit('error', new Error(
  7993. 'Invalid subscriptions - invalid No Local'))
  7994. return false
  7995. }
  7996. var rap = subs[i].rap || false
  7997. if (typeof rap !== 'boolean') {
  7998. stream.emit('error', new Error(
  7999. 'Invalid subscriptions - invalid Retain as Published'))
  8000. return false
  8001. }
  8002. var rh = subs[i].rh || 0
  8003. if (typeof rh !== 'number' || rh > 2) {
  8004. stream.emit('error', new Error(
  8005. 'Invalid subscriptions - invalid Retain Handling'))
  8006. return false
  8007. }
  8008. }
  8009. length += Buffer.byteLength(itopic) + 2 + 1
  8010. }
  8011. } else {
  8012. stream.emit('error', new Error('Invalid subscriptions'))
  8013. return false
  8014. }
  8015. // Generate header
  8016. stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  8017. // Generate length
  8018. writeVarByteInt(stream, length)
  8019. // Generate message ID
  8020. writeNumber(stream, id)
  8021. // properies mqtt 5
  8022. if (propertiesData !== null) {
  8023. propertiesData.write()
  8024. }
  8025. var result = true
  8026. // Generate subs
  8027. for (var j = 0; j < subs.length; j++) {
  8028. var sub = subs[j]
  8029. var jtopic = sub.topic
  8030. var jqos = sub.qos
  8031. var jnl = +sub.nl
  8032. var jrap = +sub.rap
  8033. var jrh = sub.rh
  8034. var joptions
  8035. // Write topic string
  8036. writeString(stream, jtopic)
  8037. // options process
  8038. joptions = protocol.SUBSCRIBE_OPTIONS_QOS[jqos]
  8039. if (version === 5) {
  8040. joptions |= jnl ? protocol.SUBSCRIBE_OPTIONS_NL : 0
  8041. joptions |= jrap ? protocol.SUBSCRIBE_OPTIONS_RAP : 0
  8042. joptions |= jrh ? protocol.SUBSCRIBE_OPTIONS_RH[jrh] : 0
  8043. }
  8044. // Write options
  8045. result = stream.write(Buffer.from([joptions]))
  8046. }
  8047. return result
  8048. }
  8049. function suback(packet, stream, opts) {
  8050. var version = opts ? opts.protocolVersion : 4
  8051. var settings = packet || {}
  8052. var id = settings.messageId
  8053. var granted = settings.granted
  8054. var properties = settings.properties
  8055. var length = 0
  8056. // Check message ID
  8057. if (typeof id !== 'number') {
  8058. stream.emit('error', new Error('Invalid messageId'))
  8059. return false
  8060. } else length += 2
  8061. // Check granted qos vector
  8062. if (typeof granted === 'object' && granted.length) {
  8063. for (var i = 0; i < granted.length; i += 1) {
  8064. if (typeof granted[i] !== 'number') {
  8065. stream.emit('error', new Error('Invalid qos vector'))
  8066. return false
  8067. }
  8068. length += 1
  8069. }
  8070. } else {
  8071. stream.emit('error', new Error('Invalid qos vector'))
  8072. return false
  8073. }
  8074. // properies mqtt 5
  8075. var propertiesData = null
  8076. if (version === 5) {
  8077. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts,
  8078. length)
  8079. if (!propertiesData) {
  8080. return false
  8081. }
  8082. length += propertiesData.length
  8083. }
  8084. // header
  8085. stream.write(protocol.SUBACK_HEADER)
  8086. // Length
  8087. writeVarByteInt(stream, length)
  8088. // Message ID
  8089. writeNumber(stream, id)
  8090. // properies mqtt 5
  8091. if (propertiesData !== null) {
  8092. propertiesData.write()
  8093. }
  8094. return stream.write(Buffer.from(granted))
  8095. }
  8096. function unsubscribe(packet, stream, opts) {
  8097. var version = opts ? opts.protocolVersion : 4
  8098. var settings = packet || {}
  8099. var id = settings.messageId
  8100. var dup = settings.dup ? protocol.DUP_MASK : 0
  8101. var unsubs = settings.unsubscriptions
  8102. var properties = settings.properties
  8103. var length = 0
  8104. // Check message ID
  8105. if (typeof id !== 'number') {
  8106. stream.emit('error', new Error('Invalid messageId'))
  8107. return false
  8108. } else {
  8109. length += 2
  8110. }
  8111. // Check unsubs
  8112. if (typeof unsubs === 'object' && unsubs.length) {
  8113. for (var i = 0; i < unsubs.length; i += 1) {
  8114. if (typeof unsubs[i] !== 'string') {
  8115. stream.emit('error', new Error('Invalid unsubscriptions'))
  8116. return false
  8117. }
  8118. length += Buffer.byteLength(unsubs[i]) + 2
  8119. }
  8120. } else {
  8121. stream.emit('error', new Error('Invalid unsubscriptions'))
  8122. return false
  8123. }
  8124. // properies mqtt 5
  8125. var propertiesData = null
  8126. if (version === 5) {
  8127. propertiesData = getProperties(stream, properties)
  8128. length += propertiesData.length
  8129. }
  8130. // Header
  8131. stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  8132. // Length
  8133. writeVarByteInt(stream, length)
  8134. // Message ID
  8135. writeNumber(stream, id)
  8136. // properies mqtt 5
  8137. if (propertiesData !== null) {
  8138. propertiesData.write()
  8139. }
  8140. // Unsubs
  8141. var result = true
  8142. for (var j = 0; j < unsubs.length; j++) {
  8143. result = writeString(stream, unsubs[j])
  8144. }
  8145. return result
  8146. }
  8147. function unsuback(packet, stream, opts) {
  8148. var version = opts ? opts.protocolVersion : 4
  8149. var settings = packet || {}
  8150. var id = settings.messageId
  8151. var dup = settings.dup ? protocol.DUP_MASK : 0
  8152. var granted = settings.granted
  8153. var properties = settings.properties
  8154. var type = settings.cmd
  8155. var qos = 0
  8156. var length = 2
  8157. // Check message ID
  8158. if (typeof id !== 'number') {
  8159. stream.emit('error', new Error('Invalid messageId'))
  8160. return false
  8161. }
  8162. // Check granted
  8163. if (version === 5) {
  8164. if (typeof granted === 'object' && granted.length) {
  8165. for (var i = 0; i < granted.length; i += 1) {
  8166. if (typeof granted[i] !== 'number') {
  8167. stream.emit('error', new Error('Invalid qos vector'))
  8168. return false
  8169. }
  8170. length += 1
  8171. }
  8172. } else {
  8173. stream.emit('error', new Error('Invalid qos vector'))
  8174. return false
  8175. }
  8176. }
  8177. // properies mqtt 5
  8178. var propertiesData = null
  8179. if (version === 5) {
  8180. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts,
  8181. length)
  8182. if (!propertiesData) {
  8183. return false
  8184. }
  8185. length += propertiesData.length
  8186. }
  8187. // Header
  8188. stream.write(protocol.ACKS[type][qos][dup][0])
  8189. // Length
  8190. writeVarByteInt(stream, length)
  8191. // Message ID
  8192. writeNumber(stream, id)
  8193. // properies mqtt 5
  8194. if (propertiesData !== null) {
  8195. propertiesData.write()
  8196. }
  8197. // payload
  8198. if (version === 5) {
  8199. stream.write(Buffer.from(granted))
  8200. }
  8201. return true
  8202. }
  8203. function emptyPacket(packet, stream, opts) {
  8204. return stream.write(protocol.EMPTY[packet.cmd])
  8205. }
  8206. function disconnect(packet, stream, opts) {
  8207. var version = opts ? opts.protocolVersion : 4
  8208. var settings = packet || {}
  8209. var reasonCode = settings.reasonCode
  8210. var properties = settings.properties
  8211. var length = version === 5 ? 1 : 0
  8212. // properies mqtt 5
  8213. var propertiesData = null
  8214. if (version === 5) {
  8215. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts,
  8216. length)
  8217. if (!propertiesData) {
  8218. return false
  8219. }
  8220. length += propertiesData.length
  8221. }
  8222. // Header
  8223. stream.write(Buffer.from([protocol.codes['disconnect'] << 4]))
  8224. // Length
  8225. writeVarByteInt(stream, length)
  8226. // reason code in header
  8227. if (version === 5) {
  8228. stream.write(Buffer.from([reasonCode]))
  8229. }
  8230. // properies mqtt 5
  8231. if (propertiesData !== null) {
  8232. propertiesData.write()
  8233. }
  8234. return true
  8235. }
  8236. function auth(packet, stream, opts) {
  8237. var version = opts ? opts.protocolVersion : 4
  8238. var settings = packet || {}
  8239. var reasonCode = settings.reasonCode
  8240. var properties = settings.properties
  8241. var length = version === 5 ? 1 : 0
  8242. if (version !== 5) stream.emit('error', new Error(
  8243. 'Invalid mqtt version for auth packet'))
  8244. // properies mqtt 5
  8245. var propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts,
  8246. length)
  8247. if (!propertiesData) {
  8248. return false
  8249. }
  8250. length += propertiesData.length
  8251. // Header
  8252. stream.write(Buffer.from([protocol.codes['auth'] << 4]))
  8253. // Length
  8254. writeVarByteInt(stream, length)
  8255. // reason code in header
  8256. stream.write(Buffer.from([reasonCode]))
  8257. // properies mqtt 5
  8258. if (propertiesData !== null) {
  8259. propertiesData.write()
  8260. }
  8261. return true
  8262. }
  8263. /**
  8264. * writeVarByteInt - write an MQTT style variable byte integer to the buffer
  8265. *
  8266. * @param <Buffer> buffer - destination
  8267. * @param <Number> pos - offset
  8268. * @param <Number> length - length (>0)
  8269. * @returns <Number> number of bytes written
  8270. *
  8271. * @api private
  8272. */
  8273. var varByteIntCache = {}
  8274. function writeVarByteInt(stream, num) {
  8275. var buffer = varByteIntCache[num]
  8276. if (!buffer) {
  8277. buffer = genBufVariableByteInt(num).data
  8278. if (num < 16384) varByteIntCache[num] = buffer
  8279. }
  8280. stream.write(buffer)
  8281. }
  8282. /**
  8283. * writeString - write a utf8 string to the buffer
  8284. *
  8285. * @param <Buffer> buffer - destination
  8286. * @param <Number> pos - offset
  8287. * @param <String> string - string to write
  8288. * @return <Number> number of bytes written
  8289. *
  8290. * @api private
  8291. */
  8292. function writeString(stream, string) {
  8293. var strlen = Buffer.byteLength(string)
  8294. writeNumber(stream, strlen)
  8295. stream.write(string, 'utf8')
  8296. }
  8297. /**
  8298. * writeStringPair - write a utf8 string pairs to the buffer
  8299. *
  8300. * @param <Buffer> buffer - destination
  8301. * @param <String> name - string name to write
  8302. * @param <String> value - string value to write
  8303. * @return <Number> number of bytes written
  8304. *
  8305. * @api private
  8306. */
  8307. function writeStringPair(stream, name, value) {
  8308. writeString(stream, name)
  8309. writeString(stream, value)
  8310. }
  8311. /**
  8312. * writeNumber - write a two byte number to the buffer
  8313. *
  8314. * @param <Buffer> buffer - destination
  8315. * @param <Number> pos - offset
  8316. * @param <String> number - number to write
  8317. * @return <Number> number of bytes written
  8318. *
  8319. * @api private
  8320. */
  8321. function writeNumberCached(stream, number) {
  8322. return stream.write(numCache[number])
  8323. }
  8324. function writeNumberGenerated(stream, number) {
  8325. return stream.write(generateNumber(number))
  8326. }
  8327. function write4ByteNumber(stream, number) {
  8328. return stream.write(generate4ByteBuffer(number))
  8329. }
  8330. /**
  8331. * writeStringOrBuffer - write a String or Buffer with the its length prefix
  8332. *
  8333. * @param <Buffer> buffer - destination
  8334. * @param <Number> pos - offset
  8335. * @param <String> toWrite - String or Buffer
  8336. * @return <Number> number of bytes written
  8337. */
  8338. function writeStringOrBuffer(stream, toWrite) {
  8339. if (typeof toWrite === 'string') {
  8340. writeString(stream, toWrite)
  8341. } else if (toWrite) {
  8342. writeNumber(stream, toWrite.length)
  8343. stream.write(toWrite)
  8344. } else writeNumber(stream, 0)
  8345. }
  8346. function getProperties(stream, properties) {
  8347. /* connect properties */
  8348. if (typeof properties !== 'object' || properties.length != null) {
  8349. return {
  8350. length: 1,
  8351. write: function() {
  8352. writeProperties(stream, {}, 0)
  8353. }
  8354. }
  8355. }
  8356. var propertiesLength = 0
  8357. function getLengthProperty(name) {
  8358. var type = protocol.propertiesTypes[name]
  8359. var value = properties[name]
  8360. var length = 0
  8361. switch (type) {
  8362. case 'byte': {
  8363. if (typeof value !== 'boolean') {
  8364. stream.emit('error', new Error('Invalid ' + name))
  8365. return false
  8366. }
  8367. length += 1 + 1
  8368. break
  8369. }
  8370. case 'int8': {
  8371. if (typeof value !== 'number') {
  8372. stream.emit('error', new Error('Invalid ' + name))
  8373. return false
  8374. }
  8375. length += 1 + 1
  8376. break
  8377. }
  8378. case 'binary': {
  8379. if (value && value === null) {
  8380. stream.emit('error', new Error('Invalid ' + name))
  8381. return false
  8382. }
  8383. length += 1 + Buffer.byteLength(value) + 2
  8384. break
  8385. }
  8386. case 'int16': {
  8387. if (typeof value !== 'number') {
  8388. stream.emit('error', new Error('Invalid ' + name))
  8389. return false
  8390. }
  8391. length += 1 + 2
  8392. break
  8393. }
  8394. case 'int32': {
  8395. if (typeof value !== 'number') {
  8396. stream.emit('error', new Error('Invalid ' + name))
  8397. return false
  8398. }
  8399. length += 1 + 4
  8400. break
  8401. }
  8402. case 'var': {
  8403. if (typeof value !== 'number') {
  8404. stream.emit('error', new Error('Invalid ' + name))
  8405. return false
  8406. }
  8407. length += 1 + genBufVariableByteInt(value).length
  8408. break
  8409. }
  8410. case 'string': {
  8411. if (typeof value !== 'string') {
  8412. stream.emit('error', new Error('Invalid ' + name))
  8413. return false
  8414. }
  8415. length += 1 + 2 + Buffer.byteLength(value.toString())
  8416. break
  8417. }
  8418. case 'pair': {
  8419. if (typeof value !== 'object') {
  8420. stream.emit('error', new Error('Invalid ' + name))
  8421. return false
  8422. }
  8423. length += Object.getOwnPropertyNames(value).reduce(function(result,
  8424. name) {
  8425. result += 1 + 2 + Buffer.byteLength(name.toString()) + 2 +
  8426. Buffer.byteLength(value[name].toString())
  8427. return result
  8428. }, 0)
  8429. break
  8430. }
  8431. default: {
  8432. stream.emit('error', new Error('Invalid property ' + name))
  8433. return false
  8434. }
  8435. }
  8436. return length
  8437. }
  8438. if (properties) {
  8439. for (var propName in properties) {
  8440. var propLength = getLengthProperty(propName)
  8441. if (!propLength) return false
  8442. propertiesLength += propLength
  8443. }
  8444. }
  8445. var propertiesLengthLength = genBufVariableByteInt(propertiesLength).length
  8446. return {
  8447. length: propertiesLengthLength + propertiesLength,
  8448. write: function() {
  8449. writeProperties(stream, properties, propertiesLength)
  8450. }
  8451. }
  8452. }
  8453. function getPropertiesByMaximumPacketSize(stream, properties, opts, length) {
  8454. var mayEmptyProps = ['reasonString', 'userProperties']
  8455. var maximumPacketSize = opts && opts.properties && opts.properties
  8456. .maximumPacketSize ? opts.properties.maximumPacketSize : 0
  8457. var propertiesData = getProperties(stream, properties)
  8458. if (maximumPacketSize) {
  8459. while (length + propertiesData.length > maximumPacketSize) {
  8460. var currentMayEmptyProp = mayEmptyProps.shift()
  8461. if (currentMayEmptyProp && properties[currentMayEmptyProp]) {
  8462. delete properties[currentMayEmptyProp]
  8463. propertiesData = getProperties(stream, properties)
  8464. } else {
  8465. return false
  8466. }
  8467. }
  8468. }
  8469. return propertiesData
  8470. }
  8471. function writeProperties(stream, properties, propertiesLength) {
  8472. /* write properties to stream */
  8473. writeVarByteInt(stream, propertiesLength)
  8474. for (var propName in properties) {
  8475. if (properties.hasOwnProperty(propName) && properties[propName] !== null) {
  8476. var value = properties[propName]
  8477. var type = protocol.propertiesTypes[propName]
  8478. switch (type) {
  8479. case 'byte': {
  8480. stream.write(Buffer.from([protocol.properties[propName]]))
  8481. stream.write(Buffer.from([+value]))
  8482. break
  8483. }
  8484. case 'int8': {
  8485. stream.write(Buffer.from([protocol.properties[propName]]))
  8486. stream.write(Buffer.from([value]))
  8487. break
  8488. }
  8489. case 'binary': {
  8490. stream.write(Buffer.from([protocol.properties[propName]]))
  8491. writeStringOrBuffer(stream, value)
  8492. break
  8493. }
  8494. case 'int16': {
  8495. stream.write(Buffer.from([protocol.properties[propName]]))
  8496. writeNumber(stream, value)
  8497. break
  8498. }
  8499. case 'int32': {
  8500. stream.write(Buffer.from([protocol.properties[propName]]))
  8501. write4ByteNumber(stream, value)
  8502. break
  8503. }
  8504. case 'var': {
  8505. stream.write(Buffer.from([protocol.properties[propName]]))
  8506. writeVarByteInt(stream, value)
  8507. break
  8508. }
  8509. case 'string': {
  8510. stream.write(Buffer.from([protocol.properties[propName]]))
  8511. writeString(stream, value)
  8512. break
  8513. }
  8514. case 'pair': {
  8515. Object.getOwnPropertyNames(value).forEach(function(name) {
  8516. stream.write(Buffer.from([protocol.properties[
  8517. propName]]))
  8518. writeStringPair(stream, name.toString(), value[name]
  8519. .toString())
  8520. })
  8521. break
  8522. }
  8523. default: {
  8524. stream.emit('error', new Error('Invalid property ' + propName))
  8525. return false
  8526. }
  8527. }
  8528. }
  8529. }
  8530. }
  8531. function byteLength(bufOrString) {
  8532. if (!bufOrString) return 0
  8533. else if (bufOrString instanceof Buffer) return bufOrString.length
  8534. else return Buffer.byteLength(bufOrString)
  8535. }
  8536. function isStringOrBuffer(field) {
  8537. return typeof field === 'string' || field instanceof Buffer
  8538. }
  8539. module.exports = generate
  8540. }, {
  8541. "./constants": 82,
  8542. "./numbers": 86,
  8543. "process-nextick-args": 91,
  8544. "safe-buffer": 110
  8545. }],
  8546. 90: [function(require, module, exports) {
  8547. var wrappy = require('wrappy')
  8548. module.exports = wrappy(once)
  8549. module.exports.strict = wrappy(onceStrict)
  8550. once.proto = once(function() {
  8551. Object.defineProperty(Function.prototype, 'once', {
  8552. value: function() {
  8553. return once(this)
  8554. },
  8555. configurable: true
  8556. })
  8557. Object.defineProperty(Function.prototype, 'onceStrict', {
  8558. value: function() {
  8559. return onceStrict(this)
  8560. },
  8561. configurable: true
  8562. })
  8563. })
  8564. function once(fn) {
  8565. var f = function() {
  8566. if (f.called) return f.value
  8567. f.called = true
  8568. return f.value = fn.apply(this, arguments)
  8569. }
  8570. f.called = false
  8571. return f
  8572. }
  8573. function onceStrict(fn) {
  8574. var f = function() {
  8575. if (f.called)
  8576. throw new Error(f.onceError)
  8577. f.called = true
  8578. return f.value = fn.apply(this, arguments)
  8579. }
  8580. var name = fn.name || 'Function wrapped with `once`'
  8581. f.onceError = name + " shouldn't be called more than once"
  8582. f.called = false
  8583. return f
  8584. }
  8585. }, {
  8586. "wrappy": 120
  8587. }],
  8588. 91: [function(require, module, exports) {
  8589. (function(process) {
  8590. 'use strict';
  8591. if (!process.version ||
  8592. process.version.indexOf('v0.') === 0 ||
  8593. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !==
  8594. 0) {
  8595. module.exports = {
  8596. nextTick: nextTick
  8597. };
  8598. } else {
  8599. module.exports = process
  8600. }
  8601. function nextTick(fn, arg1, arg2, arg3) {
  8602. if (typeof fn !== 'function') {
  8603. throw new TypeError('"callback" argument must be a function');
  8604. }
  8605. var len = arguments.length;
  8606. var args, i;
  8607. switch (len) {
  8608. case 0:
  8609. case 1:
  8610. return process.nextTick(fn);
  8611. case 2:
  8612. return process.nextTick(function afterTickOne() {
  8613. fn.call(null, arg1);
  8614. });
  8615. case 3:
  8616. return process.nextTick(function afterTickTwo() {
  8617. fn.call(null, arg1, arg2);
  8618. });
  8619. case 4:
  8620. return process.nextTick(function afterTickThree() {
  8621. fn.call(null, arg1, arg2, arg3);
  8622. });
  8623. default:
  8624. args = new Array(len - 1);
  8625. i = 0;
  8626. while (i < args.length) {
  8627. args[i++] = arguments[i];
  8628. }
  8629. return process.nextTick(function afterTick() {
  8630. fn.apply(null, args);
  8631. });
  8632. }
  8633. }
  8634. }).call(this, require('_process'))
  8635. }, {
  8636. "_process": 92
  8637. }],
  8638. 92: [function(require, module, exports) {
  8639. // shim for using process in browser
  8640. var process = module.exports = {};
  8641. // cached from whatever global is present so that test runners that stub it
  8642. // don't break things. But we need to wrap it in a try catch in case it is
  8643. // wrapped in strict mode code which doesn't define any globals. It's inside a
  8644. // function because try/catches deoptimize in certain engines.
  8645. var cachedSetTimeout;
  8646. var cachedClearTimeout;
  8647. function defaultSetTimout() {
  8648. throw new Error('setTimeout has not been defined');
  8649. }
  8650. function defaultClearTimeout() {
  8651. throw new Error('clearTimeout has not been defined');
  8652. }
  8653. (function() {
  8654. try {
  8655. if (typeof setTimeout === 'function') {
  8656. cachedSetTimeout = setTimeout;
  8657. } else {
  8658. cachedSetTimeout = defaultSetTimout;
  8659. }
  8660. } catch (e) {
  8661. cachedSetTimeout = defaultSetTimout;
  8662. }
  8663. try {
  8664. if (typeof clearTimeout === 'function') {
  8665. cachedClearTimeout = clearTimeout;
  8666. } else {
  8667. cachedClearTimeout = defaultClearTimeout;
  8668. }
  8669. } catch (e) {
  8670. cachedClearTimeout = defaultClearTimeout;
  8671. }
  8672. }())
  8673. function runTimeout(fun) {
  8674. if (cachedSetTimeout === setTimeout) {
  8675. //normal enviroments in sane situations
  8676. return setTimeout(fun, 0);
  8677. }
  8678. // if setTimeout wasn't available but was latter defined
  8679. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  8680. cachedSetTimeout = setTimeout;
  8681. return setTimeout(fun, 0);
  8682. }
  8683. try {
  8684. // when when somebody has screwed with setTimeout but no I.E. maddness
  8685. return cachedSetTimeout(fun, 0);
  8686. } catch (e) {
  8687. try {
  8688. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  8689. return cachedSetTimeout.call(null, fun, 0);
  8690. } catch (e) {
  8691. // 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
  8692. return cachedSetTimeout.call(this, fun, 0);
  8693. }
  8694. }
  8695. }
  8696. function runClearTimeout(marker) {
  8697. if (cachedClearTimeout === clearTimeout) {
  8698. //normal enviroments in sane situations
  8699. return clearTimeout(marker);
  8700. }
  8701. // if clearTimeout wasn't available but was latter defined
  8702. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) &&
  8703. clearTimeout) {
  8704. cachedClearTimeout = clearTimeout;
  8705. return clearTimeout(marker);
  8706. }
  8707. try {
  8708. // when when somebody has screwed with setTimeout but no I.E. maddness
  8709. return cachedClearTimeout(marker);
  8710. } catch (e) {
  8711. try {
  8712. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  8713. return cachedClearTimeout.call(null, marker);
  8714. } catch (e) {
  8715. // 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.
  8716. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  8717. return cachedClearTimeout.call(this, marker);
  8718. }
  8719. }
  8720. }
  8721. var queue = [];
  8722. var draining = false;
  8723. var currentQueue;
  8724. var queueIndex = -1;
  8725. function cleanUpNextTick() {
  8726. if (!draining || !currentQueue) {
  8727. return;
  8728. }
  8729. draining = false;
  8730. if (currentQueue.length) {
  8731. queue = currentQueue.concat(queue);
  8732. } else {
  8733. queueIndex = -1;
  8734. }
  8735. if (queue.length) {
  8736. drainQueue();
  8737. }
  8738. }
  8739. function drainQueue() {
  8740. if (draining) {
  8741. return;
  8742. }
  8743. var timeout = runTimeout(cleanUpNextTick);
  8744. draining = true;
  8745. var len = queue.length;
  8746. while (len) {
  8747. currentQueue = queue;
  8748. queue = [];
  8749. while (++queueIndex < len) {
  8750. if (currentQueue) {
  8751. currentQueue[queueIndex].run();
  8752. }
  8753. }
  8754. queueIndex = -1;
  8755. len = queue.length;
  8756. }
  8757. currentQueue = null;
  8758. draining = false;
  8759. runClearTimeout(timeout);
  8760. }
  8761. process.nextTick = function(fun) {
  8762. var args = new Array(arguments.length - 1);
  8763. if (arguments.length > 1) {
  8764. for (var i = 1; i < arguments.length; i++) {
  8765. args[i - 1] = arguments[i];
  8766. }
  8767. }
  8768. queue.push(new Item(fun, args));
  8769. if (queue.length === 1 && !draining) {
  8770. runTimeout(drainQueue);
  8771. }
  8772. };
  8773. // v8 likes predictible objects
  8774. function Item(fun, array) {
  8775. this.fun = fun;
  8776. this.array = array;
  8777. }
  8778. Item.prototype.run = function() {
  8779. this.fun.apply(null, this.array);
  8780. };
  8781. process.title = 'browser';
  8782. process.browser = true;
  8783. process.env = {};
  8784. process.argv = [];
  8785. process.version = ''; // empty string to avoid regexp issues
  8786. process.versions = {};
  8787. function noop() {}
  8788. process.on = noop;
  8789. process.addListener = noop;
  8790. process.once = noop;
  8791. process.off = noop;
  8792. process.removeListener = noop;
  8793. process.removeAllListeners = noop;
  8794. process.emit = noop;
  8795. process.prependListener = noop;
  8796. process.prependOnceListener = noop;
  8797. process.listeners = function(name) {
  8798. return []
  8799. }
  8800. process.binding = function(name) {
  8801. throw new Error('process.binding is not supported');
  8802. };
  8803. process.cwd = function() {
  8804. return '/'
  8805. };
  8806. process.chdir = function(dir) {
  8807. throw new Error('process.chdir is not supported');
  8808. };
  8809. process.umask = function() {
  8810. return 0;
  8811. };
  8812. }, {}],
  8813. 93: [function(require, module, exports) {
  8814. (function(global) {
  8815. /*! https://mths.be/punycode v1.4.1 by @mathias */
  8816. ;
  8817. (function(root) {
  8818. /** Detect free variables */
  8819. var freeExports = typeof exports == 'object' && exports &&
  8820. !exports.nodeType && exports;
  8821. var freeModule = typeof module == 'object' && module &&
  8822. !module.nodeType && module;
  8823. var freeGlobal = typeof global == 'object' && global;
  8824. if (
  8825. freeGlobal.global === freeGlobal ||
  8826. freeGlobal.window === freeGlobal ||
  8827. freeGlobal.self === freeGlobal
  8828. ) {
  8829. root = freeGlobal;
  8830. }
  8831. /**
  8832. * The `punycode` object.
  8833. * @name punycode
  8834. * @type Object
  8835. */
  8836. var punycode,
  8837. /** Highest positive signed 32-bit float value */
  8838. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  8839. /** Bootstring parameters */
  8840. base = 36,
  8841. tMin = 1,
  8842. tMax = 26,
  8843. skew = 38,
  8844. damp = 700,
  8845. initialBias = 72,
  8846. initialN = 128, // 0x80
  8847. delimiter = '-', // '\x2D'
  8848. /** Regular expressions */
  8849. regexPunycode = /^xn--/,
  8850. regexNonASCII =
  8851. /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  8852. regexSeparators =
  8853. /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  8854. /** Error messages */
  8855. errors = {
  8856. 'overflow': 'Overflow: input needs wider integers to process',
  8857. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  8858. 'invalid-input': 'Invalid input'
  8859. },
  8860. /** Convenience shortcuts */
  8861. baseMinusTMin = base - tMin,
  8862. floor = Math.floor,
  8863. stringFromCharCode = String.fromCharCode,
  8864. /** Temporary variable */
  8865. key;
  8866. /*--------------------------------------------------------------------------*/
  8867. /**
  8868. * A generic error utility function.
  8869. * @private
  8870. * @param {String} type The error type.
  8871. * @returns {Error} Throws a `RangeError` with the applicable error message.
  8872. */
  8873. function error(type) {
  8874. throw new RangeError(errors[type]);
  8875. }
  8876. /**
  8877. * A generic `Array#map` utility function.
  8878. * @private
  8879. * @param {Array} array The array to iterate over.
  8880. * @param {Function} callback The function that gets called for every array
  8881. * item.
  8882. * @returns {Array} A new array of values returned by the callback function.
  8883. */
  8884. function map(array, fn) {
  8885. var length = array.length;
  8886. var result = [];
  8887. while (length--) {
  8888. result[length] = fn(array[length]);
  8889. }
  8890. return result;
  8891. }
  8892. /**
  8893. * A simple `Array#map`-like wrapper to work with domain name strings or email
  8894. * addresses.
  8895. * @private
  8896. * @param {String} domain The domain name or email address.
  8897. * @param {Function} callback The function that gets called for every
  8898. * character.
  8899. * @returns {Array} A new string of characters returned by the callback
  8900. * function.
  8901. */
  8902. function mapDomain(string, fn) {
  8903. var parts = string.split('@');
  8904. var result = '';
  8905. if (parts.length > 1) {
  8906. // In email addresses, only the domain name should be punycoded. Leave
  8907. // the local part (i.e. everything up to `@`) intact.
  8908. result = parts[0] + '@';
  8909. string = parts[1];
  8910. }
  8911. // Avoid `split(regex)` for IE8 compatibility. See #17.
  8912. string = string.replace(regexSeparators, '\x2E');
  8913. var labels = string.split('.');
  8914. var encoded = map(labels, fn).join('.');
  8915. return result + encoded;
  8916. }
  8917. /**
  8918. * Creates an array containing the numeric code points of each Unicode
  8919. * character in the string. While JavaScript uses UCS-2 internally,
  8920. * this function will convert a pair of surrogate halves (each of which
  8921. * UCS-2 exposes as separate characters) into a single code point,
  8922. * matching UTF-16.
  8923. * @see `punycode.ucs2.encode`
  8924. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  8925. * @memberOf punycode.ucs2
  8926. * @name decode
  8927. * @param {String} string The Unicode input string (UCS-2).
  8928. * @returns {Array} The new array of code points.
  8929. */
  8930. function ucs2decode(string) {
  8931. var output = [],
  8932. counter = 0,
  8933. length = string.length,
  8934. value,
  8935. extra;
  8936. while (counter < length) {
  8937. value = string.charCodeAt(counter++);
  8938. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  8939. // high surrogate, and there is a next character
  8940. extra = string.charCodeAt(counter++);
  8941. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  8942. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) +
  8943. 0x10000);
  8944. } else {
  8945. // unmatched surrogate; only append this code unit, in case the next
  8946. // code unit is the high surrogate of a surrogate pair
  8947. output.push(value);
  8948. counter--;
  8949. }
  8950. } else {
  8951. output.push(value);
  8952. }
  8953. }
  8954. return output;
  8955. }
  8956. /**
  8957. * Creates a string based on an array of numeric code points.
  8958. * @see `punycode.ucs2.decode`
  8959. * @memberOf punycode.ucs2
  8960. * @name encode
  8961. * @param {Array} codePoints The array of numeric code points.
  8962. * @returns {String} The new Unicode string (UCS-2).
  8963. */
  8964. function ucs2encode(array) {
  8965. return map(array, function(value) {
  8966. var output = '';
  8967. if (value > 0xFFFF) {
  8968. value -= 0x10000;
  8969. output += stringFromCharCode(value >>> 10 & 0x3FF |
  8970. 0xD800);
  8971. value = 0xDC00 | value & 0x3FF;
  8972. }
  8973. output += stringFromCharCode(value);
  8974. return output;
  8975. }).join('');
  8976. }
  8977. /**
  8978. * Converts a basic code point into a digit/integer.
  8979. * @see `digitToBasic()`
  8980. * @private
  8981. * @param {Number} codePoint The basic numeric code point value.
  8982. * @returns {Number} The numeric value of a basic code point (for use in
  8983. * representing integers) in the range `0` to `base - 1`, or `base` if
  8984. * the code point does not represent a value.
  8985. */
  8986. function basicToDigit(codePoint) {
  8987. if (codePoint - 48 < 10) {
  8988. return codePoint - 22;
  8989. }
  8990. if (codePoint - 65 < 26) {
  8991. return codePoint - 65;
  8992. }
  8993. if (codePoint - 97 < 26) {
  8994. return codePoint - 97;
  8995. }
  8996. return base;
  8997. }
  8998. /**
  8999. * Converts a digit/integer into a basic code point.
  9000. * @see `basicToDigit()`
  9001. * @private
  9002. * @param {Number} digit The numeric value of a basic code point.
  9003. * @returns {Number} The basic code point whose value (when used for
  9004. * representing integers) is `digit`, which needs to be in the range
  9005. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  9006. * used; else, the lowercase form is used. The behavior is undefined
  9007. * if `flag` is non-zero and `digit` has no uppercase form.
  9008. */
  9009. function digitToBasic(digit, flag) {
  9010. // 0..25 map to ASCII a..z or A..Z
  9011. // 26..35 map to ASCII 0..9
  9012. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  9013. }
  9014. /**
  9015. * Bias adaptation function as per section 3.4 of RFC 3492.
  9016. * https://tools.ietf.org/html/rfc3492#section-3.4
  9017. * @private
  9018. */
  9019. function adapt(delta, numPoints, firstTime) {
  9020. var k = 0;
  9021. delta = firstTime ? floor(delta / damp) : delta >> 1;
  9022. delta += floor(delta / numPoints);
  9023. for ( /* no initialization */ ; delta > baseMinusTMin * tMax >>
  9024. 1; k += base) {
  9025. delta = floor(delta / baseMinusTMin);
  9026. }
  9027. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  9028. }
  9029. /**
  9030. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  9031. * symbols.
  9032. * @memberOf punycode
  9033. * @param {String} input The Punycode string of ASCII-only symbols.
  9034. * @returns {String} The resulting string of Unicode symbols.
  9035. */
  9036. function decode(input) {
  9037. // Don't use UCS-2
  9038. var output = [],
  9039. inputLength = input.length,
  9040. out,
  9041. i = 0,
  9042. n = initialN,
  9043. bias = initialBias,
  9044. basic,
  9045. j,
  9046. index,
  9047. oldi,
  9048. w,
  9049. k,
  9050. digit,
  9051. t,
  9052. /** Cached calculation results */
  9053. baseMinusT;
  9054. // Handle the basic code points: let `basic` be the number of input code
  9055. // points before the last delimiter, or `0` if there is none, then copy
  9056. // the first basic code points to the output.
  9057. basic = input.lastIndexOf(delimiter);
  9058. if (basic < 0) {
  9059. basic = 0;
  9060. }
  9061. for (j = 0; j < basic; ++j) {
  9062. // if it's not a basic code point
  9063. if (input.charCodeAt(j) >= 0x80) {
  9064. error('not-basic');
  9065. }
  9066. output.push(input.charCodeAt(j));
  9067. }
  9068. // Main decoding loop: start just after the last delimiter if any basic code
  9069. // points were copied; start at the beginning otherwise.
  9070. for (index = basic > 0 ? basic + 1 : 0; index <
  9071. inputLength; /* no final expression */ ) {
  9072. // `index` is the index of the next character to be consumed.
  9073. // Decode a generalized variable-length integer into `delta`,
  9074. // which gets added to `i`. The overflow checking is easier
  9075. // if we increase `i` as we go, then subtract off its starting
  9076. // value at the end to obtain `delta`.
  9077. for (oldi = i, w = 1, k = base; /* no condition */ ; k +=
  9078. base) {
  9079. if (index >= inputLength) {
  9080. error('invalid-input');
  9081. }
  9082. digit = basicToDigit(input.charCodeAt(index++));
  9083. if (digit >= base || digit > floor((maxInt - i) / w)) {
  9084. error('overflow');
  9085. }
  9086. i += digit * w;
  9087. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  9088. if (digit < t) {
  9089. break;
  9090. }
  9091. baseMinusT = base - t;
  9092. if (w > floor(maxInt / baseMinusT)) {
  9093. error('overflow');
  9094. }
  9095. w *= baseMinusT;
  9096. }
  9097. out = output.length + 1;
  9098. bias = adapt(i - oldi, out, oldi == 0);
  9099. // `i` was supposed to wrap around from `out` to `0`,
  9100. // incrementing `n` each time, so we'll fix that now:
  9101. if (floor(i / out) > maxInt - n) {
  9102. error('overflow');
  9103. }
  9104. n += floor(i / out);
  9105. i %= out;
  9106. // Insert `n` at position `i` of the output
  9107. output.splice(i++, 0, n);
  9108. }
  9109. return ucs2encode(output);
  9110. }
  9111. /**
  9112. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  9113. * Punycode string of ASCII-only symbols.
  9114. * @memberOf punycode
  9115. * @param {String} input The string of Unicode symbols.
  9116. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  9117. */
  9118. function encode(input) {
  9119. var n,
  9120. delta,
  9121. handledCPCount,
  9122. basicLength,
  9123. bias,
  9124. j,
  9125. m,
  9126. q,
  9127. k,
  9128. t,
  9129. currentValue,
  9130. output = [],
  9131. /** `inputLength` will hold the number of code points in `input`. */
  9132. inputLength,
  9133. /** Cached calculation results */
  9134. handledCPCountPlusOne,
  9135. baseMinusT,
  9136. qMinusT;
  9137. // Convert the input in UCS-2 to Unicode
  9138. input = ucs2decode(input);
  9139. // Cache the length
  9140. inputLength = input.length;
  9141. // Initialize the state
  9142. n = initialN;
  9143. delta = 0;
  9144. bias = initialBias;
  9145. // Handle the basic code points
  9146. for (j = 0; j < inputLength; ++j) {
  9147. currentValue = input[j];
  9148. if (currentValue < 0x80) {
  9149. output.push(stringFromCharCode(currentValue));
  9150. }
  9151. }
  9152. handledCPCount = basicLength = output.length;
  9153. // `handledCPCount` is the number of code points that have been handled;
  9154. // `basicLength` is the number of basic code points.
  9155. // Finish the basic string - if it is not empty - with a delimiter
  9156. if (basicLength) {
  9157. output.push(delimiter);
  9158. }
  9159. // Main encoding loop:
  9160. while (handledCPCount < inputLength) {
  9161. // All non-basic code points < n have been handled already. Find the next
  9162. // larger one:
  9163. for (m = maxInt, j = 0; j < inputLength; ++j) {
  9164. currentValue = input[j];
  9165. if (currentValue >= n && currentValue < m) {
  9166. m = currentValue;
  9167. }
  9168. }
  9169. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  9170. // but guard against overflow
  9171. handledCPCountPlusOne = handledCPCount + 1;
  9172. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  9173. error('overflow');
  9174. }
  9175. delta += (m - n) * handledCPCountPlusOne;
  9176. n = m;
  9177. for (j = 0; j < inputLength; ++j) {
  9178. currentValue = input[j];
  9179. if (currentValue < n && ++delta > maxInt) {
  9180. error('overflow');
  9181. }
  9182. if (currentValue == n) {
  9183. // Represent delta as a generalized variable-length integer
  9184. for (q = delta, k = base; /* no condition */ ; k +=
  9185. base) {
  9186. t = k <= bias ? tMin : (k >= bias + tMax ? tMax :
  9187. k - bias);
  9188. if (q < t) {
  9189. break;
  9190. }
  9191. qMinusT = q - t;
  9192. baseMinusT = base - t;
  9193. output.push(
  9194. stringFromCharCode(digitToBasic(t +
  9195. qMinusT % baseMinusT, 0))
  9196. );
  9197. q = floor(qMinusT / baseMinusT);
  9198. }
  9199. output.push(stringFromCharCode(digitToBasic(q, 0)));
  9200. bias = adapt(delta, handledCPCountPlusOne,
  9201. handledCPCount == basicLength);
  9202. delta = 0;
  9203. ++handledCPCount;
  9204. }
  9205. }
  9206. ++delta;
  9207. ++n;
  9208. }
  9209. return output.join('');
  9210. }
  9211. /**
  9212. * Converts a Punycode string representing a domain name or an email address
  9213. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  9214. * it doesn't matter if you call it on a string that has already been
  9215. * converted to Unicode.
  9216. * @memberOf punycode
  9217. * @param {String} input The Punycoded domain name or email address to
  9218. * convert to Unicode.
  9219. * @returns {String} The Unicode representation of the given Punycode
  9220. * string.
  9221. */
  9222. function toUnicode(input) {
  9223. return mapDomain(input, function(string) {
  9224. return regexPunycode.test(string) ?
  9225. decode(string.slice(4).toLowerCase()) :
  9226. string;
  9227. });
  9228. }
  9229. /**
  9230. * Converts a Unicode string representing a domain name or an email address to
  9231. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  9232. * i.e. it doesn't matter if you call it with a domain that's already in
  9233. * ASCII.
  9234. * @memberOf punycode
  9235. * @param {String} input The domain name or email address to convert, as a
  9236. * Unicode string.
  9237. * @returns {String} The Punycode representation of the given domain name or
  9238. * email address.
  9239. */
  9240. function toASCII(input) {
  9241. return mapDomain(input, function(string) {
  9242. return regexNonASCII.test(string) ?
  9243. 'xn--' + encode(string) :
  9244. string;
  9245. });
  9246. }
  9247. /*--------------------------------------------------------------------------*/
  9248. /** Define the public API */
  9249. punycode = {
  9250. /**
  9251. * A string representing the current Punycode.js version number.
  9252. * @memberOf punycode
  9253. * @type String
  9254. */
  9255. 'version': '1.4.1',
  9256. /**
  9257. * An object of methods to convert from JavaScript's internal character
  9258. * representation (UCS-2) to Unicode code points, and back.
  9259. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  9260. * @memberOf punycode
  9261. * @type Object
  9262. */
  9263. 'ucs2': {
  9264. 'decode': ucs2decode,
  9265. 'encode': ucs2encode
  9266. },
  9267. 'decode': decode,
  9268. 'encode': encode,
  9269. 'toASCII': toASCII,
  9270. 'toUnicode': toUnicode
  9271. };
  9272. /** Expose `punycode` */
  9273. // Some AMD build optimizers, like r.js, check for specific condition patterns
  9274. // like the following:
  9275. if (
  9276. typeof define == 'function' &&
  9277. typeof define.amd == 'object' &&
  9278. define.amd
  9279. ) {
  9280. define('punycode', function() {
  9281. return punycode;
  9282. });
  9283. } else if (freeExports && freeModule) {
  9284. if (module.exports == freeExports) {
  9285. // in Node.js, io.js, or RingoJS v0.8.0+
  9286. freeModule.exports = punycode;
  9287. } else {
  9288. // in Narwhal or RingoJS v0.7.0-
  9289. for (key in punycode) {
  9290. punycode.hasOwnProperty(key) && (freeExports[key] =
  9291. punycode[key]);
  9292. }
  9293. }
  9294. } else {
  9295. // in Rhino or a web browser
  9296. root.punycode = punycode;
  9297. }
  9298. }(this));
  9299. }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ?
  9300. self : typeof window !== "undefined" ? window : {})
  9301. }, {}],
  9302. 94: [function(require, module, exports) {
  9303. // Copyright Joyent, Inc. and other Node contributors.
  9304. //
  9305. // Permission is hereby granted, free of charge, to any person obtaining a
  9306. // copy of this software and associated documentation files (the
  9307. // "Software"), to deal in the Software without restriction, including
  9308. // without limitation the rights to use, copy, modify, merge, publish,
  9309. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9310. // persons to whom the Software is furnished to do so, subject to the
  9311. // following conditions:
  9312. //
  9313. // The above copyright notice and this permission notice shall be included
  9314. // in all copies or substantial portions of the Software.
  9315. //
  9316. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9317. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9318. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9319. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9320. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9321. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9322. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9323. 'use strict';
  9324. // If obj.hasOwnProperty has been overridden, then calling
  9325. // obj.hasOwnProperty(prop) will break.
  9326. // See: https://github.com/joyent/node/issues/1707
  9327. function hasOwnProperty(obj, prop) {
  9328. return Object.prototype.hasOwnProperty.call(obj, prop);
  9329. }
  9330. module.exports = function(qs, sep, eq, options) {
  9331. sep = sep || '&';
  9332. eq = eq || '=';
  9333. var obj = {};
  9334. if (typeof qs !== 'string' || qs.length === 0) {
  9335. return obj;
  9336. }
  9337. var regexp = /\+/g;
  9338. qs = qs.split(sep);
  9339. var maxKeys = 1000;
  9340. if (options && typeof options.maxKeys === 'number') {
  9341. maxKeys = options.maxKeys;
  9342. }
  9343. var len = qs.length;
  9344. // maxKeys <= 0 means that we should not limit keys count
  9345. if (maxKeys > 0 && len > maxKeys) {
  9346. len = maxKeys;
  9347. }
  9348. for (var i = 0; i < len; ++i) {
  9349. var x = qs[i].replace(regexp, '%20'),
  9350. idx = x.indexOf(eq),
  9351. kstr, vstr, k, v;
  9352. if (idx >= 0) {
  9353. kstr = x.substr(0, idx);
  9354. vstr = x.substr(idx + 1);
  9355. } else {
  9356. kstr = x;
  9357. vstr = '';
  9358. }
  9359. k = decodeURIComponent(kstr);
  9360. v = decodeURIComponent(vstr);
  9361. if (!hasOwnProperty(obj, k)) {
  9362. obj[k] = v;
  9363. } else if (isArray(obj[k])) {
  9364. obj[k].push(v);
  9365. } else {
  9366. obj[k] = [obj[k], v];
  9367. }
  9368. }
  9369. return obj;
  9370. };
  9371. var isArray = Array.isArray || function(xs) {
  9372. return Object.prototype.toString.call(xs) === '[object Array]';
  9373. };
  9374. }, {}],
  9375. 95: [function(require, module, exports) {
  9376. // Copyright Joyent, Inc. and other Node contributors.
  9377. //
  9378. // Permission is hereby granted, free of charge, to any person obtaining a
  9379. // copy of this software and associated documentation files (the
  9380. // "Software"), to deal in the Software without restriction, including
  9381. // without limitation the rights to use, copy, modify, merge, publish,
  9382. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9383. // persons to whom the Software is furnished to do so, subject to the
  9384. // following conditions:
  9385. //
  9386. // The above copyright notice and this permission notice shall be included
  9387. // in all copies or substantial portions of the Software.
  9388. //
  9389. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9390. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9391. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9392. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9393. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9394. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9395. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9396. 'use strict';
  9397. var stringifyPrimitive = function(v) {
  9398. switch (typeof v) {
  9399. case 'string':
  9400. return v;
  9401. case 'boolean':
  9402. return v ? 'true' : 'false';
  9403. case 'number':
  9404. return isFinite(v) ? v : '';
  9405. default:
  9406. return '';
  9407. }
  9408. };
  9409. module.exports = function(obj, sep, eq, name) {
  9410. sep = sep || '&';
  9411. eq = eq || '=';
  9412. if (obj === null) {
  9413. obj = undefined;
  9414. }
  9415. if (typeof obj === 'object') {
  9416. return map(objectKeys(obj), function(k) {
  9417. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  9418. if (isArray(obj[k])) {
  9419. return map(obj[k], function(v) {
  9420. return ks + encodeURIComponent(
  9421. stringifyPrimitive(v));
  9422. }).join(sep);
  9423. } else {
  9424. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  9425. }
  9426. }).join(sep);
  9427. }
  9428. if (!name) return '';
  9429. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  9430. encodeURIComponent(stringifyPrimitive(obj));
  9431. };
  9432. var isArray = Array.isArray || function(xs) {
  9433. return Object.prototype.toString.call(xs) === '[object Array]';
  9434. };
  9435. function map(xs, f) {
  9436. if (xs.map) return xs.map(f);
  9437. var res = [];
  9438. for (var i = 0; i < xs.length; i++) {
  9439. res.push(f(xs[i], i));
  9440. }
  9441. return res;
  9442. }
  9443. var objectKeys = Object.keys || function(obj) {
  9444. var res = [];
  9445. for (var key in obj) {
  9446. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  9447. }
  9448. return res;
  9449. };
  9450. }, {}],
  9451. 96: [function(require, module, exports) {
  9452. 'use strict';
  9453. exports.decode = exports.parse = require('./decode');
  9454. exports.encode = exports.stringify = require('./encode');
  9455. }, {
  9456. "./decode": 94,
  9457. "./encode": 95
  9458. }],
  9459. 97: [function(require, module, exports) {
  9460. module.exports = require('./lib/_stream_duplex.js');
  9461. }, {
  9462. "./lib/_stream_duplex.js": 98
  9463. }],
  9464. 98: [function(require, module, exports) {
  9465. // Copyright Joyent, Inc. and other Node contributors.
  9466. //
  9467. // Permission is hereby granted, free of charge, to any person obtaining a
  9468. // copy of this software and associated documentation files (the
  9469. // "Software"), to deal in the Software without restriction, including
  9470. // without limitation the rights to use, copy, modify, merge, publish,
  9471. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9472. // persons to whom the Software is furnished to do so, subject to the
  9473. // following conditions:
  9474. //
  9475. // The above copyright notice and this permission notice shall be included
  9476. // in all copies or substantial portions of the Software.
  9477. //
  9478. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9479. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9480. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9481. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9482. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9483. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9484. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9485. // a duplex stream is just a stream that is both readable and writable.
  9486. // Since JS doesn't have multiple prototypal inheritance, this class
  9487. // prototypally inherits from Readable, and then parasitically from
  9488. // Writable.
  9489. 'use strict';
  9490. /*<replacement>*/
  9491. var pna = require('process-nextick-args');
  9492. /*</replacement>*/
  9493. /*<replacement>*/
  9494. var objectKeys = Object.keys || function(obj) {
  9495. var keys = [];
  9496. for (var key in obj) {
  9497. keys.push(key);
  9498. }
  9499. return keys;
  9500. };
  9501. /*</replacement>*/
  9502. module.exports = Duplex;
  9503. /*<replacement>*/
  9504. var util = require('core-util-is');
  9505. util.inherits = require('inherits');
  9506. /*</replacement>*/
  9507. var Readable = require('./_stream_readable');
  9508. var Writable = require('./_stream_writable');
  9509. util.inherits(Duplex, Readable);
  9510. {
  9511. // avoid scope creep, the keys array can then be collected
  9512. var keys = objectKeys(Writable.prototype);
  9513. for (var v = 0; v < keys.length; v++) {
  9514. var method = keys[v];
  9515. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[
  9516. method];
  9517. }
  9518. }
  9519. function Duplex(options) {
  9520. if (!(this instanceof Duplex)) return new Duplex(options);
  9521. Readable.call(this, options);
  9522. Writable.call(this, options);
  9523. if (options && options.readable === false) this.readable = false;
  9524. if (options && options.writable === false) this.writable = false;
  9525. this.allowHalfOpen = true;
  9526. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  9527. this.once('end', onend);
  9528. }
  9529. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  9530. // making it explicit this property is not enumerable
  9531. // because otherwise some prototype manipulation in
  9532. // userland will fail
  9533. enumerable: false,
  9534. get: function() {
  9535. return this._writableState.highWaterMark;
  9536. }
  9537. });
  9538. // the no-half-open enforcer
  9539. function onend() {
  9540. // if we allow half-open state, or if the writable side ended,
  9541. // then we're ok.
  9542. if (this.allowHalfOpen || this._writableState.ended) return;
  9543. // no more data can be written.
  9544. // But allow more writes to happen in this tick.
  9545. pna.nextTick(onEndNT, this);
  9546. }
  9547. function onEndNT(self) {
  9548. self.end();
  9549. }
  9550. Object.defineProperty(Duplex.prototype, 'destroyed', {
  9551. get: function() {
  9552. if (this._readableState === undefined || this._writableState ===
  9553. undefined) {
  9554. return false;
  9555. }
  9556. return this._readableState.destroyed && this._writableState
  9557. .destroyed;
  9558. },
  9559. set: function(value) {
  9560. // we ignore the value if the stream
  9561. // has not been initialized yet
  9562. if (this._readableState === undefined || this._writableState ===
  9563. undefined) {
  9564. return;
  9565. }
  9566. // backward compatibility, the user is explicitly
  9567. // managing destroyed
  9568. this._readableState.destroyed = value;
  9569. this._writableState.destroyed = value;
  9570. }
  9571. });
  9572. Duplex.prototype._destroy = function(err, cb) {
  9573. this.push(null);
  9574. this.end();
  9575. pna.nextTick(cb, err);
  9576. };
  9577. }, {
  9578. "./_stream_readable": 100,
  9579. "./_stream_writable": 102,
  9580. "core-util-is": 14,
  9581. "inherits": 80,
  9582. "process-nextick-args": 91
  9583. }],
  9584. 99: [function(require, module, exports) {
  9585. // Copyright Joyent, Inc. and other Node contributors.
  9586. //
  9587. // Permission is hereby granted, free of charge, to any person obtaining a
  9588. // copy of this software and associated documentation files (the
  9589. // "Software"), to deal in the Software without restriction, including
  9590. // without limitation the rights to use, copy, modify, merge, publish,
  9591. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9592. // persons to whom the Software is furnished to do so, subject to the
  9593. // following conditions:
  9594. //
  9595. // The above copyright notice and this permission notice shall be included
  9596. // in all copies or substantial portions of the Software.
  9597. //
  9598. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9599. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9600. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9601. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9602. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9603. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9604. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9605. // a passthrough stream.
  9606. // basically just the most minimal sort of Transform stream.
  9607. // Every written chunk gets output as-is.
  9608. 'use strict';
  9609. module.exports = PassThrough;
  9610. var Transform = require('./_stream_transform');
  9611. /*<replacement>*/
  9612. var util = require('core-util-is');
  9613. util.inherits = require('inherits');
  9614. /*</replacement>*/
  9615. util.inherits(PassThrough, Transform);
  9616. function PassThrough(options) {
  9617. if (!(this instanceof PassThrough)) return new PassThrough(options);
  9618. Transform.call(this, options);
  9619. }
  9620. PassThrough.prototype._transform = function(chunk, encoding, cb) {
  9621. cb(null, chunk);
  9622. };
  9623. }, {
  9624. "./_stream_transform": 101,
  9625. "core-util-is": 14,
  9626. "inherits": 80
  9627. }],
  9628. 100: [function(require, module, exports) {
  9629. (function(process, global) {
  9630. // Copyright Joyent, Inc. and other Node contributors.
  9631. //
  9632. // Permission is hereby granted, free of charge, to any person obtaining a
  9633. // copy of this software and associated documentation files (the
  9634. // "Software"), to deal in the Software without restriction, including
  9635. // without limitation the rights to use, copy, modify, merge, publish,
  9636. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9637. // persons to whom the Software is furnished to do so, subject to the
  9638. // following conditions:
  9639. //
  9640. // The above copyright notice and this permission notice shall be included
  9641. // in all copies or substantial portions of the Software.
  9642. //
  9643. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9644. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9645. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9646. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9647. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9648. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9649. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9650. 'use strict';
  9651. /*<replacement>*/
  9652. var pna = require('process-nextick-args');
  9653. /*</replacement>*/
  9654. module.exports = Readable;
  9655. /*<replacement>*/
  9656. var isArray = require('isarray');
  9657. /*</replacement>*/
  9658. /*<replacement>*/
  9659. var Duplex;
  9660. /*</replacement>*/
  9661. Readable.ReadableState = ReadableState;
  9662. /*<replacement>*/
  9663. var EE = require('events').EventEmitter;
  9664. var EElistenerCount = function(emitter, type) {
  9665. return emitter.listeners(type).length;
  9666. };
  9667. /*</replacement>*/
  9668. /*<replacement>*/
  9669. var Stream = require('./internal/streams/stream');
  9670. /*</replacement>*/
  9671. /*<replacement>*/
  9672. var Buffer = require('safe-buffer').Buffer;
  9673. var OurUint8Array = global.Uint8Array || function() {};
  9674. function _uint8ArrayToBuffer(chunk) {
  9675. return Buffer.from(chunk);
  9676. }
  9677. function _isUint8Array(obj) {
  9678. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  9679. }
  9680. /*</replacement>*/
  9681. /*<replacement>*/
  9682. var util = require('core-util-is');
  9683. util.inherits = require('inherits');
  9684. /*</replacement>*/
  9685. /*<replacement>*/
  9686. var debugUtil = require('util');
  9687. var debug = void 0;
  9688. if (debugUtil && debugUtil.debuglog) {
  9689. debug = debugUtil.debuglog('stream');
  9690. } else {
  9691. debug = function() {};
  9692. }
  9693. /*</replacement>*/
  9694. var BufferList = require('./internal/streams/BufferList');
  9695. var destroyImpl = require('./internal/streams/destroy');
  9696. var StringDecoder;
  9697. util.inherits(Readable, Stream);
  9698. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  9699. function prependListener(emitter, event, fn) {
  9700. // Sadly this is not cacheable as some libraries bundle their own
  9701. // event emitter implementation with them.
  9702. if (typeof emitter.prependListener === 'function') return emitter
  9703. .prependListener(event, fn);
  9704. // This is a hack to make sure that our error handler is attached before any
  9705. // userland ones. NEVER DO THIS. This is here only because this code needs
  9706. // to continue to work with older versions of Node.js that do not include
  9707. // the prependListener() method. The goal is to eventually remove this hack.
  9708. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);
  9709. else if (isArray(emitter._events[event])) emitter._events[event].unshift(
  9710. fn);
  9711. else emitter._events[event] = [fn, emitter._events[event]];
  9712. }
  9713. function ReadableState(options, stream) {
  9714. Duplex = Duplex || require('./_stream_duplex');
  9715. options = options || {};
  9716. // Duplex streams are both readable and writable, but share
  9717. // the same options object.
  9718. // However, some cases require setting options to different
  9719. // values for the readable and the writable sides of the duplex stream.
  9720. // These options can be provided separately as readableXXX and writableXXX.
  9721. var isDuplex = stream instanceof Duplex;
  9722. // object stream flag. Used to make read(n) ignore n and to
  9723. // make all the buffer merging and length checks go away
  9724. this.objectMode = !!options.objectMode;
  9725. if (isDuplex) this.objectMode = this.objectMode || !!options
  9726. .readableObjectMode;
  9727. // the point at which it stops calling _read() to fill the buffer
  9728. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  9729. var hwm = options.highWaterMark;
  9730. var readableHwm = options.readableHighWaterMark;
  9731. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  9732. if (hwm || hwm === 0) this.highWaterMark = hwm;
  9733. else if (isDuplex && (readableHwm || readableHwm === 0)) this
  9734. .highWaterMark = readableHwm;
  9735. else this.highWaterMark = defaultHwm;
  9736. // cast to ints.
  9737. this.highWaterMark = Math.floor(this.highWaterMark);
  9738. // A linked list is used to store data chunks instead of an array because the
  9739. // linked list can remove elements from the beginning faster than
  9740. // array.shift()
  9741. this.buffer = new BufferList();
  9742. this.length = 0;
  9743. this.pipes = null;
  9744. this.pipesCount = 0;
  9745. this.flowing = null;
  9746. this.ended = false;
  9747. this.endEmitted = false;
  9748. this.reading = false;
  9749. // a flag to be able to tell if the event 'readable'/'data' is emitted
  9750. // immediately, or on a later tick. We set this to true at first, because
  9751. // any actions that shouldn't happen until "later" should generally also
  9752. // not happen before the first read call.
  9753. this.sync = true;
  9754. // whenever we return null, then we set a flag to say
  9755. // that we're awaiting a 'readable' event emission.
  9756. this.needReadable = false;
  9757. this.emittedReadable = false;
  9758. this.readableListening = false;
  9759. this.resumeScheduled = false;
  9760. // has it been destroyed
  9761. this.destroyed = false;
  9762. // Crypto is kind of old and crusty. Historically, its default string
  9763. // encoding is 'binary' so we have to make this configurable.
  9764. // Everything else in the universe uses 'utf8', though.
  9765. this.defaultEncoding = options.defaultEncoding || 'utf8';
  9766. // the number of writers that are awaiting a drain event in .pipe()s
  9767. this.awaitDrain = 0;
  9768. // if true, a maybeReadMore has been scheduled
  9769. this.readingMore = false;
  9770. this.decoder = null;
  9771. this.encoding = null;
  9772. if (options.encoding) {
  9773. if (!StringDecoder) StringDecoder = require('string_decoder/')
  9774. .StringDecoder;
  9775. this.decoder = new StringDecoder(options.encoding);
  9776. this.encoding = options.encoding;
  9777. }
  9778. }
  9779. function Readable(options) {
  9780. Duplex = Duplex || require('./_stream_duplex');
  9781. if (!(this instanceof Readable)) return new Readable(options);
  9782. this._readableState = new ReadableState(options, this);
  9783. // legacy
  9784. this.readable = true;
  9785. if (options) {
  9786. if (typeof options.read === 'function') this._read = options.read;
  9787. if (typeof options.destroy === 'function') this._destroy = options
  9788. .destroy;
  9789. }
  9790. Stream.call(this);
  9791. }
  9792. Object.defineProperty(Readable.prototype, 'destroyed', {
  9793. get: function() {
  9794. if (this._readableState === undefined) {
  9795. return false;
  9796. }
  9797. return this._readableState.destroyed;
  9798. },
  9799. set: function(value) {
  9800. // we ignore the value if the stream
  9801. // has not been initialized yet
  9802. if (!this._readableState) {
  9803. return;
  9804. }
  9805. // backward compatibility, the user is explicitly
  9806. // managing destroyed
  9807. this._readableState.destroyed = value;
  9808. }
  9809. });
  9810. Readable.prototype.destroy = destroyImpl.destroy;
  9811. Readable.prototype._undestroy = destroyImpl.undestroy;
  9812. Readable.prototype._destroy = function(err, cb) {
  9813. this.push(null);
  9814. cb(err);
  9815. };
  9816. // Manually shove something into the read() buffer.
  9817. // This returns true if the highWaterMark has not been hit yet,
  9818. // similar to how Writable.write() returns true if you should
  9819. // write() some more.
  9820. Readable.prototype.push = function(chunk, encoding) {
  9821. var state = this._readableState;
  9822. var skipChunkCheck;
  9823. if (!state.objectMode) {
  9824. if (typeof chunk === 'string') {
  9825. encoding = encoding || state.defaultEncoding;
  9826. if (encoding !== state.encoding) {
  9827. chunk = Buffer.from(chunk, encoding);
  9828. encoding = '';
  9829. }
  9830. skipChunkCheck = true;
  9831. }
  9832. } else {
  9833. skipChunkCheck = true;
  9834. }
  9835. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  9836. };
  9837. // Unshift should *always* be something directly out of read()
  9838. Readable.prototype.unshift = function(chunk) {
  9839. return readableAddChunk(this, chunk, null, true, false);
  9840. };
  9841. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  9842. var state = stream._readableState;
  9843. if (chunk === null) {
  9844. state.reading = false;
  9845. onEofChunk(stream, state);
  9846. } else {
  9847. var er;
  9848. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  9849. if (er) {
  9850. stream.emit('error', er);
  9851. } else if (state.objectMode || chunk && chunk.length > 0) {
  9852. if (typeof chunk !== 'string' && !state.objectMode && Object
  9853. .getPrototypeOf(chunk) !== Buffer.prototype) {
  9854. chunk = _uint8ArrayToBuffer(chunk);
  9855. }
  9856. if (addToFront) {
  9857. if (state.endEmitted) stream.emit('error', new Error(
  9858. 'stream.unshift() after end event'));
  9859. else addChunk(stream, state, chunk, true);
  9860. } else if (state.ended) {
  9861. stream.emit('error', new Error('stream.push() after EOF'));
  9862. } else {
  9863. state.reading = false;
  9864. if (state.decoder && !encoding) {
  9865. chunk = state.decoder.write(chunk);
  9866. if (state.objectMode || chunk.length !== 0) addChunk(stream,
  9867. state, chunk, false);
  9868. else maybeReadMore(stream, state);
  9869. } else {
  9870. addChunk(stream, state, chunk, false);
  9871. }
  9872. }
  9873. } else if (!addToFront) {
  9874. state.reading = false;
  9875. }
  9876. }
  9877. return needMoreData(state);
  9878. }
  9879. function addChunk(stream, state, chunk, addToFront) {
  9880. if (state.flowing && state.length === 0 && !state.sync) {
  9881. stream.emit('data', chunk);
  9882. stream.read(0);
  9883. } else {
  9884. // update the buffer info.
  9885. state.length += state.objectMode ? 1 : chunk.length;
  9886. if (addToFront) state.buffer.unshift(chunk);
  9887. else state.buffer.push(chunk);
  9888. if (state.needReadable) emitReadable(stream);
  9889. }
  9890. maybeReadMore(stream, state);
  9891. }
  9892. function chunkInvalid(state, chunk) {
  9893. var er;
  9894. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !==
  9895. undefined && !state.objectMode) {
  9896. er = new TypeError('Invalid non-string/buffer chunk');
  9897. }
  9898. return er;
  9899. }
  9900. // if it's past the high water mark, we can push in some more.
  9901. // Also, if we have no data yet, we can stand some
  9902. // more bytes. This is to work around cases where hwm=0,
  9903. // such as the repl. Also, if the push() triggered a
  9904. // readable event, and the user called read(largeNumber) such that
  9905. // needReadable was set, then we ought to push more, so that another
  9906. // 'readable' event will be triggered.
  9907. function needMoreData(state) {
  9908. return !state.ended && (state.needReadable || state.length < state
  9909. .highWaterMark || state.length === 0);
  9910. }
  9911. Readable.prototype.isPaused = function() {
  9912. return this._readableState.flowing === false;
  9913. };
  9914. // backwards compatibility.
  9915. Readable.prototype.setEncoding = function(enc) {
  9916. if (!StringDecoder) StringDecoder = require('string_decoder/')
  9917. .StringDecoder;
  9918. this._readableState.decoder = new StringDecoder(enc);
  9919. this._readableState.encoding = enc;
  9920. return this;
  9921. };
  9922. // Don't raise the hwm > 8MB
  9923. var MAX_HWM = 0x800000;
  9924. function computeNewHighWaterMark(n) {
  9925. if (n >= MAX_HWM) {
  9926. n = MAX_HWM;
  9927. } else {
  9928. // Get the next highest power of 2 to prevent increasing hwm excessively in
  9929. // tiny amounts
  9930. n--;
  9931. n |= n >>> 1;
  9932. n |= n >>> 2;
  9933. n |= n >>> 4;
  9934. n |= n >>> 8;
  9935. n |= n >>> 16;
  9936. n++;
  9937. }
  9938. return n;
  9939. }
  9940. // This function is designed to be inlinable, so please take care when making
  9941. // changes to the function body.
  9942. function howMuchToRead(n, state) {
  9943. if (n <= 0 || state.length === 0 && state.ended) return 0;
  9944. if (state.objectMode) return 1;
  9945. if (n !== n) {
  9946. // Only flow one buffer at a time
  9947. if (state.flowing && state.length) return state.buffer.head.data.length;
  9948. else return state.length;
  9949. }
  9950. // If we're asking for more than the current hwm, then raise the hwm.
  9951. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(
  9952. n);
  9953. if (n <= state.length) return n;
  9954. // Don't have enough
  9955. if (!state.ended) {
  9956. state.needReadable = true;
  9957. return 0;
  9958. }
  9959. return state.length;
  9960. }
  9961. // you can override either this method, or the async _read(n) below.
  9962. Readable.prototype.read = function(n) {
  9963. debug('read', n);
  9964. n = parseInt(n, 10);
  9965. var state = this._readableState;
  9966. var nOrig = n;
  9967. if (n !== 0) state.emittedReadable = false;
  9968. // if we're doing read(0) to trigger a readable event, but we
  9969. // already have a bunch of data in the buffer, then just trigger
  9970. // the 'readable' event and move on.
  9971. if (n === 0 && state.needReadable && (state.length >= state
  9972. .highWaterMark || state.ended)) {
  9973. debug('read: emitReadable', state.length, state.ended);
  9974. if (state.length === 0 && state.ended) endReadable(this);
  9975. else emitReadable(this);
  9976. return null;
  9977. }
  9978. n = howMuchToRead(n, state);
  9979. // if we've ended, and we're now clear, then finish it up.
  9980. if (n === 0 && state.ended) {
  9981. if (state.length === 0) endReadable(this);
  9982. return null;
  9983. }
  9984. // All the actual chunk generation logic needs to be
  9985. // *below* the call to _read. The reason is that in certain
  9986. // synthetic stream cases, such as passthrough streams, _read
  9987. // may be a completely synchronous operation which may change
  9988. // the state of the read buffer, providing enough data when
  9989. // before there was *not* enough.
  9990. //
  9991. // So, the steps are:
  9992. // 1. Figure out what the state of things will be after we do
  9993. // a read from the buffer.
  9994. //
  9995. // 2. If that resulting state will trigger a _read, then call _read.
  9996. // Note that this may be asynchronous, or synchronous. Yes, it is
  9997. // deeply ugly to write APIs this way, but that still doesn't mean
  9998. // that the Readable class should behave improperly, as streams are
  9999. // designed to be sync/async agnostic.
  10000. // Take note if the _read call is sync or async (ie, if the read call
  10001. // has returned yet), so that we know whether or not it's safe to emit
  10002. // 'readable' etc.
  10003. //
  10004. // 3. Actually pull the requested chunks out of the buffer and return.
  10005. // if we need a readable event, then we need to do some reading.
  10006. var doRead = state.needReadable;
  10007. debug('need readable', doRead);
  10008. // if we currently have less than the highWaterMark, then also read some
  10009. if (state.length === 0 || state.length - n < state.highWaterMark) {
  10010. doRead = true;
  10011. debug('length less than watermark', doRead);
  10012. }
  10013. // however, if we've ended, then there's no point, and if we're already
  10014. // reading, then it's unnecessary.
  10015. if (state.ended || state.reading) {
  10016. doRead = false;
  10017. debug('reading or ended', doRead);
  10018. } else if (doRead) {
  10019. debug('do read');
  10020. state.reading = true;
  10021. state.sync = true;
  10022. // if the length is currently zero, then we *need* a readable event.
  10023. if (state.length === 0) state.needReadable = true;
  10024. // call internal read method
  10025. this._read(state.highWaterMark);
  10026. state.sync = false;
  10027. // If _read pushed data synchronously, then `reading` will be false,
  10028. // and we need to re-evaluate how much data we can return to the user.
  10029. if (!state.reading) n = howMuchToRead(nOrig, state);
  10030. }
  10031. var ret;
  10032. if (n > 0) ret = fromList(n, state);
  10033. else ret = null;
  10034. if (ret === null) {
  10035. state.needReadable = true;
  10036. n = 0;
  10037. } else {
  10038. state.length -= n;
  10039. }
  10040. if (state.length === 0) {
  10041. // If we have nothing in the buffer, then we want to know
  10042. // as soon as we *do* get something into the buffer.
  10043. if (!state.ended) state.needReadable = true;
  10044. // If we tried to read() past the EOF, then emit end on the next tick.
  10045. if (nOrig !== n && state.ended) endReadable(this);
  10046. }
  10047. if (ret !== null) this.emit('data', ret);
  10048. return ret;
  10049. };
  10050. function onEofChunk(stream, state) {
  10051. if (state.ended) return;
  10052. if (state.decoder) {
  10053. var chunk = state.decoder.end();
  10054. if (chunk && chunk.length) {
  10055. state.buffer.push(chunk);
  10056. state.length += state.objectMode ? 1 : chunk.length;
  10057. }
  10058. }
  10059. state.ended = true;
  10060. // emit 'readable' now to make sure it gets picked up.
  10061. emitReadable(stream);
  10062. }
  10063. // Don't emit readable right away in sync mode, because this can trigger
  10064. // another read() call => stack overflow. This way, it might trigger
  10065. // a nextTick recursion warning, but that's not so bad.
  10066. function emitReadable(stream) {
  10067. var state = stream._readableState;
  10068. state.needReadable = false;
  10069. if (!state.emittedReadable) {
  10070. debug('emitReadable', state.flowing);
  10071. state.emittedReadable = true;
  10072. if (state.sync) pna.nextTick(emitReadable_, stream);
  10073. else emitReadable_(stream);
  10074. }
  10075. }
  10076. function emitReadable_(stream) {
  10077. debug('emit readable');
  10078. stream.emit('readable');
  10079. flow(stream);
  10080. }
  10081. // at this point, the user has presumably seen the 'readable' event,
  10082. // and called read() to consume some data. that may have triggered
  10083. // in turn another _read(n) call, in which case reading = true if
  10084. // it's in progress.
  10085. // However, if we're not ended, or reading, and the length < hwm,
  10086. // then go ahead and try to read some more preemptively.
  10087. function maybeReadMore(stream, state) {
  10088. if (!state.readingMore) {
  10089. state.readingMore = true;
  10090. pna.nextTick(maybeReadMore_, stream, state);
  10091. }
  10092. }
  10093. function maybeReadMore_(stream, state) {
  10094. var len = state.length;
  10095. while (!state.reading && !state.flowing && !state.ended && state.length <
  10096. state.highWaterMark) {
  10097. debug('maybeReadMore read 0');
  10098. stream.read(0);
  10099. if (len === state.length)
  10100. // didn't get any data, stop spinning.
  10101. break;
  10102. else len = state.length;
  10103. }
  10104. state.readingMore = false;
  10105. }
  10106. // abstract method. to be overridden in specific implementation classes.
  10107. // call cb(er, data) where data is <= n in length.
  10108. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  10109. // arbitrary, and perhaps not very meaningful.
  10110. Readable.prototype._read = function(n) {
  10111. this.emit('error', new Error('_read() is not implemented'));
  10112. };
  10113. Readable.prototype.pipe = function(dest, pipeOpts) {
  10114. var src = this;
  10115. var state = this._readableState;
  10116. switch (state.pipesCount) {
  10117. case 0:
  10118. state.pipes = dest;
  10119. break;
  10120. case 1:
  10121. state.pipes = [state.pipes, dest];
  10122. break;
  10123. default:
  10124. state.pipes.push(dest);
  10125. break;
  10126. }
  10127. state.pipesCount += 1;
  10128. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  10129. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process
  10130. .stdout && dest !== process.stderr;
  10131. var endFn = doEnd ? onend : unpipe;
  10132. if (state.endEmitted) pna.nextTick(endFn);
  10133. else src.once('end', endFn);
  10134. dest.on('unpipe', onunpipe);
  10135. function onunpipe(readable, unpipeInfo) {
  10136. debug('onunpipe');
  10137. if (readable === src) {
  10138. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  10139. unpipeInfo.hasUnpiped = true;
  10140. cleanup();
  10141. }
  10142. }
  10143. }
  10144. function onend() {
  10145. debug('onend');
  10146. dest.end();
  10147. }
  10148. // when the dest drains, it reduces the awaitDrain counter
  10149. // on the source. This would be more elegant with a .once()
  10150. // handler in flow(), but adding and removing repeatedly is
  10151. // too slow.
  10152. var ondrain = pipeOnDrain(src);
  10153. dest.on('drain', ondrain);
  10154. var cleanedUp = false;
  10155. function cleanup() {
  10156. debug('cleanup');
  10157. // cleanup event handlers once the pipe is broken
  10158. dest.removeListener('close', onclose);
  10159. dest.removeListener('finish', onfinish);
  10160. dest.removeListener('drain', ondrain);
  10161. dest.removeListener('error', onerror);
  10162. dest.removeListener('unpipe', onunpipe);
  10163. src.removeListener('end', onend);
  10164. src.removeListener('end', unpipe);
  10165. src.removeListener('data', ondata);
  10166. cleanedUp = true;
  10167. // if the reader is waiting for a drain event from this
  10168. // specific writer, then it would cause it to never start
  10169. // flowing again.
  10170. // So, if this is awaiting a drain, then we just call it now.
  10171. // If we don't know, then assume that we are waiting for one.
  10172. if (state.awaitDrain && (!dest._writableState || dest._writableState
  10173. .needDrain)) ondrain();
  10174. }
  10175. // If the user pushes more data while we're writing to dest then we'll end up
  10176. // in ondata again. However, we only want to increase awaitDrain once because
  10177. // dest will only emit one 'drain' event for the multiple writes.
  10178. // => Introduce a guard on increasing awaitDrain.
  10179. var increasedAwaitDrain = false;
  10180. src.on('data', ondata);
  10181. function ondata(chunk) {
  10182. debug('ondata');
  10183. increasedAwaitDrain = false;
  10184. var ret = dest.write(chunk);
  10185. if (false === ret && !increasedAwaitDrain) {
  10186. // If the user unpiped during `dest.write()`, it is possible
  10187. // to get stuck in a permanently paused state if that write
  10188. // also returned false.
  10189. // => Check whether `dest` is still a piping destination.
  10190. if ((state.pipesCount === 1 && state.pipes === dest || state
  10191. .pipesCount > 1 && indexOf(state.pipes, dest) !== -1) &&
  10192. !cleanedUp) {
  10193. debug('false write response, pause', src._readableState
  10194. .awaitDrain);
  10195. src._readableState.awaitDrain++;
  10196. increasedAwaitDrain = true;
  10197. }
  10198. src.pause();
  10199. }
  10200. }
  10201. // if the dest has an error, then stop piping into it.
  10202. // however, don't suppress the throwing behavior for this.
  10203. function onerror(er) {
  10204. debug('onerror', er);
  10205. unpipe();
  10206. dest.removeListener('error', onerror);
  10207. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  10208. }
  10209. // Make sure our error handler is attached before userland ones.
  10210. prependListener(dest, 'error', onerror);
  10211. // Both close and finish should trigger unpipe, but only once.
  10212. function onclose() {
  10213. dest.removeListener('finish', onfinish);
  10214. unpipe();
  10215. }
  10216. dest.once('close', onclose);
  10217. function onfinish() {
  10218. debug('onfinish');
  10219. dest.removeListener('close', onclose);
  10220. unpipe();
  10221. }
  10222. dest.once('finish', onfinish);
  10223. function unpipe() {
  10224. debug('unpipe');
  10225. src.unpipe(dest);
  10226. }
  10227. // tell the dest that it's being piped to
  10228. dest.emit('pipe', src);
  10229. // start the flow if it hasn't been started already.
  10230. if (!state.flowing) {
  10231. debug('pipe resume');
  10232. src.resume();
  10233. }
  10234. return dest;
  10235. };
  10236. function pipeOnDrain(src) {
  10237. return function() {
  10238. var state = src._readableState;
  10239. debug('pipeOnDrain', state.awaitDrain);
  10240. if (state.awaitDrain) state.awaitDrain--;
  10241. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  10242. state.flowing = true;
  10243. flow(src);
  10244. }
  10245. };
  10246. }
  10247. Readable.prototype.unpipe = function(dest) {
  10248. var state = this._readableState;
  10249. var unpipeInfo = {
  10250. hasUnpiped: false
  10251. };
  10252. // if we're not piping anywhere, then do nothing.
  10253. if (state.pipesCount === 0) return this;
  10254. // just one destination. most common case.
  10255. if (state.pipesCount === 1) {
  10256. // passed in one, but it's not the right one.
  10257. if (dest && dest !== state.pipes) return this;
  10258. if (!dest) dest = state.pipes;
  10259. // got a match.
  10260. state.pipes = null;
  10261. state.pipesCount = 0;
  10262. state.flowing = false;
  10263. if (dest) dest.emit('unpipe', this, unpipeInfo);
  10264. return this;
  10265. }
  10266. // slow case. multiple pipe destinations.
  10267. if (!dest) {
  10268. // remove all.
  10269. var dests = state.pipes;
  10270. var len = state.pipesCount;
  10271. state.pipes = null;
  10272. state.pipesCount = 0;
  10273. state.flowing = false;
  10274. for (var i = 0; i < len; i++) {
  10275. dests[i].emit('unpipe', this, unpipeInfo);
  10276. }
  10277. return this;
  10278. }
  10279. // try to find the right one.
  10280. var index = indexOf(state.pipes, dest);
  10281. if (index === -1) return this;
  10282. state.pipes.splice(index, 1);
  10283. state.pipesCount -= 1;
  10284. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  10285. dest.emit('unpipe', this, unpipeInfo);
  10286. return this;
  10287. };
  10288. // set up data events if they are asked for
  10289. // Ensure readable listeners eventually get something
  10290. Readable.prototype.on = function(ev, fn) {
  10291. var res = Stream.prototype.on.call(this, ev, fn);
  10292. if (ev === 'data') {
  10293. // Start flowing on next tick if stream isn't explicitly paused
  10294. if (this._readableState.flowing !== false) this.resume();
  10295. } else if (ev === 'readable') {
  10296. var state = this._readableState;
  10297. if (!state.endEmitted && !state.readableListening) {
  10298. state.readableListening = state.needReadable = true;
  10299. state.emittedReadable = false;
  10300. if (!state.reading) {
  10301. pna.nextTick(nReadingNextTick, this);
  10302. } else if (state.length) {
  10303. emitReadable(this);
  10304. }
  10305. }
  10306. }
  10307. return res;
  10308. };
  10309. Readable.prototype.addListener = Readable.prototype.on;
  10310. function nReadingNextTick(self) {
  10311. debug('readable nexttick read 0');
  10312. self.read(0);
  10313. }
  10314. // pause() and resume() are remnants of the legacy readable stream API
  10315. // If the user uses them, then switch into old mode.
  10316. Readable.prototype.resume = function() {
  10317. var state = this._readableState;
  10318. if (!state.flowing) {
  10319. debug('resume');
  10320. state.flowing = true;
  10321. resume(this, state);
  10322. }
  10323. return this;
  10324. };
  10325. function resume(stream, state) {
  10326. if (!state.resumeScheduled) {
  10327. state.resumeScheduled = true;
  10328. pna.nextTick(resume_, stream, state);
  10329. }
  10330. }
  10331. function resume_(stream, state) {
  10332. if (!state.reading) {
  10333. debug('resume read 0');
  10334. stream.read(0);
  10335. }
  10336. state.resumeScheduled = false;
  10337. state.awaitDrain = 0;
  10338. stream.emit('resume');
  10339. flow(stream);
  10340. if (state.flowing && !state.reading) stream.read(0);
  10341. }
  10342. Readable.prototype.pause = function() {
  10343. debug('call pause flowing=%j', this._readableState.flowing);
  10344. if (false !== this._readableState.flowing) {
  10345. debug('pause');
  10346. this._readableState.flowing = false;
  10347. this.emit('pause');
  10348. }
  10349. return this;
  10350. };
  10351. function flow(stream) {
  10352. var state = stream._readableState;
  10353. debug('flow', state.flowing);
  10354. while (state.flowing && stream.read() !== null) {}
  10355. }
  10356. // wrap an old-style stream as the async data source.
  10357. // This is *not* part of the readable stream interface.
  10358. // It is an ugly unfortunate mess of history.
  10359. Readable.prototype.wrap = function(stream) {
  10360. var _this = this;
  10361. var state = this._readableState;
  10362. var paused = false;
  10363. stream.on('end', function() {
  10364. debug('wrapped end');
  10365. if (state.decoder && !state.ended) {
  10366. var chunk = state.decoder.end();
  10367. if (chunk && chunk.length) _this.push(chunk);
  10368. }
  10369. _this.push(null);
  10370. });
  10371. stream.on('data', function(chunk) {
  10372. debug('wrapped data');
  10373. if (state.decoder) chunk = state.decoder.write(chunk);
  10374. // don't skip over falsy values in objectMode
  10375. if (state.objectMode && (chunk === null || chunk ===
  10376. undefined)) return;
  10377. else if (!state.objectMode && (!chunk || !chunk.length))
  10378. return;
  10379. var ret = _this.push(chunk);
  10380. if (!ret) {
  10381. paused = true;
  10382. stream.pause();
  10383. }
  10384. });
  10385. // proxy all the other methods.
  10386. // important when wrapping filters and duplexes.
  10387. for (var i in stream) {
  10388. if (this[i] === undefined && typeof stream[i] === 'function') {
  10389. this[i] = function(method) {
  10390. return function() {
  10391. return stream[method].apply(stream, arguments);
  10392. };
  10393. }(i);
  10394. }
  10395. }
  10396. // proxy certain important events.
  10397. for (var n = 0; n < kProxyEvents.length; n++) {
  10398. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  10399. }
  10400. // when we try to consume some more bytes, simply unpause the
  10401. // underlying stream.
  10402. this._read = function(n) {
  10403. debug('wrapped _read', n);
  10404. if (paused) {
  10405. paused = false;
  10406. stream.resume();
  10407. }
  10408. };
  10409. return this;
  10410. };
  10411. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  10412. // making it explicit this property is not enumerable
  10413. // because otherwise some prototype manipulation in
  10414. // userland will fail
  10415. enumerable: false,
  10416. get: function() {
  10417. return this._readableState.highWaterMark;
  10418. }
  10419. });
  10420. // exposed for testing purposes only.
  10421. Readable._fromList = fromList;
  10422. // Pluck off n bytes from an array of buffers.
  10423. // Length is the combined lengths of all the buffers in the list.
  10424. // This function is designed to be inlinable, so please take care when making
  10425. // changes to the function body.
  10426. function fromList(n, state) {
  10427. // nothing buffered
  10428. if (state.length === 0) return null;
  10429. var ret;
  10430. if (state.objectMode) ret = state.buffer.shift();
  10431. else if (!n || n >= state.length) {
  10432. // read it all, truncate the list
  10433. if (state.decoder) ret = state.buffer.join('');
  10434. else if (state.buffer.length === 1) ret = state.buffer.head.data;
  10435. else ret = state.buffer.concat(state.length);
  10436. state.buffer.clear();
  10437. } else {
  10438. // read part of list
  10439. ret = fromListPartial(n, state.buffer, state.decoder);
  10440. }
  10441. return ret;
  10442. }
  10443. // Extracts only enough buffered data to satisfy the amount requested.
  10444. // This function is designed to be inlinable, so please take care when making
  10445. // changes to the function body.
  10446. function fromListPartial(n, list, hasStrings) {
  10447. var ret;
  10448. if (n < list.head.data.length) {
  10449. // slice is the same for buffers and strings
  10450. ret = list.head.data.slice(0, n);
  10451. list.head.data = list.head.data.slice(n);
  10452. } else if (n === list.head.data.length) {
  10453. // first chunk is a perfect match
  10454. ret = list.shift();
  10455. } else {
  10456. // result spans more than one buffer
  10457. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n,
  10458. list);
  10459. }
  10460. return ret;
  10461. }
  10462. // Copies a specified amount of characters from the list of buffered data
  10463. // chunks.
  10464. // This function is designed to be inlinable, so please take care when making
  10465. // changes to the function body.
  10466. function copyFromBufferString(n, list) {
  10467. var p = list.head;
  10468. var c = 1;
  10469. var ret = p.data;
  10470. n -= ret.length;
  10471. while (p = p.next) {
  10472. var str = p.data;
  10473. var nb = n > str.length ? str.length : n;
  10474. if (nb === str.length) ret += str;
  10475. else ret += str.slice(0, n);
  10476. n -= nb;
  10477. if (n === 0) {
  10478. if (nb === str.length) {
  10479. ++c;
  10480. if (p.next) list.head = p.next;
  10481. else list.head = list.tail = null;
  10482. } else {
  10483. list.head = p;
  10484. p.data = str.slice(nb);
  10485. }
  10486. break;
  10487. }
  10488. ++c;
  10489. }
  10490. list.length -= c;
  10491. return ret;
  10492. }
  10493. // Copies a specified amount of bytes from the list of buffered data chunks.
  10494. // This function is designed to be inlinable, so please take care when making
  10495. // changes to the function body.
  10496. function copyFromBuffer(n, list) {
  10497. var ret = Buffer.allocUnsafe(n);
  10498. var p = list.head;
  10499. var c = 1;
  10500. p.data.copy(ret);
  10501. n -= p.data.length;
  10502. while (p = p.next) {
  10503. var buf = p.data;
  10504. var nb = n > buf.length ? buf.length : n;
  10505. buf.copy(ret, ret.length - n, 0, nb);
  10506. n -= nb;
  10507. if (n === 0) {
  10508. if (nb === buf.length) {
  10509. ++c;
  10510. if (p.next) list.head = p.next;
  10511. else list.head = list.tail = null;
  10512. } else {
  10513. list.head = p;
  10514. p.data = buf.slice(nb);
  10515. }
  10516. break;
  10517. }
  10518. ++c;
  10519. }
  10520. list.length -= c;
  10521. return ret;
  10522. }
  10523. function endReadable(stream) {
  10524. var state = stream._readableState;
  10525. // If we get here before consuming all the bytes, then that is a
  10526. // bug in node. Should never happen.
  10527. if (state.length > 0) throw new Error(
  10528. '"endReadable()" called on non-empty stream');
  10529. if (!state.endEmitted) {
  10530. state.ended = true;
  10531. pna.nextTick(endReadableNT, state, stream);
  10532. }
  10533. }
  10534. function endReadableNT(state, stream) {
  10535. // Check that we didn't get one last unshift.
  10536. if (!state.endEmitted && state.length === 0) {
  10537. state.endEmitted = true;
  10538. stream.readable = false;
  10539. stream.emit('end');
  10540. }
  10541. }
  10542. function indexOf(xs, x) {
  10543. for (var i = 0, l = xs.length; i < l; i++) {
  10544. if (xs[i] === x) return i;
  10545. }
  10546. return -1;
  10547. }
  10548. }).call(this, require('_process'), typeof global !== "undefined" ? global :
  10549. typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}
  10550. )
  10551. }, {
  10552. "./_stream_duplex": 98,
  10553. "./internal/streams/BufferList": 103,
  10554. "./internal/streams/destroy": 104,
  10555. "./internal/streams/stream": 105,
  10556. "_process": 92,
  10557. "core-util-is": 14,
  10558. "events": 13,
  10559. "inherits": 80,
  10560. "isarray": 106,
  10561. "process-nextick-args": 91,
  10562. "safe-buffer": 110,
  10563. "string_decoder/": 107,
  10564. "util": 11
  10565. }],
  10566. 101: [function(require, module, exports) {
  10567. // Copyright Joyent, Inc. and other Node contributors.
  10568. //
  10569. // Permission is hereby granted, free of charge, to any person obtaining a
  10570. // copy of this software and associated documentation files (the
  10571. // "Software"), to deal in the Software without restriction, including
  10572. // without limitation the rights to use, copy, modify, merge, publish,
  10573. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10574. // persons to whom the Software is furnished to do so, subject to the
  10575. // following conditions:
  10576. //
  10577. // The above copyright notice and this permission notice shall be included
  10578. // in all copies or substantial portions of the Software.
  10579. //
  10580. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10581. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10582. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10583. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10584. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10585. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10586. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10587. // a transform stream is a readable/writable stream where you do
  10588. // something with the data. Sometimes it's called a "filter",
  10589. // but that's not a great name for it, since that implies a thing where
  10590. // some bits pass through, and others are simply ignored. (That would
  10591. // be a valid example of a transform, of course.)
  10592. //
  10593. // While the output is causally related to the input, it's not a
  10594. // necessarily symmetric or synchronous transformation. For example,
  10595. // a zlib stream might take multiple plain-text writes(), and then
  10596. // emit a single compressed chunk some time in the future.
  10597. //
  10598. // Here's how this works:
  10599. //
  10600. // The Transform stream has all the aspects of the readable and writable
  10601. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  10602. // internally, and returns false if there's a lot of pending writes
  10603. // buffered up. When you call read(), that calls _read(n) until
  10604. // there's enough pending readable data buffered up.
  10605. //
  10606. // In a transform stream, the written data is placed in a buffer. When
  10607. // _read(n) is called, it transforms the queued up data, calling the
  10608. // buffered _write cb's as it consumes chunks. If consuming a single
  10609. // written chunk would result in multiple output chunks, then the first
  10610. // outputted bit calls the readcb, and subsequent chunks just go into
  10611. // the read buffer, and will cause it to emit 'readable' if necessary.
  10612. //
  10613. // This way, back-pressure is actually determined by the reading side,
  10614. // since _read has to be called to start processing a new chunk. However,
  10615. // a pathological inflate type of transform can cause excessive buffering
  10616. // here. For example, imagine a stream where every byte of input is
  10617. // interpreted as an integer from 0-255, and then results in that many
  10618. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  10619. // 1kb of data being output. In this case, you could write a very small
  10620. // amount of input, and end up with a very large amount of output. In
  10621. // such a pathological inflating mechanism, there'd be no way to tell
  10622. // the system to stop doing the transform. A single 4MB write could
  10623. // cause the system to run out of memory.
  10624. //
  10625. // However, even in such a pathological case, only a single written chunk
  10626. // would be consumed, and then the rest would wait (un-transformed) until
  10627. // the results of the previous transformed chunk were consumed.
  10628. 'use strict';
  10629. module.exports = Transform;
  10630. var Duplex = require('./_stream_duplex');
  10631. /*<replacement>*/
  10632. var util = require('core-util-is');
  10633. util.inherits = require('inherits');
  10634. /*</replacement>*/
  10635. util.inherits(Transform, Duplex);
  10636. function afterTransform(er, data) {
  10637. var ts = this._transformState;
  10638. ts.transforming = false;
  10639. var cb = ts.writecb;
  10640. if (!cb) {
  10641. return this.emit('error', new Error('write callback called multiple times'));
  10642. }
  10643. ts.writechunk = null;
  10644. ts.writecb = null;
  10645. if (data != null) // single equals check for both `null` and `undefined`
  10646. this.push(data);
  10647. cb(er);
  10648. var rs = this._readableState;
  10649. rs.reading = false;
  10650. if (rs.needReadable || rs.length < rs.highWaterMark) {
  10651. this._read(rs.highWaterMark);
  10652. }
  10653. }
  10654. function Transform(options) {
  10655. if (!(this instanceof Transform)) return new Transform(options);
  10656. Duplex.call(this, options);
  10657. this._transformState = {
  10658. afterTransform: afterTransform.bind(this),
  10659. needTransform: false,
  10660. transforming: false,
  10661. writecb: null,
  10662. writechunk: null,
  10663. writeencoding: null
  10664. };
  10665. // start out asking for a readable event once data is transformed.
  10666. this._readableState.needReadable = true;
  10667. // we have implemented the _read method, and done the other things
  10668. // that Readable wants before the first _read call, so unset the
  10669. // sync guard flag.
  10670. this._readableState.sync = false;
  10671. if (options) {
  10672. if (typeof options.transform === 'function') this._transform = options
  10673. .transform;
  10674. if (typeof options.flush === 'function') this._flush = options.flush;
  10675. }
  10676. // When the writable side finishes, then flush out anything remaining.
  10677. this.on('prefinish', prefinish);
  10678. }
  10679. function prefinish() {
  10680. var _this = this;
  10681. if (typeof this._flush === 'function') {
  10682. this._flush(function(er, data) {
  10683. done(_this, er, data);
  10684. });
  10685. } else {
  10686. done(this, null, null);
  10687. }
  10688. }
  10689. Transform.prototype.push = function(chunk, encoding) {
  10690. this._transformState.needTransform = false;
  10691. return Duplex.prototype.push.call(this, chunk, encoding);
  10692. };
  10693. // This is the part where you do stuff!
  10694. // override this function in implementation classes.
  10695. // 'chunk' is an input chunk.
  10696. //
  10697. // Call `push(newChunk)` to pass along transformed output
  10698. // to the readable side. You may call 'push' zero or more times.
  10699. //
  10700. // Call `cb(err)` when you are done with this chunk. If you pass
  10701. // an error, then that'll put the hurt on the whole operation. If you
  10702. // never call cb(), then you'll never get another chunk.
  10703. Transform.prototype._transform = function(chunk, encoding, cb) {
  10704. throw new Error('_transform() is not implemented');
  10705. };
  10706. Transform.prototype._write = function(chunk, encoding, cb) {
  10707. var ts = this._transformState;
  10708. ts.writecb = cb;
  10709. ts.writechunk = chunk;
  10710. ts.writeencoding = encoding;
  10711. if (!ts.transforming) {
  10712. var rs = this._readableState;
  10713. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark)
  10714. this._read(rs.highWaterMark);
  10715. }
  10716. };
  10717. // Doesn't matter what the args are here.
  10718. // _transform does all the work.
  10719. // That we got here means that the readable side wants more data.
  10720. Transform.prototype._read = function(n) {
  10721. var ts = this._transformState;
  10722. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  10723. ts.transforming = true;
  10724. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  10725. } else {
  10726. // mark that we need a transform, so that any data that comes in
  10727. // will get processed, now that we've asked for it.
  10728. ts.needTransform = true;
  10729. }
  10730. };
  10731. Transform.prototype._destroy = function(err, cb) {
  10732. var _this2 = this;
  10733. Duplex.prototype._destroy.call(this, err, function(err2) {
  10734. cb(err2);
  10735. _this2.emit('close');
  10736. });
  10737. };
  10738. function done(stream, er, data) {
  10739. if (er) return stream.emit('error', er);
  10740. if (data != null) // single equals check for both `null` and `undefined`
  10741. stream.push(data);
  10742. // if there's nothing in the write buffer, then that means
  10743. // that nothing more will ever be provided
  10744. if (stream._writableState.length) throw new Error(
  10745. 'Calling transform done when ws.length != 0');
  10746. if (stream._transformState.transforming) throw new Error(
  10747. 'Calling transform done when still transforming');
  10748. return stream.push(null);
  10749. }
  10750. }, {
  10751. "./_stream_duplex": 98,
  10752. "core-util-is": 14,
  10753. "inherits": 80
  10754. }],
  10755. 102: [function(require, module, exports) {
  10756. (function(process, global, setImmediate) {
  10757. // Copyright Joyent, Inc. and other Node contributors.
  10758. //
  10759. // Permission is hereby granted, free of charge, to any person obtaining a
  10760. // copy of this software and associated documentation files (the
  10761. // "Software"), to deal in the Software without restriction, including
  10762. // without limitation the rights to use, copy, modify, merge, publish,
  10763. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10764. // persons to whom the Software is furnished to do so, subject to the
  10765. // following conditions:
  10766. //
  10767. // The above copyright notice and this permission notice shall be included
  10768. // in all copies or substantial portions of the Software.
  10769. //
  10770. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10771. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10772. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10773. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10774. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10775. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10776. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10777. // A bit simpler than readable streams.
  10778. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  10779. // the drain event emission and buffering.
  10780. 'use strict';
  10781. /*<replacement>*/
  10782. var pna = require('process-nextick-args');
  10783. /*</replacement>*/
  10784. module.exports = Writable;
  10785. /* <replacement> */
  10786. function WriteReq(chunk, encoding, cb) {
  10787. this.chunk = chunk;
  10788. this.encoding = encoding;
  10789. this.callback = cb;
  10790. this.next = null;
  10791. }
  10792. // It seems a linked list but it is not
  10793. // there will be only 2 of these for each stream
  10794. function CorkedRequest(state) {
  10795. var _this = this;
  10796. this.next = null;
  10797. this.entry = null;
  10798. this.finish = function() {
  10799. onCorkedFinish(_this, state);
  10800. };
  10801. }
  10802. /* </replacement> */
  10803. /*<replacement>*/
  10804. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version
  10805. .slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  10806. /*</replacement>*/
  10807. /*<replacement>*/
  10808. var Duplex;
  10809. /*</replacement>*/
  10810. Writable.WritableState = WritableState;
  10811. /*<replacement>*/
  10812. var util = require('core-util-is');
  10813. util.inherits = require('inherits');
  10814. /*</replacement>*/
  10815. /*<replacement>*/
  10816. var internalUtil = {
  10817. deprecate: require('util-deprecate')
  10818. };
  10819. /*</replacement>*/
  10820. /*<replacement>*/
  10821. var Stream = require('./internal/streams/stream');
  10822. /*</replacement>*/
  10823. /*<replacement>*/
  10824. var Buffer = require('safe-buffer').Buffer;
  10825. var OurUint8Array = global.Uint8Array || function() {};
  10826. function _uint8ArrayToBuffer(chunk) {
  10827. return Buffer.from(chunk);
  10828. }
  10829. function _isUint8Array(obj) {
  10830. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  10831. }
  10832. /*</replacement>*/
  10833. var destroyImpl = require('./internal/streams/destroy');
  10834. util.inherits(Writable, Stream);
  10835. function nop() {}
  10836. function WritableState(options, stream) {
  10837. Duplex = Duplex || require('./_stream_duplex');
  10838. options = options || {};
  10839. // Duplex streams are both readable and writable, but share
  10840. // the same options object.
  10841. // However, some cases require setting options to different
  10842. // values for the readable and the writable sides of the duplex stream.
  10843. // These options can be provided separately as readableXXX and writableXXX.
  10844. var isDuplex = stream instanceof Duplex;
  10845. // object stream flag to indicate whether or not this stream
  10846. // contains buffers or objects.
  10847. this.objectMode = !!options.objectMode;
  10848. if (isDuplex) this.objectMode = this.objectMode || !!options
  10849. .writableObjectMode;
  10850. // the point at which write() starts returning false
  10851. // Note: 0 is a valid value, means that we always return false if
  10852. // the entire buffer is not flushed immediately on write()
  10853. var hwm = options.highWaterMark;
  10854. var writableHwm = options.writableHighWaterMark;
  10855. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  10856. if (hwm || hwm === 0) this.highWaterMark = hwm;
  10857. else if (isDuplex && (writableHwm || writableHwm === 0)) this
  10858. .highWaterMark = writableHwm;
  10859. else this.highWaterMark = defaultHwm;
  10860. // cast to ints.
  10861. this.highWaterMark = Math.floor(this.highWaterMark);
  10862. // if _final has been called
  10863. this.finalCalled = false;
  10864. // drain event flag.
  10865. this.needDrain = false;
  10866. // at the start of calling end()
  10867. this.ending = false;
  10868. // when end() has been called, and returned
  10869. this.ended = false;
  10870. // when 'finish' is emitted
  10871. this.finished = false;
  10872. // has it been destroyed
  10873. this.destroyed = false;
  10874. // should we decode strings into buffers before passing to _write?
  10875. // this is here so that some node-core streams can optimize string
  10876. // handling at a lower level.
  10877. var noDecode = options.decodeStrings === false;
  10878. this.decodeStrings = !noDecode;
  10879. // Crypto is kind of old and crusty. Historically, its default string
  10880. // encoding is 'binary' so we have to make this configurable.
  10881. // Everything else in the universe uses 'utf8', though.
  10882. this.defaultEncoding = options.defaultEncoding || 'utf8';
  10883. // not an actual buffer we keep track of, but a measurement
  10884. // of how much we're waiting to get pushed to some underlying
  10885. // socket or file.
  10886. this.length = 0;
  10887. // a flag to see when we're in the middle of a write.
  10888. this.writing = false;
  10889. // when true all writes will be buffered until .uncork() call
  10890. this.corked = 0;
  10891. // a flag to be able to tell if the onwrite cb is called immediately,
  10892. // or on a later tick. We set this to true at first, because any
  10893. // actions that shouldn't happen until "later" should generally also
  10894. // not happen before the first write call.
  10895. this.sync = true;
  10896. // a flag to know if we're processing previously buffered items, which
  10897. // may call the _write() callback in the same tick, so that we don't
  10898. // end up in an overlapped onwrite situation.
  10899. this.bufferProcessing = false;
  10900. // the callback that's passed to _write(chunk,cb)
  10901. this.onwrite = function(er) {
  10902. onwrite(stream, er);
  10903. };
  10904. // the callback that the user supplies to write(chunk,encoding,cb)
  10905. this.writecb = null;
  10906. // the amount that is being written when _write is called.
  10907. this.writelen = 0;
  10908. this.bufferedRequest = null;
  10909. this.lastBufferedRequest = null;
  10910. // number of pending user-supplied write callbacks
  10911. // this must be 0 before 'finish' can be emitted
  10912. this.pendingcb = 0;
  10913. // emit prefinish if the only thing we're waiting for is _write cbs
  10914. // This is relevant for synchronous Transform streams
  10915. this.prefinished = false;
  10916. // True if the error was already emitted and should not be thrown again
  10917. this.errorEmitted = false;
  10918. // count buffered requests
  10919. this.bufferedRequestCount = 0;
  10920. // allocate the first CorkedRequest, there is always
  10921. // one allocated and free to use, and we maintain at most two
  10922. this.corkedRequestsFree = new CorkedRequest(this);
  10923. }
  10924. WritableState.prototype.getBuffer = function getBuffer() {
  10925. var current = this.bufferedRequest;
  10926. var out = [];
  10927. while (current) {
  10928. out.push(current);
  10929. current = current.next;
  10930. }
  10931. return out;
  10932. };
  10933. (function() {
  10934. try {
  10935. Object.defineProperty(WritableState.prototype, 'buffer', {
  10936. get: internalUtil.deprecate(function() {
  10937. return this.getBuffer();
  10938. },
  10939. '_writableState.buffer is deprecated. Use _writableState.getBuffer ' +
  10940. 'instead.', 'DEP0003')
  10941. });
  10942. } catch (_) {}
  10943. })();
  10944. // Test _writableState for inheritance to account for Duplex streams,
  10945. // whose prototype chain only points to Readable.
  10946. var realHasInstance;
  10947. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function
  10948. .prototype[Symbol.hasInstance] === 'function') {
  10949. realHasInstance = Function.prototype[Symbol.hasInstance];
  10950. Object.defineProperty(Writable, Symbol.hasInstance, {
  10951. value: function(object) {
  10952. if (realHasInstance.call(this, object)) return true;
  10953. if (this !== Writable) return false;
  10954. return object && object
  10955. ._writableState instanceof WritableState;
  10956. }
  10957. });
  10958. } else {
  10959. realHasInstance = function(object) {
  10960. return object instanceof this;
  10961. };
  10962. }
  10963. function Writable(options) {
  10964. Duplex = Duplex || require('./_stream_duplex');
  10965. // Writable ctor is applied to Duplexes, too.
  10966. // `realHasInstance` is necessary because using plain `instanceof`
  10967. // would return false, as no `_writableState` property is attached.
  10968. // Trying to use the custom `instanceof` for Writable here will also break the
  10969. // Node.js LazyTransform implementation, which has a non-trivial getter for
  10970. // `_writableState` that would lead to infinite recursion.
  10971. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  10972. return new Writable(options);
  10973. }
  10974. this._writableState = new WritableState(options, this);
  10975. // legacy.
  10976. this.writable = true;
  10977. if (options) {
  10978. if (typeof options.write === 'function') this._write = options.write;
  10979. if (typeof options.writev === 'function') this._writev = options.writev;
  10980. if (typeof options.destroy === 'function') this._destroy = options
  10981. .destroy;
  10982. if (typeof options.final === 'function') this._final = options.final;
  10983. }
  10984. Stream.call(this);
  10985. }
  10986. // Otherwise people can pipe Writable streams, which is just wrong.
  10987. Writable.prototype.pipe = function() {
  10988. this.emit('error', new Error('Cannot pipe, not readable'));
  10989. };
  10990. function writeAfterEnd(stream, cb) {
  10991. var er = new Error('write after end');
  10992. // TODO: defer error events consistently everywhere, not just the cb
  10993. stream.emit('error', er);
  10994. pna.nextTick(cb, er);
  10995. }
  10996. // Checks that a user-supplied chunk is valid, especially for the particular
  10997. // mode the stream is in. Currently this means that `null` is never accepted
  10998. // and undefined/non-string values are only allowed in object mode.
  10999. function validChunk(stream, state, chunk, cb) {
  11000. var valid = true;
  11001. var er = false;
  11002. if (chunk === null) {
  11003. er = new TypeError('May not write null values to stream');
  11004. } else if (typeof chunk !== 'string' && chunk !== undefined && !state
  11005. .objectMode) {
  11006. er = new TypeError('Invalid non-string/buffer chunk');
  11007. }
  11008. if (er) {
  11009. stream.emit('error', er);
  11010. pna.nextTick(cb, er);
  11011. valid = false;
  11012. }
  11013. return valid;
  11014. }
  11015. Writable.prototype.write = function(chunk, encoding, cb) {
  11016. var state = this._writableState;
  11017. var ret = false;
  11018. var isBuf = !state.objectMode && _isUint8Array(chunk);
  11019. if (isBuf && !Buffer.isBuffer(chunk)) {
  11020. chunk = _uint8ArrayToBuffer(chunk);
  11021. }
  11022. if (typeof encoding === 'function') {
  11023. cb = encoding;
  11024. encoding = null;
  11025. }
  11026. if (isBuf) encoding = 'buffer';
  11027. else if (!encoding) encoding = state.defaultEncoding;
  11028. if (typeof cb !== 'function') cb = nop;
  11029. if (state.ended) writeAfterEnd(this, cb);
  11030. else if (isBuf || validChunk(this, state, chunk, cb)) {
  11031. state.pendingcb++;
  11032. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  11033. }
  11034. return ret;
  11035. };
  11036. Writable.prototype.cork = function() {
  11037. var state = this._writableState;
  11038. state.corked++;
  11039. };
  11040. Writable.prototype.uncork = function() {
  11041. var state = this._writableState;
  11042. if (state.corked) {
  11043. state.corked--;
  11044. if (!state.writing && !state.corked && !state.finished && !state
  11045. .bufferProcessing && state.bufferedRequest) clearBuffer(this,
  11046. state);
  11047. }
  11048. };
  11049. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  11050. // node::ParseEncoding() requires lower case.
  11051. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  11052. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2',
  11053. 'ucs-2', 'utf16le', 'utf-16le', 'raw'
  11054. ].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError(
  11055. 'Unknown encoding: ' + encoding);
  11056. this._writableState.defaultEncoding = encoding;
  11057. return this;
  11058. };
  11059. function decodeChunk(state, chunk, encoding) {
  11060. if (!state.objectMode && state.decodeStrings !== false && typeof chunk ===
  11061. 'string') {
  11062. chunk = Buffer.from(chunk, encoding);
  11063. }
  11064. return chunk;
  11065. }
  11066. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  11067. // making it explicit this property is not enumerable
  11068. // because otherwise some prototype manipulation in
  11069. // userland will fail
  11070. enumerable: false,
  11071. get: function() {
  11072. return this._writableState.highWaterMark;
  11073. }
  11074. });
  11075. // if we're already writing something, then just put this
  11076. // in the queue, and wait our turn. Otherwise, call _write
  11077. // If we return false, then we need a drain event, so set that flag.
  11078. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  11079. if (!isBuf) {
  11080. var newChunk = decodeChunk(state, chunk, encoding);
  11081. if (chunk !== newChunk) {
  11082. isBuf = true;
  11083. encoding = 'buffer';
  11084. chunk = newChunk;
  11085. }
  11086. }
  11087. var len = state.objectMode ? 1 : chunk.length;
  11088. state.length += len;
  11089. var ret = state.length < state.highWaterMark;
  11090. // we must ensure that previous needDrain will not be reset to false.
  11091. if (!ret) state.needDrain = true;
  11092. if (state.writing || state.corked) {
  11093. var last = state.lastBufferedRequest;
  11094. state.lastBufferedRequest = {
  11095. chunk: chunk,
  11096. encoding: encoding,
  11097. isBuf: isBuf,
  11098. callback: cb,
  11099. next: null
  11100. };
  11101. if (last) {
  11102. last.next = state.lastBufferedRequest;
  11103. } else {
  11104. state.bufferedRequest = state.lastBufferedRequest;
  11105. }
  11106. state.bufferedRequestCount += 1;
  11107. } else {
  11108. doWrite(stream, state, false, len, chunk, encoding, cb);
  11109. }
  11110. return ret;
  11111. }
  11112. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  11113. state.writelen = len;
  11114. state.writecb = cb;
  11115. state.writing = true;
  11116. state.sync = true;
  11117. if (writev) stream._writev(chunk, state.onwrite);
  11118. else stream._write(chunk, encoding, state.onwrite);
  11119. state.sync = false;
  11120. }
  11121. function onwriteError(stream, state, sync, er, cb) {
  11122. --state.pendingcb;
  11123. if (sync) {
  11124. // defer the callback if we are being called synchronously
  11125. // to avoid piling up things on the stack
  11126. pna.nextTick(cb, er);
  11127. // this can emit finish, and it will always happen
  11128. // after error
  11129. pna.nextTick(finishMaybe, stream, state);
  11130. stream._writableState.errorEmitted = true;
  11131. stream.emit('error', er);
  11132. } else {
  11133. // the caller expect this to happen before if
  11134. // it is async
  11135. cb(er);
  11136. stream._writableState.errorEmitted = true;
  11137. stream.emit('error', er);
  11138. // this can emit finish, but finish must
  11139. // always follow error
  11140. finishMaybe(stream, state);
  11141. }
  11142. }
  11143. function onwriteStateUpdate(state) {
  11144. state.writing = false;
  11145. state.writecb = null;
  11146. state.length -= state.writelen;
  11147. state.writelen = 0;
  11148. }
  11149. function onwrite(stream, er) {
  11150. var state = stream._writableState;
  11151. var sync = state.sync;
  11152. var cb = state.writecb;
  11153. onwriteStateUpdate(state);
  11154. if (er) onwriteError(stream, state, sync, er, cb);
  11155. else {
  11156. // Check if we're actually ready to finish, but don't emit yet
  11157. var finished = needFinish(state);
  11158. if (!finished && !state.corked && !state.bufferProcessing && state
  11159. .bufferedRequest) {
  11160. clearBuffer(stream, state);
  11161. }
  11162. if (sync) {
  11163. /*<replacement>*/
  11164. asyncWrite(afterWrite, stream, state, finished, cb);
  11165. /*</replacement>*/
  11166. } else {
  11167. afterWrite(stream, state, finished, cb);
  11168. }
  11169. }
  11170. }
  11171. function afterWrite(stream, state, finished, cb) {
  11172. if (!finished) onwriteDrain(stream, state);
  11173. state.pendingcb--;
  11174. cb();
  11175. finishMaybe(stream, state);
  11176. }
  11177. // Must force callback to be called on nextTick, so that we don't
  11178. // emit 'drain' before the write() consumer gets the 'false' return
  11179. // value, and has a chance to attach a 'drain' listener.
  11180. function onwriteDrain(stream, state) {
  11181. if (state.length === 0 && state.needDrain) {
  11182. state.needDrain = false;
  11183. stream.emit('drain');
  11184. }
  11185. }
  11186. // if there's something in the buffer waiting, then process it
  11187. function clearBuffer(stream, state) {
  11188. state.bufferProcessing = true;
  11189. var entry = state.bufferedRequest;
  11190. if (stream._writev && entry && entry.next) {
  11191. // Fast case, write everything using _writev()
  11192. var l = state.bufferedRequestCount;
  11193. var buffer = new Array(l);
  11194. var holder = state.corkedRequestsFree;
  11195. holder.entry = entry;
  11196. var count = 0;
  11197. var allBuffers = true;
  11198. while (entry) {
  11199. buffer[count] = entry;
  11200. if (!entry.isBuf) allBuffers = false;
  11201. entry = entry.next;
  11202. count += 1;
  11203. }
  11204. buffer.allBuffers = allBuffers;
  11205. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  11206. // doWrite is almost always async, defer these to save a bit of time
  11207. // as the hot path ends with doWrite
  11208. state.pendingcb++;
  11209. state.lastBufferedRequest = null;
  11210. if (holder.next) {
  11211. state.corkedRequestsFree = holder.next;
  11212. holder.next = null;
  11213. } else {
  11214. state.corkedRequestsFree = new CorkedRequest(state);
  11215. }
  11216. state.bufferedRequestCount = 0;
  11217. } else {
  11218. // Slow case, write chunks one-by-one
  11219. while (entry) {
  11220. var chunk = entry.chunk;
  11221. var encoding = entry.encoding;
  11222. var cb = entry.callback;
  11223. var len = state.objectMode ? 1 : chunk.length;
  11224. doWrite(stream, state, false, len, chunk, encoding, cb);
  11225. entry = entry.next;
  11226. state.bufferedRequestCount--;
  11227. // if we didn't call the onwrite immediately, then
  11228. // it means that we need to wait until it does.
  11229. // also, that means that the chunk and cb are currently
  11230. // being processed, so move the buffer counter past them.
  11231. if (state.writing) {
  11232. break;
  11233. }
  11234. }
  11235. if (entry === null) state.lastBufferedRequest = null;
  11236. }
  11237. state.bufferedRequest = entry;
  11238. state.bufferProcessing = false;
  11239. }
  11240. Writable.prototype._write = function(chunk, encoding, cb) {
  11241. cb(new Error('_write() is not implemented'));
  11242. };
  11243. Writable.prototype._writev = null;
  11244. Writable.prototype.end = function(chunk, encoding, cb) {
  11245. var state = this._writableState;
  11246. if (typeof chunk === 'function') {
  11247. cb = chunk;
  11248. chunk = null;
  11249. encoding = null;
  11250. } else if (typeof encoding === 'function') {
  11251. cb = encoding;
  11252. encoding = null;
  11253. }
  11254. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  11255. // .end() fully uncorks
  11256. if (state.corked) {
  11257. state.corked = 1;
  11258. this.uncork();
  11259. }
  11260. // ignore unnecessary end() calls.
  11261. if (!state.ending && !state.finished) endWritable(this, state, cb);
  11262. };
  11263. function needFinish(state) {
  11264. return state.ending && state.length === 0 && state.bufferedRequest ===
  11265. null && !state.finished && !state.writing;
  11266. }
  11267. function callFinal(stream, state) {
  11268. stream._final(function(err) {
  11269. state.pendingcb--;
  11270. if (err) {
  11271. stream.emit('error', err);
  11272. }
  11273. state.prefinished = true;
  11274. stream.emit('prefinish');
  11275. finishMaybe(stream, state);
  11276. });
  11277. }
  11278. function prefinish(stream, state) {
  11279. if (!state.prefinished && !state.finalCalled) {
  11280. if (typeof stream._final === 'function') {
  11281. state.pendingcb++;
  11282. state.finalCalled = true;
  11283. pna.nextTick(callFinal, stream, state);
  11284. } else {
  11285. state.prefinished = true;
  11286. stream.emit('prefinish');
  11287. }
  11288. }
  11289. }
  11290. function finishMaybe(stream, state) {
  11291. var need = needFinish(state);
  11292. if (need) {
  11293. prefinish(stream, state);
  11294. if (state.pendingcb === 0) {
  11295. state.finished = true;
  11296. stream.emit('finish');
  11297. }
  11298. }
  11299. return need;
  11300. }
  11301. function endWritable(stream, state, cb) {
  11302. state.ending = true;
  11303. finishMaybe(stream, state);
  11304. if (cb) {
  11305. if (state.finished) pna.nextTick(cb);
  11306. else stream.once('finish', cb);
  11307. }
  11308. state.ended = true;
  11309. stream.writable = false;
  11310. }
  11311. function onCorkedFinish(corkReq, state, err) {
  11312. var entry = corkReq.entry;
  11313. corkReq.entry = null;
  11314. while (entry) {
  11315. var cb = entry.callback;
  11316. state.pendingcb--;
  11317. cb(err);
  11318. entry = entry.next;
  11319. }
  11320. if (state.corkedRequestsFree) {
  11321. state.corkedRequestsFree.next = corkReq;
  11322. } else {
  11323. state.corkedRequestsFree = corkReq;
  11324. }
  11325. }
  11326. Object.defineProperty(Writable.prototype, 'destroyed', {
  11327. get: function() {
  11328. if (this._writableState === undefined) {
  11329. return false;
  11330. }
  11331. return this._writableState.destroyed;
  11332. },
  11333. set: function(value) {
  11334. // we ignore the value if the stream
  11335. // has not been initialized yet
  11336. if (!this._writableState) {
  11337. return;
  11338. }
  11339. // backward compatibility, the user is explicitly
  11340. // managing destroyed
  11341. this._writableState.destroyed = value;
  11342. }
  11343. });
  11344. Writable.prototype.destroy = destroyImpl.destroy;
  11345. Writable.prototype._undestroy = destroyImpl.undestroy;
  11346. Writable.prototype._destroy = function(err, cb) {
  11347. this.end();
  11348. cb(err);
  11349. };
  11350. }).call(this, require('_process'), typeof global !== "undefined" ? global :
  11351. typeof self !== "undefined" ? self : typeof window !== "undefined" ? window :
  11352. {}, require("timers").setImmediate)
  11353. }, {
  11354. "./_stream_duplex": 98,
  11355. "./internal/streams/destroy": 104,
  11356. "./internal/streams/stream": 105,
  11357. "_process": 92,
  11358. "core-util-is": 14,
  11359. "inherits": 80,
  11360. "process-nextick-args": 91,
  11361. "safe-buffer": 110,
  11362. "timers": 112,
  11363. "util-deprecate": 115
  11364. }],
  11365. 103: [function(require, module, exports) {
  11366. 'use strict';
  11367. function _classCallCheck(instance, Constructor) {
  11368. if (!(instance instanceof Constructor)) {
  11369. throw new TypeError("Cannot call a class as a function");
  11370. }
  11371. }
  11372. var Buffer = require('safe-buffer').Buffer;
  11373. var util = require('util');
  11374. function copyBuffer(src, target, offset) {
  11375. src.copy(target, offset);
  11376. }
  11377. module.exports = function() {
  11378. function BufferList() {
  11379. _classCallCheck(this, BufferList);
  11380. this.head = null;
  11381. this.tail = null;
  11382. this.length = 0;
  11383. }
  11384. BufferList.prototype.push = function push(v) {
  11385. var entry = {
  11386. data: v,
  11387. next: null
  11388. };
  11389. if (this.length > 0) this.tail.next = entry;
  11390. else this.head = entry;
  11391. this.tail = entry;
  11392. ++this.length;
  11393. };
  11394. BufferList.prototype.unshift = function unshift(v) {
  11395. var entry = {
  11396. data: v,
  11397. next: this.head
  11398. };
  11399. if (this.length === 0) this.tail = entry;
  11400. this.head = entry;
  11401. ++this.length;
  11402. };
  11403. BufferList.prototype.shift = function shift() {
  11404. if (this.length === 0) return;
  11405. var ret = this.head.data;
  11406. if (this.length === 1) this.head = this.tail = null;
  11407. else this.head = this.head.next;
  11408. --this.length;
  11409. return ret;
  11410. };
  11411. BufferList.prototype.clear = function clear() {
  11412. this.head = this.tail = null;
  11413. this.length = 0;
  11414. };
  11415. BufferList.prototype.join = function join(s) {
  11416. if (this.length === 0) return '';
  11417. var p = this.head;
  11418. var ret = '' + p.data;
  11419. while (p = p.next) {
  11420. ret += s + p.data;
  11421. }
  11422. return ret;
  11423. };
  11424. BufferList.prototype.concat = function concat(n) {
  11425. if (this.length === 0) return Buffer.alloc(0);
  11426. if (this.length === 1) return this.head.data;
  11427. var ret = Buffer.allocUnsafe(n >>> 0);
  11428. var p = this.head;
  11429. var i = 0;
  11430. while (p) {
  11431. copyBuffer(p.data, ret, i);
  11432. i += p.data.length;
  11433. p = p.next;
  11434. }
  11435. return ret;
  11436. };
  11437. return BufferList;
  11438. }();
  11439. if (util && util.inspect && util.inspect.custom) {
  11440. module.exports.prototype[util.inspect.custom] = function() {
  11441. var obj = util.inspect({
  11442. length: this.length
  11443. });
  11444. return this.constructor.name + ' ' + obj;
  11445. };
  11446. }
  11447. }, {
  11448. "safe-buffer": 110,
  11449. "util": 11
  11450. }],
  11451. 104: [function(require, module, exports) {
  11452. 'use strict';
  11453. /*<replacement>*/
  11454. var pna = require('process-nextick-args');
  11455. /*</replacement>*/
  11456. // undocumented cb() API, needed for core, not for public API
  11457. function destroy(err, cb) {
  11458. var _this = this;
  11459. var readableDestroyed = this._readableState && this._readableState.destroyed;
  11460. var writableDestroyed = this._writableState && this._writableState.destroyed;
  11461. if (readableDestroyed || writableDestroyed) {
  11462. if (cb) {
  11463. cb(err);
  11464. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  11465. pna.nextTick(emitErrorNT, this, err);
  11466. }
  11467. return this;
  11468. }
  11469. // we set destroyed to true before firing error callbacks in order
  11470. // to make it re-entrance safe in case destroy() is called within callbacks
  11471. if (this._readableState) {
  11472. this._readableState.destroyed = true;
  11473. }
  11474. // if this is a duplex stream mark the writable part as destroyed as well
  11475. if (this._writableState) {
  11476. this._writableState.destroyed = true;
  11477. }
  11478. this._destroy(err || null, function(err) {
  11479. if (!cb && err) {
  11480. pna.nextTick(emitErrorNT, _this, err);
  11481. if (_this._writableState) {
  11482. _this._writableState.errorEmitted = true;
  11483. }
  11484. } else if (cb) {
  11485. cb(err);
  11486. }
  11487. });
  11488. return this;
  11489. }
  11490. function undestroy() {
  11491. if (this._readableState) {
  11492. this._readableState.destroyed = false;
  11493. this._readableState.reading = false;
  11494. this._readableState.ended = false;
  11495. this._readableState.endEmitted = false;
  11496. }
  11497. if (this._writableState) {
  11498. this._writableState.destroyed = false;
  11499. this._writableState.ended = false;
  11500. this._writableState.ending = false;
  11501. this._writableState.finished = false;
  11502. this._writableState.errorEmitted = false;
  11503. }
  11504. }
  11505. function emitErrorNT(self, err) {
  11506. self.emit('error', err);
  11507. }
  11508. module.exports = {
  11509. destroy: destroy,
  11510. undestroy: undestroy
  11511. };
  11512. }, {
  11513. "process-nextick-args": 91
  11514. }],
  11515. 105: [function(require, module, exports) {
  11516. module.exports = require('events').EventEmitter;
  11517. }, {
  11518. "events": 13
  11519. }],
  11520. 106: [function(require, module, exports) {
  11521. var toString = {}.toString;
  11522. module.exports = Array.isArray || function(arr) {
  11523. return toString.call(arr) == '[object Array]';
  11524. };
  11525. }, {}],
  11526. 107: [function(require, module, exports) {
  11527. // Copyright Joyent, Inc. and other Node contributors.
  11528. //
  11529. // Permission is hereby granted, free of charge, to any person obtaining a
  11530. // copy of this software and associated documentation files (the
  11531. // "Software"), to deal in the Software without restriction, including
  11532. // without limitation the rights to use, copy, modify, merge, publish,
  11533. // distribute, sublicense, and/or sell copies of the Software, and to permit
  11534. // persons to whom the Software is furnished to do so, subject to the
  11535. // following conditions:
  11536. //
  11537. // The above copyright notice and this permission notice shall be included
  11538. // in all copies or substantial portions of the Software.
  11539. //
  11540. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  11541. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  11542. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  11543. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  11544. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  11545. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  11546. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  11547. 'use strict';
  11548. /*<replacement>*/
  11549. var Buffer = require('safe-buffer').Buffer;
  11550. /*</replacement>*/
  11551. var isEncoding = Buffer.isEncoding || function(encoding) {
  11552. encoding = '' + encoding;
  11553. switch (encoding && encoding.toLowerCase()) {
  11554. case 'hex':
  11555. case 'utf8':
  11556. case 'utf-8':
  11557. case 'ascii':
  11558. case 'binary':
  11559. case 'base64':
  11560. case 'ucs2':
  11561. case 'ucs-2':
  11562. case 'utf16le':
  11563. case 'utf-16le':
  11564. case 'raw':
  11565. return true;
  11566. default:
  11567. return false;
  11568. }
  11569. };
  11570. function _normalizeEncoding(enc) {
  11571. if (!enc) return 'utf8';
  11572. var retried;
  11573. while (true) {
  11574. switch (enc) {
  11575. case 'utf8':
  11576. case 'utf-8':
  11577. return 'utf8';
  11578. case 'ucs2':
  11579. case 'ucs-2':
  11580. case 'utf16le':
  11581. case 'utf-16le':
  11582. return 'utf16le';
  11583. case 'latin1':
  11584. case 'binary':
  11585. return 'latin1';
  11586. case 'base64':
  11587. case 'ascii':
  11588. case 'hex':
  11589. return enc;
  11590. default:
  11591. if (retried) return; // undefined
  11592. enc = ('' + enc).toLowerCase();
  11593. retried = true;
  11594. }
  11595. }
  11596. };
  11597. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  11598. // modules monkey-patch it to support additional encodings
  11599. function normalizeEncoding(enc) {
  11600. var nenc = _normalizeEncoding(enc);
  11601. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(
  11602. enc))) throw new Error('Unknown encoding: ' + enc);
  11603. return nenc || enc;
  11604. }
  11605. // StringDecoder provides an interface for efficiently splitting a series of
  11606. // buffers into a series of JS strings without breaking apart multi-byte
  11607. // characters.
  11608. exports.StringDecoder = StringDecoder;
  11609. function StringDecoder(encoding) {
  11610. this.encoding = normalizeEncoding(encoding);
  11611. var nb;
  11612. switch (this.encoding) {
  11613. case 'utf16le':
  11614. this.text = utf16Text;
  11615. this.end = utf16End;
  11616. nb = 4;
  11617. break;
  11618. case 'utf8':
  11619. this.fillLast = utf8FillLast;
  11620. nb = 4;
  11621. break;
  11622. case 'base64':
  11623. this.text = base64Text;
  11624. this.end = base64End;
  11625. nb = 3;
  11626. break;
  11627. default:
  11628. this.write = simpleWrite;
  11629. this.end = simpleEnd;
  11630. return;
  11631. }
  11632. this.lastNeed = 0;
  11633. this.lastTotal = 0;
  11634. this.lastChar = Buffer.allocUnsafe(nb);
  11635. }
  11636. StringDecoder.prototype.write = function(buf) {
  11637. if (buf.length === 0) return '';
  11638. var r;
  11639. var i;
  11640. if (this.lastNeed) {
  11641. r = this.fillLast(buf);
  11642. if (r === undefined) return '';
  11643. i = this.lastNeed;
  11644. this.lastNeed = 0;
  11645. } else {
  11646. i = 0;
  11647. }
  11648. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  11649. return r || '';
  11650. };
  11651. StringDecoder.prototype.end = utf8End;
  11652. // Returns only complete characters in a Buffer
  11653. StringDecoder.prototype.text = utf8Text;
  11654. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  11655. StringDecoder.prototype.fillLast = function(buf) {
  11656. if (this.lastNeed <= buf.length) {
  11657. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  11658. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  11659. }
  11660. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  11661. this.lastNeed -= buf.length;
  11662. };
  11663. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  11664. // continuation byte. If an invalid byte is detected, -2 is returned.
  11665. function utf8CheckByte(byte) {
  11666. if (byte <= 0x7F) return 0;
  11667. else if (byte >> 5 === 0x06) return 2;
  11668. else if (byte >> 4 === 0x0E) return 3;
  11669. else if (byte >> 3 === 0x1E) return 4;
  11670. return byte >> 6 === 0x02 ? -1 : -2;
  11671. }
  11672. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  11673. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  11674. // needed to complete the UTF-8 character (if applicable) are returned.
  11675. function utf8CheckIncomplete(self, buf, i) {
  11676. var j = buf.length - 1;
  11677. if (j < i) return 0;
  11678. var nb = utf8CheckByte(buf[j]);
  11679. if (nb >= 0) {
  11680. if (nb > 0) self.lastNeed = nb - 1;
  11681. return nb;
  11682. }
  11683. if (--j < i || nb === -2) return 0;
  11684. nb = utf8CheckByte(buf[j]);
  11685. if (nb >= 0) {
  11686. if (nb > 0) self.lastNeed = nb - 2;
  11687. return nb;
  11688. }
  11689. if (--j < i || nb === -2) return 0;
  11690. nb = utf8CheckByte(buf[j]);
  11691. if (nb >= 0) {
  11692. if (nb > 0) {
  11693. if (nb === 2) nb = 0;
  11694. else self.lastNeed = nb - 3;
  11695. }
  11696. return nb;
  11697. }
  11698. return 0;
  11699. }
  11700. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  11701. // needed or are available. If we see a non-continuation byte where we expect
  11702. // one, we "replace" the validated continuation bytes we've seen so far with
  11703. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  11704. // behavior. The continuation byte check is included three times in the case
  11705. // where all of the continuation bytes for a character exist in the same buffer.
  11706. // It is also done this way as a slight performance increase instead of using a
  11707. // loop.
  11708. function utf8CheckExtraBytes(self, buf, p) {
  11709. if ((buf[0] & 0xC0) !== 0x80) {
  11710. self.lastNeed = 0;
  11711. return '\ufffd';
  11712. }
  11713. if (self.lastNeed > 1 && buf.length > 1) {
  11714. if ((buf[1] & 0xC0) !== 0x80) {
  11715. self.lastNeed = 1;
  11716. return '\ufffd';
  11717. }
  11718. if (self.lastNeed > 2 && buf.length > 2) {
  11719. if ((buf[2] & 0xC0) !== 0x80) {
  11720. self.lastNeed = 2;
  11721. return '\ufffd';
  11722. }
  11723. }
  11724. }
  11725. }
  11726. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  11727. function utf8FillLast(buf) {
  11728. var p = this.lastTotal - this.lastNeed;
  11729. var r = utf8CheckExtraBytes(this, buf, p);
  11730. if (r !== undefined) return r;
  11731. if (this.lastNeed <= buf.length) {
  11732. buf.copy(this.lastChar, p, 0, this.lastNeed);
  11733. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  11734. }
  11735. buf.copy(this.lastChar, p, 0, buf.length);
  11736. this.lastNeed -= buf.length;
  11737. }
  11738. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  11739. // partial character, the character's bytes are buffered until the required
  11740. // number of bytes are available.
  11741. function utf8Text(buf, i) {
  11742. var total = utf8CheckIncomplete(this, buf, i);
  11743. if (!this.lastNeed) return buf.toString('utf8', i);
  11744. this.lastTotal = total;
  11745. var end = buf.length - (total - this.lastNeed);
  11746. buf.copy(this.lastChar, 0, end);
  11747. return buf.toString('utf8', i, end);
  11748. }
  11749. // For UTF-8, a replacement character is added when ending on a partial
  11750. // character.
  11751. function utf8End(buf) {
  11752. var r = buf && buf.length ? this.write(buf) : '';
  11753. if (this.lastNeed) return r + '\ufffd';
  11754. return r;
  11755. }
  11756. // UTF-16LE typically needs two bytes per character, but even if we have an even
  11757. // number of bytes available, we need to check if we end on a leading/high
  11758. // surrogate. In that case, we need to wait for the next two bytes in order to
  11759. // decode the last character properly.
  11760. function utf16Text(buf, i) {
  11761. if ((buf.length - i) % 2 === 0) {
  11762. var r = buf.toString('utf16le', i);
  11763. if (r) {
  11764. var c = r.charCodeAt(r.length - 1);
  11765. if (c >= 0xD800 && c <= 0xDBFF) {
  11766. this.lastNeed = 2;
  11767. this.lastTotal = 4;
  11768. this.lastChar[0] = buf[buf.length - 2];
  11769. this.lastChar[1] = buf[buf.length - 1];
  11770. return r.slice(0, -1);
  11771. }
  11772. }
  11773. return r;
  11774. }
  11775. this.lastNeed = 1;
  11776. this.lastTotal = 2;
  11777. this.lastChar[0] = buf[buf.length - 1];
  11778. return buf.toString('utf16le', i, buf.length - 1);
  11779. }
  11780. // For UTF-16LE we do not explicitly append special replacement characters if we
  11781. // end on a partial character, we simply let v8 handle that.
  11782. function utf16End(buf) {
  11783. var r = buf && buf.length ? this.write(buf) : '';
  11784. if (this.lastNeed) {
  11785. var end = this.lastTotal - this.lastNeed;
  11786. return r + this.lastChar.toString('utf16le', 0, end);
  11787. }
  11788. return r;
  11789. }
  11790. function base64Text(buf, i) {
  11791. var n = (buf.length - i) % 3;
  11792. if (n === 0) return buf.toString('base64', i);
  11793. this.lastNeed = 3 - n;
  11794. this.lastTotal = 3;
  11795. if (n === 1) {
  11796. this.lastChar[0] = buf[buf.length - 1];
  11797. } else {
  11798. this.lastChar[0] = buf[buf.length - 2];
  11799. this.lastChar[1] = buf[buf.length - 1];
  11800. }
  11801. return buf.toString('base64', i, buf.length - n);
  11802. }
  11803. function base64End(buf) {
  11804. var r = buf && buf.length ? this.write(buf) : '';
  11805. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this
  11806. .lastNeed);
  11807. return r;
  11808. }
  11809. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  11810. function simpleWrite(buf) {
  11811. return buf.toString(this.encoding);
  11812. }
  11813. function simpleEnd(buf) {
  11814. return buf && buf.length ? this.write(buf) : '';
  11815. }
  11816. }, {
  11817. "safe-buffer": 110
  11818. }],
  11819. 108: [function(require, module, exports) {
  11820. exports = module.exports = require('./lib/_stream_readable.js');
  11821. exports.Stream = exports;
  11822. exports.Readable = exports;
  11823. exports.Writable = require('./lib/_stream_writable.js');
  11824. exports.Duplex = require('./lib/_stream_duplex.js');
  11825. exports.Transform = require('./lib/_stream_transform.js');
  11826. exports.PassThrough = require('./lib/_stream_passthrough.js');
  11827. }, {
  11828. "./lib/_stream_duplex.js": 98,
  11829. "./lib/_stream_passthrough.js": 99,
  11830. "./lib/_stream_readable.js": 100,
  11831. "./lib/_stream_transform.js": 101,
  11832. "./lib/_stream_writable.js": 102
  11833. }],
  11834. 109: [function(require, module, exports) {
  11835. 'use strict'
  11836. function ReInterval(callback, interval, args) {
  11837. var self = this;
  11838. this._callback = callback;
  11839. this._args = args;
  11840. this._interval = setInterval(callback, interval, this._args);
  11841. this.reschedule = function(interval) {
  11842. // if no interval entered, use the interval passed in on creation
  11843. if (!interval)
  11844. interval = self._interval;
  11845. if (self._interval)
  11846. clearInterval(self._interval);
  11847. self._interval = setInterval(self._callback, interval, self._args);
  11848. };
  11849. this.clear = function() {
  11850. if (self._interval) {
  11851. clearInterval(self._interval);
  11852. self._interval = undefined;
  11853. }
  11854. };
  11855. this.destroy = function() {
  11856. if (self._interval) {
  11857. clearInterval(self._interval);
  11858. }
  11859. self._callback = undefined;
  11860. self._interval = undefined;
  11861. self._args = undefined;
  11862. };
  11863. }
  11864. function reInterval() {
  11865. if (typeof arguments[0] !== 'function')
  11866. throw new Error('callback needed');
  11867. if (typeof arguments[1] !== 'number')
  11868. throw new Error('interval needed');
  11869. var args;
  11870. if (arguments.length > 0) {
  11871. args = new Array(arguments.length - 2);
  11872. for (var i = 0; i < args.length; i++) {
  11873. args[i] = arguments[i + 2];
  11874. }
  11875. }
  11876. return new ReInterval(arguments[0], arguments[1], args);
  11877. }
  11878. module.exports = reInterval;
  11879. }, {}],
  11880. 110: [function(require, module, exports) {
  11881. /* eslint-disable node/no-deprecated-api */
  11882. var buffer = require('buffer')
  11883. var Buffer = buffer.Buffer
  11884. // alternative to using Object.keys for old browsers
  11885. function copyProps(src, dst) {
  11886. for (var key in src) {
  11887. dst[key] = src[key]
  11888. }
  11889. }
  11890. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  11891. module.exports = buffer
  11892. } else {
  11893. // Copy properties from require('buffer')
  11894. copyProps(buffer, exports)
  11895. exports.Buffer = SafeBuffer
  11896. }
  11897. function SafeBuffer(arg, encodingOrOffset, length) {
  11898. return Buffer(arg, encodingOrOffset, length)
  11899. }
  11900. // Copy static methods from Buffer
  11901. copyProps(Buffer, SafeBuffer)
  11902. SafeBuffer.from = function(arg, encodingOrOffset, length) {
  11903. if (typeof arg === 'number') {
  11904. throw new TypeError('Argument must not be a number')
  11905. }
  11906. return Buffer(arg, encodingOrOffset, length)
  11907. }
  11908. SafeBuffer.alloc = function(size, fill, encoding) {
  11909. if (typeof size !== 'number') {
  11910. throw new TypeError('Argument must be a number')
  11911. }
  11912. var buf = Buffer(size)
  11913. if (fill !== undefined) {
  11914. if (typeof encoding === 'string') {
  11915. buf.fill(fill, encoding)
  11916. } else {
  11917. buf.fill(fill)
  11918. }
  11919. } else {
  11920. buf.fill(0)
  11921. }
  11922. return buf
  11923. }
  11924. SafeBuffer.allocUnsafe = function(size) {
  11925. if (typeof size !== 'number') {
  11926. throw new TypeError('Argument must be a number')
  11927. }
  11928. return Buffer(size)
  11929. }
  11930. SafeBuffer.allocUnsafeSlow = function(size) {
  11931. if (typeof size !== 'number') {
  11932. throw new TypeError('Argument must be a number')
  11933. }
  11934. return buffer.SlowBuffer(size)
  11935. }
  11936. }, {
  11937. "buffer": 12
  11938. }],
  11939. 111: [function(require, module, exports) {
  11940. module.exports = shift
  11941. function shift(stream) {
  11942. var rs = stream._readableState
  11943. if (!rs) return null
  11944. return rs.objectMode ? stream.read() : stream.read(getStateLength(rs))
  11945. }
  11946. function getStateLength(state) {
  11947. if (state.buffer.length) {
  11948. // Since node 6.3.0 state.buffer is a BufferList not an array
  11949. if (state.buffer.head) {
  11950. return state.buffer.head.data.length
  11951. }
  11952. return state.buffer[0].length
  11953. }
  11954. return state.length
  11955. }
  11956. }, {}],
  11957. 112: [function(require, module, exports) {
  11958. (function(setImmediate, clearImmediate) {
  11959. var nextTick = require('process/browser.js').nextTick;
  11960. var apply = Function.prototype.apply;
  11961. var slice = Array.prototype.slice;
  11962. var immediateIds = {};
  11963. var nextImmediateId = 0;
  11964. // DOM APIs, for completeness
  11965. exports.setTimeout = function() {
  11966. return new Timeout(apply.call(setTimeout, window, arguments),
  11967. clearTimeout);
  11968. };
  11969. exports.setInterval = function() {
  11970. return new Timeout(apply.call(setInterval, window, arguments),
  11971. clearInterval);
  11972. };
  11973. exports.clearTimeout =
  11974. exports.clearInterval = function(timeout) {
  11975. timeout.close();
  11976. };
  11977. function Timeout(id, clearFn) {
  11978. this._id = id;
  11979. this._clearFn = clearFn;
  11980. }
  11981. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  11982. Timeout.prototype.close = function() {
  11983. this._clearFn.call(window, this._id);
  11984. };
  11985. // Does not start the time, just sets up the members needed.
  11986. exports.enroll = function(item, msecs) {
  11987. clearTimeout(item._idleTimeoutId);
  11988. item._idleTimeout = msecs;
  11989. };
  11990. exports.unenroll = function(item) {
  11991. clearTimeout(item._idleTimeoutId);
  11992. item._idleTimeout = -1;
  11993. };
  11994. exports._unrefActive = exports.active = function(item) {
  11995. clearTimeout(item._idleTimeoutId);
  11996. var msecs = item._idleTimeout;
  11997. if (msecs >= 0) {
  11998. item._idleTimeoutId = setTimeout(function onTimeout() {
  11999. if (item._onTimeout)
  12000. item._onTimeout();
  12001. }, msecs);
  12002. }
  12003. };
  12004. // That's not how node.js implements it but the exposed api is the same.
  12005. exports.setImmediate = typeof setImmediate === "function" ? setImmediate :
  12006. function(fn) {
  12007. var id = nextImmediateId++;
  12008. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  12009. immediateIds[id] = true;
  12010. nextTick(function onNextTick() {
  12011. if (immediateIds[id]) {
  12012. // fn.call() is faster so we optimize for the common use-case
  12013. // @see http://jsperf.com/call-apply-segu
  12014. if (args) {
  12015. fn.apply(null, args);
  12016. } else {
  12017. fn.call(null);
  12018. }
  12019. // Prevent ids from leaking
  12020. exports.clearImmediate(id);
  12021. }
  12022. });
  12023. return id;
  12024. };
  12025. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate :
  12026. function(id) {
  12027. delete immediateIds[id];
  12028. };
  12029. }).call(this, require("timers").setImmediate, require("timers").clearImmediate)
  12030. }, {
  12031. "process/browser.js": 92,
  12032. "timers": 112
  12033. }],
  12034. 113: [function(require, module, exports) {
  12035. // Copyright Joyent, Inc. and other Node contributors.
  12036. //
  12037. // Permission is hereby granted, free of charge, to any person obtaining a
  12038. // copy of this software and associated documentation files (the
  12039. // "Software"), to deal in the Software without restriction, including
  12040. // without limitation the rights to use, copy, modify, merge, publish,
  12041. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12042. // persons to whom the Software is furnished to do so, subject to the
  12043. // following conditions:
  12044. //
  12045. // The above copyright notice and this permission notice shall be included
  12046. // in all copies or substantial portions of the Software.
  12047. //
  12048. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12049. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12050. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12051. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12052. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12053. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12054. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12055. 'use strict';
  12056. var punycode = require('punycode');
  12057. var util = require('./util');
  12058. exports.parse = urlParse;
  12059. exports.resolve = urlResolve;
  12060. exports.resolveObject = urlResolveObject;
  12061. exports.format = urlFormat;
  12062. exports.Url = Url;
  12063. function Url() {
  12064. this.protocol = null;
  12065. this.slashes = null;
  12066. this.auth = null;
  12067. this.host = null;
  12068. this.port = null;
  12069. this.hostname = null;
  12070. this.hash = null;
  12071. this.search = null;
  12072. this.query = null;
  12073. this.pathname = null;
  12074. this.path = null;
  12075. this.href = null;
  12076. }
  12077. // Reference: RFC 3986, RFC 1808, RFC 2396
  12078. // define these here so at least they only have to be
  12079. // compiled once on the first module load.
  12080. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  12081. portPattern = /:[0-9]*$/,
  12082. // Special case for a simple path URL
  12083. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  12084. // RFC 2396: characters reserved for delimiting URLs.
  12085. // We actually just auto-escape these.
  12086. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  12087. // RFC 2396: characters not allowed for various reasons.
  12088. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  12089. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  12090. autoEscape = ['\''].concat(unwise),
  12091. // Characters that are never ever allowed in a hostname.
  12092. // Note that any invalid chars are also handled, but these
  12093. // are the ones that are *expected* to be seen, so we fast-path
  12094. // them.
  12095. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  12096. hostEndingChars = ['/', '?', '#'],
  12097. hostnameMaxLen = 255,
  12098. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  12099. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  12100. // protocols that can allow "unsafe" and "unwise" chars.
  12101. unsafeProtocol = {
  12102. 'javascript': true,
  12103. 'javascript:': true
  12104. },
  12105. // protocols that never have a hostname.
  12106. hostlessProtocol = {
  12107. 'javascript': true,
  12108. 'javascript:': true
  12109. },
  12110. // protocols that always contain a // bit.
  12111. slashedProtocol = {
  12112. 'http': true,
  12113. 'https': true,
  12114. 'ftp': true,
  12115. 'gopher': true,
  12116. 'file': true,
  12117. 'http:': true,
  12118. 'https:': true,
  12119. 'ftp:': true,
  12120. 'gopher:': true,
  12121. 'file:': true
  12122. },
  12123. querystring = require('querystring');
  12124. function urlParse(url, parseQueryString, slashesDenoteHost) {
  12125. if (url && util.isObject(url) && url instanceof Url) return url;
  12126. var u = new Url;
  12127. u.parse(url, parseQueryString, slashesDenoteHost);
  12128. return u;
  12129. }
  12130. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  12131. if (!util.isString(url)) {
  12132. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  12133. }
  12134. // Copy chrome, IE, opera backslash-handling behavior.
  12135. // Back slashes before the query string get converted to forward slashes
  12136. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  12137. var queryIndex = url.indexOf('?'),
  12138. splitter =
  12139. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  12140. uSplit = url.split(splitter),
  12141. slashRegex = /\\/g;
  12142. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  12143. url = uSplit.join(splitter);
  12144. var rest = url;
  12145. // trim before proceeding.
  12146. // This is to support parse stuff like " http://foo.com \n"
  12147. rest = rest.trim();
  12148. if (!slashesDenoteHost && url.split('#').length === 1) {
  12149. // Try fast path regexp
  12150. var simplePath = simplePathPattern.exec(rest);
  12151. if (simplePath) {
  12152. this.path = rest;
  12153. this.href = rest;
  12154. this.pathname = simplePath[1];
  12155. if (simplePath[2]) {
  12156. this.search = simplePath[2];
  12157. if (parseQueryString) {
  12158. this.query = querystring.parse(this.search.substr(1));
  12159. } else {
  12160. this.query = this.search.substr(1);
  12161. }
  12162. } else if (parseQueryString) {
  12163. this.search = '';
  12164. this.query = {};
  12165. }
  12166. return this;
  12167. }
  12168. }
  12169. var proto = protocolPattern.exec(rest);
  12170. if (proto) {
  12171. proto = proto[0];
  12172. var lowerProto = proto.toLowerCase();
  12173. this.protocol = lowerProto;
  12174. rest = rest.substr(proto.length);
  12175. }
  12176. // figure out if it's got a host
  12177. // user@server is *always* interpreted as a hostname, and url
  12178. // resolution will treat //foo/bar as host=foo,path=bar because that's
  12179. // how the browser resolves relative URLs.
  12180. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  12181. var slashes = rest.substr(0, 2) === '//';
  12182. if (slashes && !(proto && hostlessProtocol[proto])) {
  12183. rest = rest.substr(2);
  12184. this.slashes = true;
  12185. }
  12186. }
  12187. if (!hostlessProtocol[proto] &&
  12188. (slashes || (proto && !slashedProtocol[proto]))) {
  12189. // there's a hostname.
  12190. // the first instance of /, ?, ;, or # ends the host.
  12191. //
  12192. // If there is an @ in the hostname, then non-host chars *are* allowed
  12193. // to the left of the last @ sign, unless some host-ending character
  12194. // comes *before* the @-sign.
  12195. // URLs are obnoxious.
  12196. //
  12197. // ex:
  12198. // http://a@b@c/ => user:a@b host:c
  12199. // http://a@b?@c => user:a host:c path:/?@c
  12200. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  12201. // Review our test case against browsers more comprehensively.
  12202. // find the first instance of any hostEndingChars
  12203. var hostEnd = -1;
  12204. for (var i = 0; i < hostEndingChars.length; i++) {
  12205. var hec = rest.indexOf(hostEndingChars[i]);
  12206. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  12207. hostEnd = hec;
  12208. }
  12209. // at this point, either we have an explicit point where the
  12210. // auth portion cannot go past, or the last @ char is the decider.
  12211. var auth, atSign;
  12212. if (hostEnd === -1) {
  12213. // atSign can be anywhere.
  12214. atSign = rest.lastIndexOf('@');
  12215. } else {
  12216. // atSign must be in auth portion.
  12217. // http://a@b/c@d => host:b auth:a path:/c@d
  12218. atSign = rest.lastIndexOf('@', hostEnd);
  12219. }
  12220. // Now we have a portion which is definitely the auth.
  12221. // Pull that off.
  12222. if (atSign !== -1) {
  12223. auth = rest.slice(0, atSign);
  12224. rest = rest.slice(atSign + 1);
  12225. this.auth = decodeURIComponent(auth);
  12226. }
  12227. // the host is the remaining to the left of the first non-host char
  12228. hostEnd = -1;
  12229. for (var i = 0; i < nonHostChars.length; i++) {
  12230. var hec = rest.indexOf(nonHostChars[i]);
  12231. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  12232. hostEnd = hec;
  12233. }
  12234. // if we still have not hit it, then the entire thing is a host.
  12235. if (hostEnd === -1)
  12236. hostEnd = rest.length;
  12237. this.host = rest.slice(0, hostEnd);
  12238. rest = rest.slice(hostEnd);
  12239. // pull out port.
  12240. this.parseHost();
  12241. // we've indicated that there is a hostname,
  12242. // so even if it's empty, it has to be present.
  12243. this.hostname = this.hostname || '';
  12244. // if hostname begins with [ and ends with ]
  12245. // assume that it's an IPv6 address.
  12246. var ipv6Hostname = this.hostname[0] === '[' &&
  12247. this.hostname[this.hostname.length - 1] === ']';
  12248. // validate a little.
  12249. if (!ipv6Hostname) {
  12250. var hostparts = this.hostname.split(/\./);
  12251. for (var i = 0, l = hostparts.length; i < l; i++) {
  12252. var part = hostparts[i];
  12253. if (!part) continue;
  12254. if (!part.match(hostnamePartPattern)) {
  12255. var newpart = '';
  12256. for (var j = 0, k = part.length; j < k; j++) {
  12257. if (part.charCodeAt(j) > 127) {
  12258. // we replace non-ASCII char with a temporary placeholder
  12259. // we need this to make sure size of hostname is not
  12260. // broken by replacing non-ASCII by nothing
  12261. newpart += 'x';
  12262. } else {
  12263. newpart += part[j];
  12264. }
  12265. }
  12266. // we test again with ASCII char only
  12267. if (!newpart.match(hostnamePartPattern)) {
  12268. var validParts = hostparts.slice(0, i);
  12269. var notHost = hostparts.slice(i + 1);
  12270. var bit = part.match(hostnamePartStart);
  12271. if (bit) {
  12272. validParts.push(bit[1]);
  12273. notHost.unshift(bit[2]);
  12274. }
  12275. if (notHost.length) {
  12276. rest = '/' + notHost.join('.') + rest;
  12277. }
  12278. this.hostname = validParts.join('.');
  12279. break;
  12280. }
  12281. }
  12282. }
  12283. }
  12284. if (this.hostname.length > hostnameMaxLen) {
  12285. this.hostname = '';
  12286. } else {
  12287. // hostnames are always lower case.
  12288. this.hostname = this.hostname.toLowerCase();
  12289. }
  12290. if (!ipv6Hostname) {
  12291. // IDNA Support: Returns a punycoded representation of "domain".
  12292. // It only converts parts of the domain name that
  12293. // have non-ASCII characters, i.e. it doesn't matter if
  12294. // you call it with a domain that already is ASCII-only.
  12295. this.hostname = punycode.toASCII(this.hostname);
  12296. }
  12297. var p = this.port ? ':' + this.port : '';
  12298. var h = this.hostname || '';
  12299. this.host = h + p;
  12300. this.href += this.host;
  12301. // strip [ and ] from the hostname
  12302. // the host field still retains them, though
  12303. if (ipv6Hostname) {
  12304. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  12305. if (rest[0] !== '/') {
  12306. rest = '/' + rest;
  12307. }
  12308. }
  12309. }
  12310. // now rest is set to the post-host stuff.
  12311. // chop off any delim chars.
  12312. if (!unsafeProtocol[lowerProto]) {
  12313. // First, make 100% sure that any "autoEscape" chars get
  12314. // escaped, even if encodeURIComponent doesn't think they
  12315. // need to be.
  12316. for (var i = 0, l = autoEscape.length; i < l; i++) {
  12317. var ae = autoEscape[i];
  12318. if (rest.indexOf(ae) === -1)
  12319. continue;
  12320. var esc = encodeURIComponent(ae);
  12321. if (esc === ae) {
  12322. esc = escape(ae);
  12323. }
  12324. rest = rest.split(ae).join(esc);
  12325. }
  12326. }
  12327. // chop off from the tail first.
  12328. var hash = rest.indexOf('#');
  12329. if (hash !== -1) {
  12330. // got a fragment string.
  12331. this.hash = rest.substr(hash);
  12332. rest = rest.slice(0, hash);
  12333. }
  12334. var qm = rest.indexOf('?');
  12335. if (qm !== -1) {
  12336. this.search = rest.substr(qm);
  12337. this.query = rest.substr(qm + 1);
  12338. if (parseQueryString) {
  12339. this.query = querystring.parse(this.query);
  12340. }
  12341. rest = rest.slice(0, qm);
  12342. } else if (parseQueryString) {
  12343. // no query string, but parseQueryString still requested
  12344. this.search = '';
  12345. this.query = {};
  12346. }
  12347. if (rest) this.pathname = rest;
  12348. if (slashedProtocol[lowerProto] &&
  12349. this.hostname && !this.pathname) {
  12350. this.pathname = '/';
  12351. }
  12352. //to support http.request
  12353. if (this.pathname || this.search) {
  12354. var p = this.pathname || '';
  12355. var s = this.search || '';
  12356. this.path = p + s;
  12357. }
  12358. // finally, reconstruct the href based on what has been validated.
  12359. this.href = this.format();
  12360. return this;
  12361. };
  12362. // format a parsed object into a url string
  12363. function urlFormat(obj) {
  12364. // ensure it's an object, and not a string url.
  12365. // If it's an obj, this is a no-op.
  12366. // this way, you can call url_format() on strings
  12367. // to clean up potentially wonky urls.
  12368. if (util.isString(obj)) obj = urlParse(obj);
  12369. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  12370. return obj.format();
  12371. }
  12372. Url.prototype.format = function() {
  12373. var auth = this.auth || '';
  12374. if (auth) {
  12375. auth = encodeURIComponent(auth);
  12376. auth = auth.replace(/%3A/i, ':');
  12377. auth += '@';
  12378. }
  12379. var protocol = this.protocol || '',
  12380. pathname = this.pathname || '',
  12381. hash = this.hash || '',
  12382. host = false,
  12383. query = '';
  12384. if (this.host) {
  12385. host = auth + this.host;
  12386. } else if (this.hostname) {
  12387. host = auth + (this.hostname.indexOf(':') === -1 ?
  12388. this.hostname :
  12389. '[' + this.hostname + ']');
  12390. if (this.port) {
  12391. host += ':' + this.port;
  12392. }
  12393. }
  12394. if (this.query &&
  12395. util.isObject(this.query) &&
  12396. Object.keys(this.query).length) {
  12397. query = querystring.stringify(this.query);
  12398. }
  12399. var search = this.search || (query && ('?' + query)) || '';
  12400. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  12401. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  12402. // unless they had them to begin with.
  12403. if (this.slashes ||
  12404. (!protocol || slashedProtocol[protocol]) && host !== false) {
  12405. host = '//' + (host || '');
  12406. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  12407. } else if (!host) {
  12408. host = '';
  12409. }
  12410. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  12411. if (search && search.charAt(0) !== '?') search = '?' + search;
  12412. pathname = pathname.replace(/[?#]/g, function(match) {
  12413. return encodeURIComponent(match);
  12414. });
  12415. search = search.replace('#', '%23');
  12416. return protocol + host + pathname + search + hash;
  12417. };
  12418. function urlResolve(source, relative) {
  12419. return urlParse(source, false, true).resolve(relative);
  12420. }
  12421. Url.prototype.resolve = function(relative) {
  12422. return this.resolveObject(urlParse(relative, false, true)).format();
  12423. };
  12424. function urlResolveObject(source, relative) {
  12425. if (!source) return relative;
  12426. return urlParse(source, false, true).resolveObject(relative);
  12427. }
  12428. Url.prototype.resolveObject = function(relative) {
  12429. if (util.isString(relative)) {
  12430. var rel = new Url();
  12431. rel.parse(relative, false, true);
  12432. relative = rel;
  12433. }
  12434. var result = new Url();
  12435. var tkeys = Object.keys(this);
  12436. for (var tk = 0; tk < tkeys.length; tk++) {
  12437. var tkey = tkeys[tk];
  12438. result[tkey] = this[tkey];
  12439. }
  12440. // hash is always overridden, no matter what.
  12441. // even href="" will remove it.
  12442. result.hash = relative.hash;
  12443. // if the relative url is empty, then there's nothing left to do here.
  12444. if (relative.href === '') {
  12445. result.href = result.format();
  12446. return result;
  12447. }
  12448. // hrefs like //foo/bar always cut to the protocol.
  12449. if (relative.slashes && !relative.protocol) {
  12450. // take everything except the protocol from relative
  12451. var rkeys = Object.keys(relative);
  12452. for (var rk = 0; rk < rkeys.length; rk++) {
  12453. var rkey = rkeys[rk];
  12454. if (rkey !== 'protocol')
  12455. result[rkey] = relative[rkey];
  12456. }
  12457. //urlParse appends trailing / to urls like http://www.example.com
  12458. if (slashedProtocol[result.protocol] &&
  12459. result.hostname && !result.pathname) {
  12460. result.path = result.pathname = '/';
  12461. }
  12462. result.href = result.format();
  12463. return result;
  12464. }
  12465. if (relative.protocol && relative.protocol !== result.protocol) {
  12466. // if it's a known url protocol, then changing
  12467. // the protocol does weird things
  12468. // first, if it's not file:, then we MUST have a host,
  12469. // and if there was a path
  12470. // to begin with, then we MUST have a path.
  12471. // if it is file:, then the host is dropped,
  12472. // because that's known to be hostless.
  12473. // anything else is assumed to be absolute.
  12474. if (!slashedProtocol[relative.protocol]) {
  12475. var keys = Object.keys(relative);
  12476. for (var v = 0; v < keys.length; v++) {
  12477. var k = keys[v];
  12478. result[k] = relative[k];
  12479. }
  12480. result.href = result.format();
  12481. return result;
  12482. }
  12483. result.protocol = relative.protocol;
  12484. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  12485. var relPath = (relative.pathname || '').split('/');
  12486. while (relPath.length && !(relative.host = relPath.shift()));
  12487. if (!relative.host) relative.host = '';
  12488. if (!relative.hostname) relative.hostname = '';
  12489. if (relPath[0] !== '') relPath.unshift('');
  12490. if (relPath.length < 2) relPath.unshift('');
  12491. result.pathname = relPath.join('/');
  12492. } else {
  12493. result.pathname = relative.pathname;
  12494. }
  12495. result.search = relative.search;
  12496. result.query = relative.query;
  12497. result.host = relative.host || '';
  12498. result.auth = relative.auth;
  12499. result.hostname = relative.hostname || relative.host;
  12500. result.port = relative.port;
  12501. // to support http.request
  12502. if (result.pathname || result.search) {
  12503. var p = result.pathname || '';
  12504. var s = result.search || '';
  12505. result.path = p + s;
  12506. }
  12507. result.slashes = result.slashes || relative.slashes;
  12508. result.href = result.format();
  12509. return result;
  12510. }
  12511. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  12512. isRelAbs = (
  12513. relative.host ||
  12514. relative.pathname && relative.pathname.charAt(0) === '/'
  12515. ),
  12516. mustEndAbs = (isRelAbs || isSourceAbs ||
  12517. (result.host && relative.pathname)),
  12518. removeAllDots = mustEndAbs,
  12519. srcPath = result.pathname && result.pathname.split('/') || [],
  12520. relPath = relative.pathname && relative.pathname.split('/') || [],
  12521. psychotic = result.protocol && !slashedProtocol[result.protocol];
  12522. // if the url is a non-slashed url, then relative
  12523. // links like ../.. should be able
  12524. // to crawl up to the hostname, as well. This is strange.
  12525. // result.protocol has already been set by now.
  12526. // Later on, put the first path part into the host field.
  12527. if (psychotic) {
  12528. result.hostname = '';
  12529. result.port = null;
  12530. if (result.host) {
  12531. if (srcPath[0] === '') srcPath[0] = result.host;
  12532. else srcPath.unshift(result.host);
  12533. }
  12534. result.host = '';
  12535. if (relative.protocol) {
  12536. relative.hostname = null;
  12537. relative.port = null;
  12538. if (relative.host) {
  12539. if (relPath[0] === '') relPath[0] = relative.host;
  12540. else relPath.unshift(relative.host);
  12541. }
  12542. relative.host = null;
  12543. }
  12544. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  12545. }
  12546. if (isRelAbs) {
  12547. // it's absolute.
  12548. result.host = (relative.host || relative.host === '') ?
  12549. relative.host : result.host;
  12550. result.hostname = (relative.hostname || relative.hostname === '') ?
  12551. relative.hostname : result.hostname;
  12552. result.search = relative.search;
  12553. result.query = relative.query;
  12554. srcPath = relPath;
  12555. // fall through to the dot-handling below.
  12556. } else if (relPath.length) {
  12557. // it's relative
  12558. // throw away the existing file, and take the new path instead.
  12559. if (!srcPath) srcPath = [];
  12560. srcPath.pop();
  12561. srcPath = srcPath.concat(relPath);
  12562. result.search = relative.search;
  12563. result.query = relative.query;
  12564. } else if (!util.isNullOrUndefined(relative.search)) {
  12565. // just pull out the search.
  12566. // like href='?foo'.
  12567. // Put this after the other two cases because it simplifies the booleans
  12568. if (psychotic) {
  12569. result.hostname = result.host = srcPath.shift();
  12570. //occationaly the auth can get stuck only in host
  12571. //this especially happens in cases like
  12572. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  12573. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  12574. result.host.split('@') : false;
  12575. if (authInHost) {
  12576. result.auth = authInHost.shift();
  12577. result.host = result.hostname = authInHost.shift();
  12578. }
  12579. }
  12580. result.search = relative.search;
  12581. result.query = relative.query;
  12582. //to support http.request
  12583. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  12584. result.path = (result.pathname ? result.pathname : '') +
  12585. (result.search ? result.search : '');
  12586. }
  12587. result.href = result.format();
  12588. return result;
  12589. }
  12590. if (!srcPath.length) {
  12591. // no path at all. easy.
  12592. // we've already handled the other stuff above.
  12593. result.pathname = null;
  12594. //to support http.request
  12595. if (result.search) {
  12596. result.path = '/' + result.search;
  12597. } else {
  12598. result.path = null;
  12599. }
  12600. result.href = result.format();
  12601. return result;
  12602. }
  12603. // if a url ENDs in . or .., then it must get a trailing slash.
  12604. // however, if it ends in anything else non-slashy,
  12605. // then it must NOT get a trailing slash.
  12606. var last = srcPath.slice(-1)[0];
  12607. var hasTrailingSlash = (
  12608. (result.host || relative.host || srcPath.length > 1) &&
  12609. (last === '.' || last === '..') || last === '');
  12610. // strip single dots, resolve double dots to parent dir
  12611. // if the path tries to go above the root, `up` ends up > 0
  12612. var up = 0;
  12613. for (var i = srcPath.length; i >= 0; i--) {
  12614. last = srcPath[i];
  12615. if (last === '.') {
  12616. srcPath.splice(i, 1);
  12617. } else if (last === '..') {
  12618. srcPath.splice(i, 1);
  12619. up++;
  12620. } else if (up) {
  12621. srcPath.splice(i, 1);
  12622. up--;
  12623. }
  12624. }
  12625. // if the path is allowed to go above the root, restore leading ..s
  12626. if (!mustEndAbs && !removeAllDots) {
  12627. for (; up--; up) {
  12628. srcPath.unshift('..');
  12629. }
  12630. }
  12631. if (mustEndAbs && srcPath[0] !== '' &&
  12632. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  12633. srcPath.unshift('');
  12634. }
  12635. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  12636. srcPath.push('');
  12637. }
  12638. var isAbsolute = srcPath[0] === '' ||
  12639. (srcPath[0] && srcPath[0].charAt(0) === '/');
  12640. // put the host back
  12641. if (psychotic) {
  12642. result.hostname = result.host = isAbsolute ? '' :
  12643. srcPath.length ? srcPath.shift() : '';
  12644. //occationaly the auth can get stuck only in host
  12645. //this especially happens in cases like
  12646. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  12647. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  12648. result.host.split('@') : false;
  12649. if (authInHost) {
  12650. result.auth = authInHost.shift();
  12651. result.host = result.hostname = authInHost.shift();
  12652. }
  12653. }
  12654. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  12655. if (mustEndAbs && !isAbsolute) {
  12656. srcPath.unshift('');
  12657. }
  12658. if (!srcPath.length) {
  12659. result.pathname = null;
  12660. result.path = null;
  12661. } else {
  12662. result.pathname = srcPath.join('/');
  12663. }
  12664. //to support request.http
  12665. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  12666. result.path = (result.pathname ? result.pathname : '') +
  12667. (result.search ? result.search : '');
  12668. }
  12669. result.auth = relative.auth || result.auth;
  12670. result.slashes = result.slashes || relative.slashes;
  12671. result.href = result.format();
  12672. return result;
  12673. };
  12674. Url.prototype.parseHost = function() {
  12675. var host = this.host;
  12676. var port = portPattern.exec(host);
  12677. if (port) {
  12678. port = port[0];
  12679. if (port !== ':') {
  12680. this.port = port.substr(1);
  12681. }
  12682. host = host.substr(0, host.length - port.length);
  12683. }
  12684. if (host) this.hostname = host;
  12685. };
  12686. }, {
  12687. "./util": 114,
  12688. "punycode": 93,
  12689. "querystring": 96
  12690. }],
  12691. 114: [function(require, module, exports) {
  12692. 'use strict';
  12693. module.exports = {
  12694. isString: function(arg) {
  12695. return typeof(arg) === 'string';
  12696. },
  12697. isObject: function(arg) {
  12698. return typeof(arg) === 'object' && arg !== null;
  12699. },
  12700. isNull: function(arg) {
  12701. return arg === null;
  12702. },
  12703. isNullOrUndefined: function(arg) {
  12704. return arg == null;
  12705. }
  12706. };
  12707. }, {}],
  12708. 115: [function(require, module, exports) {
  12709. (function(global) {
  12710. /**
  12711. * Module exports.
  12712. */
  12713. module.exports = deprecate;
  12714. /**
  12715. * Mark that a method should not be used.
  12716. * Returns a modified function which warns once by default.
  12717. *
  12718. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  12719. *
  12720. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  12721. * will throw an Error when invoked.
  12722. *
  12723. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  12724. * will invoke `console.trace()` instead of `console.error()`.
  12725. *
  12726. * @param {Function} fn - the function to deprecate
  12727. * @param {String} msg - the string to print to the console when `fn` is invoked
  12728. * @returns {Function} a new "deprecated" version of `fn`
  12729. * @api public
  12730. */
  12731. function deprecate(fn, msg) {
  12732. if (config('noDeprecation')) {
  12733. return fn;
  12734. }
  12735. var warned = false;
  12736. function deprecated() {
  12737. if (!warned) {
  12738. if (config('throwDeprecation')) {
  12739. throw new Error(msg);
  12740. } else if (config('traceDeprecation')) {
  12741. console.trace(msg);
  12742. } else {
  12743. console.warn(msg);
  12744. }
  12745. warned = true;
  12746. }
  12747. return fn.apply(this, arguments);
  12748. }
  12749. return deprecated;
  12750. }
  12751. /**
  12752. * Checks `localStorage` for boolean values for the given `name`.
  12753. *
  12754. * @param {String} name
  12755. * @returns {Boolean}
  12756. * @api private
  12757. */
  12758. function config(name) {
  12759. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  12760. try {
  12761. if (!global.localStorage) return false;
  12762. } catch (_) {
  12763. return false;
  12764. }
  12765. var val = global.localStorage[name];
  12766. if (null == val) return false;
  12767. return String(val).toLowerCase() === 'true';
  12768. }
  12769. }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ?
  12770. self : typeof window !== "undefined" ? window : {})
  12771. }, {}],
  12772. 116: [function(require, module, exports) {
  12773. module.exports = function isBuffer(arg) {
  12774. return arg && typeof arg === 'object' &&
  12775. typeof arg.copy === 'function' &&
  12776. typeof arg.fill === 'function' &&
  12777. typeof arg.readUInt8 === 'function';
  12778. }
  12779. }, {}],
  12780. 117: [function(require, module, exports) {
  12781. (function(process, global) {
  12782. // Copyright Joyent, Inc. and other Node contributors.
  12783. //
  12784. // Permission is hereby granted, free of charge, to any person obtaining a
  12785. // copy of this software and associated documentation files (the
  12786. // "Software"), to deal in the Software without restriction, including
  12787. // without limitation the rights to use, copy, modify, merge, publish,
  12788. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12789. // persons to whom the Software is furnished to do so, subject to the
  12790. // following conditions:
  12791. //
  12792. // The above copyright notice and this permission notice shall be included
  12793. // in all copies or substantial portions of the Software.
  12794. //
  12795. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12796. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12797. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12798. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12799. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12800. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12801. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12802. var formatRegExp = /%[sdj%]/g;
  12803. exports.format = function(f) {
  12804. if (!isString(f)) {
  12805. var objects = [];
  12806. for (var i = 0; i < arguments.length; i++) {
  12807. objects.push(inspect(arguments[i]));
  12808. }
  12809. return objects.join(' ');
  12810. }
  12811. var i = 1;
  12812. var args = arguments;
  12813. var len = args.length;
  12814. var str = String(f).replace(formatRegExp, function(x) {
  12815. if (x === '%%') return '%';
  12816. if (i >= len) return x;
  12817. switch (x) {
  12818. case '%s':
  12819. return String(args[i++]);
  12820. case '%d':
  12821. return Number(args[i++]);
  12822. case '%j':
  12823. try {
  12824. return JSON.stringify(args[i++]);
  12825. } catch (_) {
  12826. return '[Circular]';
  12827. }
  12828. default:
  12829. return x;
  12830. }
  12831. });
  12832. for (var x = args[i]; i < len; x = args[++i]) {
  12833. if (isNull(x) || !isObject(x)) {
  12834. str += ' ' + x;
  12835. } else {
  12836. str += ' ' + inspect(x);
  12837. }
  12838. }
  12839. return str;
  12840. };
  12841. // Mark that a method should not be used.
  12842. // Returns a modified function which warns once by default.
  12843. // If --no-deprecation is set, then it is a no-op.
  12844. exports.deprecate = function(fn, msg) {
  12845. // Allow for deprecating things in the process of starting up.
  12846. if (isUndefined(global.process)) {
  12847. return function() {
  12848. return exports.deprecate(fn, msg).apply(this, arguments);
  12849. };
  12850. }
  12851. if (process.noDeprecation === true) {
  12852. return fn;
  12853. }
  12854. var warned = false;
  12855. function deprecated() {
  12856. if (!warned) {
  12857. if (process.throwDeprecation) {
  12858. throw new Error(msg);
  12859. } else if (process.traceDeprecation) {
  12860. console.trace(msg);
  12861. } else {
  12862. console.error(msg);
  12863. }
  12864. warned = true;
  12865. }
  12866. return fn.apply(this, arguments);
  12867. }
  12868. return deprecated;
  12869. };
  12870. var debugs = {};
  12871. var debugEnviron;
  12872. exports.debuglog = function(set) {
  12873. if (isUndefined(debugEnviron))
  12874. debugEnviron = process.env.NODE_DEBUG || '';
  12875. set = set.toUpperCase();
  12876. if (!debugs[set]) {
  12877. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  12878. var pid = process.pid;
  12879. debugs[set] = function() {
  12880. var msg = exports.format.apply(exports, arguments);
  12881. console.error('%s %d: %s', set, pid, msg);
  12882. };
  12883. } else {
  12884. debugs[set] = function() {};
  12885. }
  12886. }
  12887. return debugs[set];
  12888. };
  12889. /**
  12890. * Echos the value of a value. Trys to print the value out
  12891. * in the best way possible given the different types.
  12892. *
  12893. * @param {Object} obj The object to print out.
  12894. * @param {Object} opts Optional options object that alters the output.
  12895. */
  12896. /* legacy: obj, showHidden, depth, colors*/
  12897. function inspect(obj, opts) {
  12898. // default options
  12899. var ctx = {
  12900. seen: [],
  12901. stylize: stylizeNoColor
  12902. };
  12903. // legacy...
  12904. if (arguments.length >= 3) ctx.depth = arguments[2];
  12905. if (arguments.length >= 4) ctx.colors = arguments[3];
  12906. if (isBoolean(opts)) {
  12907. // legacy...
  12908. ctx.showHidden = opts;
  12909. } else if (opts) {
  12910. // got an "options" object
  12911. exports._extend(ctx, opts);
  12912. }
  12913. // set default options
  12914. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  12915. if (isUndefined(ctx.depth)) ctx.depth = 2;
  12916. if (isUndefined(ctx.colors)) ctx.colors = false;
  12917. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  12918. if (ctx.colors) ctx.stylize = stylizeWithColor;
  12919. return formatValue(ctx, obj, ctx.depth);
  12920. }
  12921. exports.inspect = inspect;
  12922. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  12923. inspect.colors = {
  12924. 'bold': [1, 22],
  12925. 'italic': [3, 23],
  12926. 'underline': [4, 24],
  12927. 'inverse': [7, 27],
  12928. 'white': [37, 39],
  12929. 'grey': [90, 39],
  12930. 'black': [30, 39],
  12931. 'blue': [34, 39],
  12932. 'cyan': [36, 39],
  12933. 'green': [32, 39],
  12934. 'magenta': [35, 39],
  12935. 'red': [31, 39],
  12936. 'yellow': [33, 39]
  12937. };
  12938. // Don't use 'blue' not visible on cmd.exe
  12939. inspect.styles = {
  12940. 'special': 'cyan',
  12941. 'number': 'yellow',
  12942. 'boolean': 'yellow',
  12943. 'undefined': 'grey',
  12944. 'null': 'bold',
  12945. 'string': 'green',
  12946. 'date': 'magenta',
  12947. // "name": intentionally not styling
  12948. 'regexp': 'red'
  12949. };
  12950. function stylizeWithColor(str, styleType) {
  12951. var style = inspect.styles[styleType];
  12952. if (style) {
  12953. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  12954. '\u001b[' + inspect.colors[style][1] + 'm';
  12955. } else {
  12956. return str;
  12957. }
  12958. }
  12959. function stylizeNoColor(str, styleType) {
  12960. return str;
  12961. }
  12962. function arrayToHash(array) {
  12963. var hash = {};
  12964. array.forEach(function(val, idx) {
  12965. hash[val] = true;
  12966. });
  12967. return hash;
  12968. }
  12969. function formatValue(ctx, value, recurseTimes) {
  12970. // Provide a hook for user-specified inspect functions.
  12971. // Check that value is an object with an inspect function on it
  12972. if (ctx.customInspect &&
  12973. value &&
  12974. isFunction(value.inspect) &&
  12975. // Filter out the util module, it's inspect function is special
  12976. value.inspect !== exports.inspect &&
  12977. // Also filter out any prototype objects using the circular check.
  12978. !(value.constructor && value.constructor.prototype === value)) {
  12979. var ret = value.inspect(recurseTimes, ctx);
  12980. if (!isString(ret)) {
  12981. ret = formatValue(ctx, ret, recurseTimes);
  12982. }
  12983. return ret;
  12984. }
  12985. // Primitive types cannot have properties
  12986. var primitive = formatPrimitive(ctx, value);
  12987. if (primitive) {
  12988. return primitive;
  12989. }
  12990. // Look up the keys of the object.
  12991. var keys = Object.keys(value);
  12992. var visibleKeys = arrayToHash(keys);
  12993. if (ctx.showHidden) {
  12994. keys = Object.getOwnPropertyNames(value);
  12995. }
  12996. // IE doesn't make error fields non-enumerable
  12997. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  12998. if (isError(value) &&
  12999. (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  13000. return formatError(value);
  13001. }
  13002. // Some type of object without properties can be shortcutted.
  13003. if (keys.length === 0) {
  13004. if (isFunction(value)) {
  13005. var name = value.name ? ': ' + value.name : '';
  13006. return ctx.stylize('[Function' + name + ']', 'special');
  13007. }
  13008. if (isRegExp(value)) {
  13009. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  13010. }
  13011. if (isDate(value)) {
  13012. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  13013. }
  13014. if (isError(value)) {
  13015. return formatError(value);
  13016. }
  13017. }
  13018. var base = '',
  13019. array = false,
  13020. braces = ['{', '}'];
  13021. // Make Array say that they are Array
  13022. if (isArray(value)) {
  13023. array = true;
  13024. braces = ['[', ']'];
  13025. }
  13026. // Make functions say that they are functions
  13027. if (isFunction(value)) {
  13028. var n = value.name ? ': ' + value.name : '';
  13029. base = ' [Function' + n + ']';
  13030. }
  13031. // Make RegExps say that they are RegExps
  13032. if (isRegExp(value)) {
  13033. base = ' ' + RegExp.prototype.toString.call(value);
  13034. }
  13035. // Make dates with properties first say the date
  13036. if (isDate(value)) {
  13037. base = ' ' + Date.prototype.toUTCString.call(value);
  13038. }
  13039. // Make error with message first say the error
  13040. if (isError(value)) {
  13041. base = ' ' + formatError(value);
  13042. }
  13043. if (keys.length === 0 && (!array || value.length == 0)) {
  13044. return braces[0] + base + braces[1];
  13045. }
  13046. if (recurseTimes < 0) {
  13047. if (isRegExp(value)) {
  13048. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  13049. } else {
  13050. return ctx.stylize('[Object]', 'special');
  13051. }
  13052. }
  13053. ctx.seen.push(value);
  13054. var output;
  13055. if (array) {
  13056. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  13057. } else {
  13058. output = keys.map(function(key) {
  13059. return formatProperty(ctx, value, recurseTimes, visibleKeys,
  13060. key, array);
  13061. });
  13062. }
  13063. ctx.seen.pop();
  13064. return reduceToSingleString(output, base, braces);
  13065. }
  13066. function formatPrimitive(ctx, value) {
  13067. if (isUndefined(value))
  13068. return ctx.stylize('undefined', 'undefined');
  13069. if (isString(value)) {
  13070. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  13071. .replace(/'/g, "\\'")
  13072. .replace(/\\"/g, '"') + '\'';
  13073. return ctx.stylize(simple, 'string');
  13074. }
  13075. if (isNumber(value))
  13076. return ctx.stylize('' + value, 'number');
  13077. if (isBoolean(value))
  13078. return ctx.stylize('' + value, 'boolean');
  13079. // For some reason typeof null is "object", so special case here.
  13080. if (isNull(value))
  13081. return ctx.stylize('null', 'null');
  13082. }
  13083. function formatError(value) {
  13084. return '[' + Error.prototype.toString.call(value) + ']';
  13085. }
  13086. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  13087. var output = [];
  13088. for (var i = 0, l = value.length; i < l; ++i) {
  13089. if (hasOwnProperty(value, String(i))) {
  13090. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  13091. String(i), true));
  13092. } else {
  13093. output.push('');
  13094. }
  13095. }
  13096. keys.forEach(function(key) {
  13097. if (!key.match(/^\d+$/)) {
  13098. output.push(formatProperty(ctx, value, recurseTimes,
  13099. visibleKeys,
  13100. key, true));
  13101. }
  13102. });
  13103. return output;
  13104. }
  13105. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  13106. var name, str, desc;
  13107. desc = Object.getOwnPropertyDescriptor(value, key) || {
  13108. value: value[key]
  13109. };
  13110. if (desc.get) {
  13111. if (desc.set) {
  13112. str = ctx.stylize('[Getter/Setter]', 'special');
  13113. } else {
  13114. str = ctx.stylize('[Getter]', 'special');
  13115. }
  13116. } else {
  13117. if (desc.set) {
  13118. str = ctx.stylize('[Setter]', 'special');
  13119. }
  13120. }
  13121. if (!hasOwnProperty(visibleKeys, key)) {
  13122. name = '[' + key + ']';
  13123. }
  13124. if (!str) {
  13125. if (ctx.seen.indexOf(desc.value) < 0) {
  13126. if (isNull(recurseTimes)) {
  13127. str = formatValue(ctx, desc.value, null);
  13128. } else {
  13129. str = formatValue(ctx, desc.value, recurseTimes - 1);
  13130. }
  13131. if (str.indexOf('\n') > -1) {
  13132. if (array) {
  13133. str = str.split('\n').map(function(line) {
  13134. return ' ' + line;
  13135. }).join('\n').substr(2);
  13136. } else {
  13137. str = '\n' + str.split('\n').map(function(line) {
  13138. return ' ' + line;
  13139. }).join('\n');
  13140. }
  13141. }
  13142. } else {
  13143. str = ctx.stylize('[Circular]', 'special');
  13144. }
  13145. }
  13146. if (isUndefined(name)) {
  13147. if (array && key.match(/^\d+$/)) {
  13148. return str;
  13149. }
  13150. name = JSON.stringify('' + key);
  13151. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  13152. name = name.substr(1, name.length - 2);
  13153. name = ctx.stylize(name, 'name');
  13154. } else {
  13155. name = name.replace(/'/g, "\\'")
  13156. .replace(/\\"/g, '"')
  13157. .replace(/(^"|"$)/g, "'");
  13158. name = ctx.stylize(name, 'string');
  13159. }
  13160. }
  13161. return name + ': ' + str;
  13162. }
  13163. function reduceToSingleString(output, base, braces) {
  13164. var numLinesEst = 0;
  13165. var length = output.reduce(function(prev, cur) {
  13166. numLinesEst++;
  13167. if (cur.indexOf('\n') >= 0) numLinesEst++;
  13168. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  13169. }, 0);
  13170. if (length > 60) {
  13171. return braces[0] +
  13172. (base === '' ? '' : base + '\n ') +
  13173. ' ' +
  13174. output.join(',\n ') +
  13175. ' ' +
  13176. braces[1];
  13177. }
  13178. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  13179. }
  13180. // NOTE: These type checking functions intentionally don't use `instanceof`
  13181. // because it is fragile and can be easily faked with `Object.create()`.
  13182. function isArray(ar) {
  13183. return Array.isArray(ar);
  13184. }
  13185. exports.isArray = isArray;
  13186. function isBoolean(arg) {
  13187. return typeof arg === 'boolean';
  13188. }
  13189. exports.isBoolean = isBoolean;
  13190. function isNull(arg) {
  13191. return arg === null;
  13192. }
  13193. exports.isNull = isNull;
  13194. function isNullOrUndefined(arg) {
  13195. return arg == null;
  13196. }
  13197. exports.isNullOrUndefined = isNullOrUndefined;
  13198. function isNumber(arg) {
  13199. return typeof arg === 'number';
  13200. }
  13201. exports.isNumber = isNumber;
  13202. function isString(arg) {
  13203. return typeof arg === 'string';
  13204. }
  13205. exports.isString = isString;
  13206. function isSymbol(arg) {
  13207. return typeof arg === 'symbol';
  13208. }
  13209. exports.isSymbol = isSymbol;
  13210. function isUndefined(arg) {
  13211. return arg === void 0;
  13212. }
  13213. exports.isUndefined = isUndefined;
  13214. function isRegExp(re) {
  13215. return isObject(re) && objectToString(re) === '[object RegExp]';
  13216. }
  13217. exports.isRegExp = isRegExp;
  13218. function isObject(arg) {
  13219. return typeof arg === 'object' && arg !== null;
  13220. }
  13221. exports.isObject = isObject;
  13222. function isDate(d) {
  13223. return isObject(d) && objectToString(d) === '[object Date]';
  13224. }
  13225. exports.isDate = isDate;
  13226. function isError(e) {
  13227. return isObject(e) &&
  13228. (objectToString(e) === '[object Error]' || e instanceof Error);
  13229. }
  13230. exports.isError = isError;
  13231. function isFunction(arg) {
  13232. return typeof arg === 'function';
  13233. }
  13234. exports.isFunction = isFunction;
  13235. function isPrimitive(arg) {
  13236. return arg === null ||
  13237. typeof arg === 'boolean' ||
  13238. typeof arg === 'number' ||
  13239. typeof arg === 'string' ||
  13240. typeof arg === 'symbol' || // ES6 symbol
  13241. typeof arg === 'undefined';
  13242. }
  13243. exports.isPrimitive = isPrimitive;
  13244. exports.isBuffer = require('./support/isBuffer');
  13245. function objectToString(o) {
  13246. return Object.prototype.toString.call(o);
  13247. }
  13248. function pad(n) {
  13249. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  13250. }
  13251. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  13252. 'Oct', 'Nov', 'Dec'
  13253. ];
  13254. // 26 Feb 16:19:34
  13255. function timestamp() {
  13256. var d = new Date();
  13257. var time = [pad(d.getHours()),
  13258. pad(d.getMinutes()),
  13259. pad(d.getSeconds())
  13260. ].join(':');
  13261. return [d.getDate(), months[d.getMonth()], time].join(' ');
  13262. }
  13263. // log is just a thin wrapper to console.log that prepends a timestamp
  13264. exports.log = function() {
  13265. console.log('%s - %s', timestamp(), exports.format.apply(exports,
  13266. arguments));
  13267. };
  13268. /**
  13269. * Inherit the prototype methods from one constructor into another.
  13270. *
  13271. * The Function.prototype.inherits from lang.js rewritten as a standalone
  13272. * function (not on Function.prototype). NOTE: If this file is to be loaded
  13273. * during bootstrapping this function needs to be rewritten using some native
  13274. * functions as prototype setup using normal JavaScript does not work as
  13275. * expected during bootstrapping (see mirror.js in r114903).
  13276. *
  13277. * @param {function} ctor Constructor function which needs to inherit the
  13278. * prototype.
  13279. * @param {function} superCtor Constructor function to inherit prototype from.
  13280. */
  13281. exports.inherits = require('inherits');
  13282. exports._extend = function(origin, add) {
  13283. // Don't do anything if add isn't an object
  13284. if (!add || !isObject(add)) return origin;
  13285. var keys = Object.keys(add);
  13286. var i = keys.length;
  13287. while (i--) {
  13288. origin[keys[i]] = add[keys[i]];
  13289. }
  13290. return origin;
  13291. };
  13292. function hasOwnProperty(obj, prop) {
  13293. return Object.prototype.hasOwnProperty.call(obj, prop);
  13294. }
  13295. }).call(this, require('_process'), typeof global !== "undefined" ? global :
  13296. typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}
  13297. )
  13298. }, {
  13299. "./support/isBuffer": 116,
  13300. "_process": 92,
  13301. "inherits": 80
  13302. }],
  13303. 118: [function(require, module, exports) {
  13304. (function(process, global) {
  13305. 'use strict'
  13306. var Transform = require('readable-stream').Transform
  13307. var duplexify = require('duplexify')
  13308. var WS = require('ws')
  13309. var Buffer = require('safe-buffer').Buffer
  13310. module.exports = WebSocketStream
  13311. function buildProxy(options, socketWrite, socketEnd) {
  13312. var proxy = new Transform({
  13313. objectMode: options.objectMode
  13314. })
  13315. proxy._write = socketWrite
  13316. proxy._flush = socketEnd
  13317. return proxy
  13318. }
  13319. function WebSocketStream(target, protocols, options) {
  13320. var stream, socket
  13321. var isBrowser = process.title === 'browser'
  13322. var isNative = !!global.WebSocket
  13323. var socketWrite = isBrowser ? socketWriteBrowser : socketWriteNode
  13324. if (protocols && !Array.isArray(protocols) && 'object' ===
  13325. typeof protocols) {
  13326. // accept the "options" Object as the 2nd argument
  13327. options = protocols
  13328. protocols = null
  13329. if (typeof options.protocol === 'string' || Array.isArray(options
  13330. .protocol)) {
  13331. protocols = options.protocol;
  13332. }
  13333. }
  13334. if (!options) options = {}
  13335. if (options.objectMode === undefined) {
  13336. options.objectMode = !(options.binary === true || options.binary ===
  13337. undefined)
  13338. }
  13339. var proxy = buildProxy(options, socketWrite, socketEnd)
  13340. if (!options.objectMode) {
  13341. proxy._writev = writev
  13342. }
  13343. // browser only: sets the maximum socket buffer size before throttling
  13344. var bufferSize = options.browserBufferSize || 1024 * 512
  13345. // browser only: how long to wait when throttling
  13346. var bufferTimeout = options.browserBufferTimeout || 1000
  13347. // use existing WebSocket object that was passed in
  13348. if (typeof target === 'object') {
  13349. socket = target
  13350. // otherwise make a new one
  13351. } else {
  13352. // special constructor treatment for native websockets in browsers, see
  13353. // https://github.com/maxogden/websocket-stream/issues/82
  13354. if (isNative && isBrowser) {
  13355. socket = new WS(target, protocols)
  13356. } else {
  13357. socket = new WS(target, protocols, options)
  13358. }
  13359. socket.binaryType = 'arraybuffer'
  13360. }
  13361. // was already open when passed in
  13362. if (socket.readyState === socket.OPEN) {
  13363. stream = proxy
  13364. } else {
  13365. stream = duplexify.obj()
  13366. socket.onopen = onopen
  13367. }
  13368. stream.socket = socket
  13369. socket.onclose = onclose
  13370. socket.onerror = onerror
  13371. socket.onmessage = onmessage
  13372. proxy.on('close', destroy)
  13373. var coerceToBuffer = !options.objectMode
  13374. function socketWriteNode(chunk, enc, next) {
  13375. // avoid errors, this never happens unless
  13376. // destroy() is called
  13377. if (socket.readyState !== socket.OPEN) {
  13378. next()
  13379. return
  13380. }
  13381. if (coerceToBuffer && typeof chunk === 'string') {
  13382. chunk = Buffer.from(chunk, 'utf8')
  13383. }
  13384. socket.send(chunk, next)
  13385. }
  13386. function socketWriteBrowser(chunk, enc, next) {
  13387. if (socket.bufferedAmount > bufferSize) {
  13388. setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
  13389. return
  13390. }
  13391. if (coerceToBuffer && typeof chunk === 'string') {
  13392. chunk = Buffer.from(chunk, 'utf8')
  13393. }
  13394. try {
  13395. socket.send(chunk)
  13396. } catch (err) {
  13397. return next(err)
  13398. }
  13399. next()
  13400. }
  13401. function socketEnd(done) {
  13402. socket.close()
  13403. done()
  13404. }
  13405. function onopen() {
  13406. stream.setReadable(proxy)
  13407. stream.setWritable(proxy)
  13408. stream.emit('connect')
  13409. }
  13410. function onclose() {
  13411. stream.end()
  13412. stream.destroy()
  13413. }
  13414. function onerror(err) {
  13415. stream.destroy(err)
  13416. }
  13417. function onmessage(event) {
  13418. var data = event.data
  13419. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  13420. else data = Buffer.from(data, 'utf8')
  13421. proxy.push(data)
  13422. }
  13423. function destroy() {
  13424. socket.close()
  13425. }
  13426. // this is to be enabled only if objectMode is false
  13427. function writev(chunks, cb) {
  13428. var buffers = new Array(chunks.length)
  13429. for (var i = 0; i < chunks.length; i++) {
  13430. if (typeof chunks[i].chunk === 'string') {
  13431. buffers[i] = Buffer.from(chunks[i], 'utf8')
  13432. } else {
  13433. buffers[i] = chunks[i].chunk
  13434. }
  13435. }
  13436. this._write(Buffer.concat(buffers), 'binary', cb)
  13437. }
  13438. return stream
  13439. }
  13440. }).call(this, require('_process'), typeof global !== "undefined" ? global :
  13441. typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}
  13442. )
  13443. }, {
  13444. "_process": 92,
  13445. "duplexify": 17,
  13446. "readable-stream": 108,
  13447. "safe-buffer": 110,
  13448. "ws": 119
  13449. }],
  13450. 119: [function(require, module, exports) {
  13451. var ws = null
  13452. if (typeof WebSocket !== 'undefined') {
  13453. ws = WebSocket
  13454. } else if (typeof MozWebSocket !== 'undefined') {
  13455. ws = MozWebSocket
  13456. } else if (typeof window !== 'undefined') {
  13457. ws = window.WebSocket || window.MozWebSocket
  13458. }
  13459. module.exports = ws
  13460. }, {}],
  13461. 120: [function(require, module, exports) {
  13462. // Returns a wrapper function that returns a wrapped callback
  13463. // The wrapper function should do some stuff, and return a
  13464. // presumably different callback function.
  13465. // This makes sure that own properties are retained, so that
  13466. // decorations and such are not lost along the way.
  13467. module.exports = wrappy
  13468. function wrappy(fn, cb) {
  13469. if (fn && cb) return wrappy(fn)(cb)
  13470. if (typeof fn !== 'function')
  13471. throw new TypeError('need wrapper function')
  13472. Object.keys(fn).forEach(function(k) {
  13473. wrapper[k] = fn[k]
  13474. })
  13475. return wrapper
  13476. function wrapper() {
  13477. var args = new Array(arguments.length)
  13478. for (var i = 0; i < args.length; i++) {
  13479. args[i] = arguments[i]
  13480. }
  13481. var ret = fn.apply(this, args)
  13482. var cb = args[args.length - 1]
  13483. if (typeof ret === 'function' && ret !== cb) {
  13484. Object.keys(cb).forEach(function(k) {
  13485. ret[k] = cb[k]
  13486. })
  13487. }
  13488. return ret
  13489. }
  13490. }
  13491. }, {}],
  13492. 121: [function(require, module, exports) {
  13493. module.exports = extend
  13494. var hasOwnProperty = Object.prototype.hasOwnProperty;
  13495. function extend() {
  13496. var target = {}
  13497. for (var i = 0; i < arguments.length; i++) {
  13498. var source = arguments[i]
  13499. for (var key in source) {
  13500. if (hasOwnProperty.call(source, key)) {
  13501. target[key] = source[key]
  13502. }
  13503. }
  13504. }
  13505. return target
  13506. }
  13507. }, {}]
  13508. }, {}, [9])(9)
  13509. };
  13510. export default init;