mqtt.js 551 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.mqtt = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. (function (process,global){(function (){
  3. 'use strict'
  4. /**
  5. * Module dependencies
  6. */
  7. const EventEmitter = require('events').EventEmitter
  8. const Store = require('./store')
  9. const TopicAliasRecv = require('./topic-alias-recv')
  10. const TopicAliasSend = require('./topic-alias-send')
  11. const mqttPacket = require('mqtt-packet')
  12. const DefaultMessageIdProvider = require('./default-message-id-provider')
  13. const Writable = require('readable-stream').Writable
  14. const inherits = require('inherits')
  15. const reInterval = require('reinterval')
  16. const clone = require('rfdc/default')
  17. const validations = require('./validations')
  18. const xtend = require('xtend')
  19. const debug = require('debug')('mqttjs:client')
  20. const nextTick = process ? process.nextTick : function (callback) { setTimeout(callback, 0) }
  21. const setImmediate = global.setImmediate || function (callback) {
  22. // works in node v0.8
  23. nextTick(callback)
  24. }
  25. const defaultConnectOptions = {
  26. keepalive: 60,
  27. reschedulePings: true,
  28. protocolId: 'MQTT',
  29. protocolVersion: 4,
  30. reconnectPeriod: 1000,
  31. connectTimeout: 30 * 1000,
  32. clean: true,
  33. resubscribe: true
  34. }
  35. const socketErrors = [
  36. 'ECONNREFUSED',
  37. 'EADDRINUSE',
  38. 'ECONNRESET',
  39. 'ENOTFOUND'
  40. ]
  41. // Other Socket Errors: EADDRINUSE, ECONNRESET, ENOTFOUND.
  42. const errors = {
  43. 0: '',
  44. 1: 'Unacceptable protocol version',
  45. 2: 'Identifier rejected',
  46. 3: 'Server unavailable',
  47. 4: 'Bad username or password',
  48. 5: 'Not authorized',
  49. 16: 'No matching subscribers',
  50. 17: 'No subscription existed',
  51. 128: 'Unspecified error',
  52. 129: 'Malformed Packet',
  53. 130: 'Protocol Error',
  54. 131: 'Implementation specific error',
  55. 132: 'Unsupported Protocol Version',
  56. 133: 'Client Identifier not valid',
  57. 134: 'Bad User Name or Password',
  58. 135: 'Not authorized',
  59. 136: 'Server unavailable',
  60. 137: 'Server busy',
  61. 138: 'Banned',
  62. 139: 'Server shutting down',
  63. 140: 'Bad authentication method',
  64. 141: 'Keep Alive timeout',
  65. 142: 'Session taken over',
  66. 143: 'Topic Filter invalid',
  67. 144: 'Topic Name invalid',
  68. 145: 'Packet identifier in use',
  69. 146: 'Packet Identifier not found',
  70. 147: 'Receive Maximum exceeded',
  71. 148: 'Topic Alias invalid',
  72. 149: 'Packet too large',
  73. 150: 'Message rate too high',
  74. 151: 'Quota exceeded',
  75. 152: 'Administrative action',
  76. 153: 'Payload format invalid',
  77. 154: 'Retain not supported',
  78. 155: 'QoS not supported',
  79. 156: 'Use another server',
  80. 157: 'Server moved',
  81. 158: 'Shared Subscriptions not supported',
  82. 159: 'Connection rate exceeded',
  83. 160: 'Maximum connect time',
  84. 161: 'Subscription Identifiers not supported',
  85. 162: 'Wildcard Subscriptions not supported'
  86. }
  87. function defaultId () {
  88. return 'mqttjs_' + Math.random().toString(16).substr(2, 8)
  89. }
  90. function applyTopicAlias (client, packet) {
  91. if (client.options.protocolVersion === 5) {
  92. if (packet.cmd === 'publish') {
  93. let alias
  94. if (packet.properties) {
  95. alias = packet.properties.topicAlias
  96. }
  97. const topic = packet.topic.toString()
  98. if (client.topicAliasSend) {
  99. if (alias) {
  100. if (topic.length !== 0) {
  101. // register topic alias
  102. debug('applyTopicAlias :: register topic: %s - alias: %d', topic, alias)
  103. if (!client.topicAliasSend.put(topic, alias)) {
  104. debug('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias)
  105. return new Error('Sending Topic Alias out of range')
  106. }
  107. }
  108. } else {
  109. if (topic.length !== 0) {
  110. if (client.options.autoAssignTopicAlias) {
  111. alias = client.topicAliasSend.getAliasByTopic(topic)
  112. if (alias) {
  113. packet.topic = ''
  114. packet.properties = { ...(packet.properties), topicAlias: alias }
  115. debug('applyTopicAlias :: auto assign(use) topic: %s - alias: %d', topic, alias)
  116. } else {
  117. alias = client.topicAliasSend.getLruAlias()
  118. client.topicAliasSend.put(topic, alias)
  119. packet.properties = { ...(packet.properties), topicAlias: alias }
  120. debug('applyTopicAlias :: auto assign topic: %s - alias: %d', topic, alias)
  121. }
  122. } else if (client.options.autoUseTopicAlias) {
  123. alias = client.topicAliasSend.getAliasByTopic(topic)
  124. if (alias) {
  125. packet.topic = ''
  126. packet.properties = { ...(packet.properties), topicAlias: alias }
  127. debug('applyTopicAlias :: auto use topic: %s - alias: %d', topic, alias)
  128. }
  129. }
  130. }
  131. }
  132. } else if (alias) {
  133. debug('applyTopicAlias :: error out of range. topic: %s - alias: %d', topic, alias)
  134. return new Error('Sending Topic Alias out of range')
  135. }
  136. }
  137. }
  138. }
  139. function removeTopicAliasAndRecoverTopicName (client, packet) {
  140. let alias
  141. if (packet.properties) {
  142. alias = packet.properties.topicAlias
  143. }
  144. let topic = packet.topic.toString()
  145. if (topic.length === 0) {
  146. // restore topic from alias
  147. if (typeof alias === 'undefined') {
  148. return new Error('Unregistered Topic Alias')
  149. } else {
  150. topic = client.topicAliasSend.getTopicByAlias(alias)
  151. if (typeof topic === 'undefined') {
  152. return new Error('Unregistered Topic Alias')
  153. } else {
  154. packet.topic = topic
  155. }
  156. }
  157. }
  158. if (alias) {
  159. delete packet.properties.topicAlias
  160. }
  161. }
  162. function sendPacket (client, packet, cb) {
  163. debug('sendPacket :: packet: %O', packet)
  164. debug('sendPacket :: emitting `packetsend`')
  165. client.emit('packetsend', packet)
  166. debug('sendPacket :: writing to stream')
  167. const result = mqttPacket.writeToStream(packet, client.stream, client.options)
  168. debug('sendPacket :: writeToStream result %s', result)
  169. if (!result && cb && cb !== nop) {
  170. debug('sendPacket :: handle events on `drain` once through callback.')
  171. client.stream.once('drain', cb)
  172. } else if (cb) {
  173. debug('sendPacket :: invoking cb')
  174. cb()
  175. }
  176. }
  177. function flush (queue) {
  178. if (queue) {
  179. debug('flush: queue exists? %b', !!(queue))
  180. Object.keys(queue).forEach(function (messageId) {
  181. if (typeof queue[messageId].cb === 'function') {
  182. queue[messageId].cb(new Error('Connection closed'))
  183. // This is suspicious. Why do we only delete this if we have a callbck?
  184. // If this is by-design, then adding no as callback would cause this to get deleted unintentionally.
  185. delete queue[messageId]
  186. }
  187. })
  188. }
  189. }
  190. function flushVolatile (queue) {
  191. if (queue) {
  192. debug('flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function')
  193. Object.keys(queue).forEach(function (messageId) {
  194. if (queue[messageId].volatile && typeof queue[messageId].cb === 'function') {
  195. queue[messageId].cb(new Error('Connection closed'))
  196. delete queue[messageId]
  197. }
  198. })
  199. }
  200. }
  201. function storeAndSend (client, packet, cb, cbStorePut) {
  202. debug('storeAndSend :: store packet with cmd %s to outgoingStore', packet.cmd)
  203. let storePacket = packet
  204. let err
  205. if (storePacket.cmd === 'publish') {
  206. // The original packet is for sending.
  207. // The cloned storePacket is for storing to resend on reconnect.
  208. // Topic Alias must not be used after disconnected.
  209. storePacket = clone(packet)
  210. err = removeTopicAliasAndRecoverTopicName(client, storePacket)
  211. if (err) {
  212. return cb && cb(err)
  213. }
  214. }
  215. client.outgoingStore.put(storePacket, function storedPacket (err) {
  216. if (err) {
  217. return cb && cb(err)
  218. }
  219. cbStorePut()
  220. sendPacket(client, packet, cb)
  221. })
  222. }
  223. function nop (error) {
  224. debug('nop ::', error)
  225. }
  226. /**
  227. * MqttClient constructor
  228. *
  229. * @param {Stream} stream - stream
  230. * @param {Object} [options] - connection options
  231. * (see Connection#connect)
  232. */
  233. function MqttClient (streamBuilder, options) {
  234. let k
  235. const that = this
  236. if (!(this instanceof MqttClient)) {
  237. return new MqttClient(streamBuilder, options)
  238. }
  239. this.options = options || {}
  240. // Defaults
  241. for (k in defaultConnectOptions) {
  242. if (typeof this.options[k] === 'undefined') {
  243. this.options[k] = defaultConnectOptions[k]
  244. } else {
  245. this.options[k] = options[k]
  246. }
  247. }
  248. debug('MqttClient :: options.protocol', options.protocol)
  249. debug('MqttClient :: options.protocolVersion', options.protocolVersion)
  250. debug('MqttClient :: options.username', options.username)
  251. debug('MqttClient :: options.keepalive', options.keepalive)
  252. debug('MqttClient :: options.reconnectPeriod', options.reconnectPeriod)
  253. debug('MqttClient :: options.rejectUnauthorized', options.rejectUnauthorized)
  254. debug('MqttClient :: options.topicAliasMaximum', options.topicAliasMaximum)
  255. this.options.clientId = (typeof options.clientId === 'string') ? options.clientId : defaultId()
  256. debug('MqttClient :: clientId', this.options.clientId)
  257. this.options.customHandleAcks = (options.protocolVersion === 5 && options.customHandleAcks) ? options.customHandleAcks : function () { arguments[3](0) }
  258. this.streamBuilder = streamBuilder
  259. this.messageIdProvider = (typeof this.options.messageIdProvider === 'undefined') ? new DefaultMessageIdProvider() : this.options.messageIdProvider
  260. // Inflight message storages
  261. this.outgoingStore = options.outgoingStore || new Store()
  262. this.incomingStore = options.incomingStore || new Store()
  263. // Should QoS zero messages be queued when the connection is broken?
  264. this.queueQoSZero = options.queueQoSZero === undefined ? true : options.queueQoSZero
  265. // map of subscribed topics to support reconnection
  266. this._resubscribeTopics = {}
  267. // map of a subscribe messageId and a topic
  268. this.messageIdToTopic = {}
  269. // Ping timer, setup in _setupPingTimer
  270. this.pingTimer = null
  271. // Is the client connected?
  272. this.connected = false
  273. // Are we disconnecting?
  274. this.disconnecting = false
  275. // Packet queue
  276. this.queue = []
  277. // connack timer
  278. this.connackTimer = null
  279. // Reconnect timer
  280. this.reconnectTimer = null
  281. // Is processing store?
  282. this._storeProcessing = false
  283. // Packet Ids are put into the store during store processing
  284. this._packetIdsDuringStoreProcessing = {}
  285. // Store processing queue
  286. this._storeProcessingQueue = []
  287. // Inflight callbacks
  288. this.outgoing = {}
  289. // True if connection is first time.
  290. this._firstConnection = true
  291. if (options.topicAliasMaximum > 0) {
  292. if (options.topicAliasMaximum > 0xffff) {
  293. debug('MqttClient :: options.topicAliasMaximum is out of range')
  294. } else {
  295. this.topicAliasRecv = new TopicAliasRecv(options.topicAliasMaximum)
  296. }
  297. }
  298. // Send queued packets
  299. this.on('connect', function () {
  300. const queue = this.queue
  301. function deliver () {
  302. const entry = queue.shift()
  303. debug('deliver :: entry %o', entry)
  304. let packet = null
  305. if (!entry) {
  306. that._resubscribe()
  307. return
  308. }
  309. packet = entry.packet
  310. debug('deliver :: call _sendPacket for %o', packet)
  311. let send = true
  312. if (packet.messageId && packet.messageId !== 0) {
  313. if (!that.messageIdProvider.register(packet.messageId)) {
  314. send = false
  315. }
  316. }
  317. if (send) {
  318. that._sendPacket(
  319. packet,
  320. function (err) {
  321. if (entry.cb) {
  322. entry.cb(err)
  323. }
  324. deliver()
  325. }
  326. )
  327. } else {
  328. debug('messageId: %d has already used. The message is skipped and removed.', packet.messageId)
  329. deliver()
  330. }
  331. }
  332. debug('connect :: sending queued packets')
  333. deliver()
  334. })
  335. this.on('close', function () {
  336. debug('close :: connected set to `false`')
  337. this.connected = false
  338. debug('close :: clearing connackTimer')
  339. clearTimeout(this.connackTimer)
  340. debug('close :: clearing ping timer')
  341. if (that.pingTimer !== null) {
  342. that.pingTimer.clear()
  343. that.pingTimer = null
  344. }
  345. if (this.topicAliasRecv) {
  346. this.topicAliasRecv.clear()
  347. }
  348. debug('close :: calling _setupReconnect')
  349. this._setupReconnect()
  350. })
  351. EventEmitter.call(this)
  352. debug('MqttClient :: setting up stream')
  353. this._setupStream()
  354. }
  355. inherits(MqttClient, EventEmitter)
  356. /**
  357. * setup the event handlers in the inner stream.
  358. *
  359. * @api private
  360. */
  361. MqttClient.prototype._setupStream = function () {
  362. const that = this
  363. const writable = new Writable()
  364. const parser = mqttPacket.parser(this.options)
  365. let completeParse = null
  366. const packets = []
  367. debug('_setupStream :: calling method to clear reconnect')
  368. this._clearReconnect()
  369. debug('_setupStream :: using streamBuilder provided to client to create stream')
  370. this.stream = this.streamBuilder(this)
  371. parser.on('packet', function (packet) {
  372. debug('parser :: on packet push to packets array.')
  373. packets.push(packet)
  374. })
  375. function nextTickWork () {
  376. if (packets.length) {
  377. nextTick(work)
  378. } else {
  379. const done = completeParse
  380. completeParse = null
  381. done()
  382. }
  383. }
  384. function work () {
  385. debug('work :: getting next packet in queue')
  386. const packet = packets.shift()
  387. if (packet) {
  388. debug('work :: packet pulled from queue')
  389. that._handlePacket(packet, nextTickWork)
  390. } else {
  391. debug('work :: no packets in queue')
  392. const done = completeParse
  393. completeParse = null
  394. debug('work :: done flag is %s', !!(done))
  395. if (done) done()
  396. }
  397. }
  398. writable._write = function (buf, enc, done) {
  399. completeParse = done
  400. debug('writable stream :: parsing buffer')
  401. parser.parse(buf)
  402. work()
  403. }
  404. function streamErrorHandler (error) {
  405. debug('streamErrorHandler :: error', error.message)
  406. if (socketErrors.includes(error.code)) {
  407. // handle error
  408. debug('streamErrorHandler :: emitting error')
  409. that.emit('error', error)
  410. } else {
  411. nop(error)
  412. }
  413. }
  414. debug('_setupStream :: pipe stream to writable stream')
  415. this.stream.pipe(writable)
  416. // Suppress connection errors
  417. this.stream.on('error', streamErrorHandler)
  418. // Echo stream close
  419. this.stream.on('close', function () {
  420. debug('(%s)stream :: on close', that.options.clientId)
  421. flushVolatile(that.outgoing)
  422. debug('stream: emit close to MqttClient')
  423. that.emit('close')
  424. })
  425. // Send a connect packet
  426. debug('_setupStream: sending packet `connect`')
  427. const connectPacket = Object.create(this.options)
  428. connectPacket.cmd = 'connect'
  429. if (this.topicAliasRecv) {
  430. if (!connectPacket.properties) {
  431. connectPacket.properties = {}
  432. }
  433. if (this.topicAliasRecv) {
  434. connectPacket.properties.topicAliasMaximum = this.topicAliasRecv.max
  435. }
  436. }
  437. // avoid message queue
  438. sendPacket(this, connectPacket)
  439. // Echo connection errors
  440. parser.on('error', this.emit.bind(this, 'error'))
  441. // auth
  442. if (this.options.properties) {
  443. if (!this.options.properties.authenticationMethod && this.options.properties.authenticationData) {
  444. that.end(() =>
  445. this.emit('error', new Error('Packet has no Authentication Method')
  446. ))
  447. return this
  448. }
  449. if (this.options.properties.authenticationMethod && this.options.authPacket && typeof this.options.authPacket === 'object') {
  450. const authPacket = xtend({ cmd: 'auth', reasonCode: 0 }, this.options.authPacket)
  451. sendPacket(this, authPacket)
  452. }
  453. }
  454. // many drain listeners are needed for qos 1 callbacks if the connection is intermittent
  455. this.stream.setMaxListeners(1000)
  456. clearTimeout(this.connackTimer)
  457. this.connackTimer = setTimeout(function () {
  458. debug('!!connectTimeout hit!! Calling _cleanUp with force `true`')
  459. that._cleanUp(true)
  460. }, this.options.connectTimeout)
  461. }
  462. MqttClient.prototype._handlePacket = function (packet, done) {
  463. const options = this.options
  464. if (options.protocolVersion === 5 && options.properties && options.properties.maximumPacketSize && options.properties.maximumPacketSize < packet.length) {
  465. this.emit('error', new Error('exceeding packets size ' + packet.cmd))
  466. this.end({ reasonCode: 149, properties: { reasonString: 'Maximum packet size was exceeded' } })
  467. return this
  468. }
  469. debug('_handlePacket :: emitting packetreceive')
  470. this.emit('packetreceive', packet)
  471. switch (packet.cmd) {
  472. case 'publish':
  473. this._handlePublish(packet, done)
  474. break
  475. case 'puback':
  476. case 'pubrec':
  477. case 'pubcomp':
  478. case 'suback':
  479. case 'unsuback':
  480. this._handleAck(packet)
  481. done()
  482. break
  483. case 'pubrel':
  484. this._handlePubrel(packet, done)
  485. break
  486. case 'connack':
  487. this._handleConnack(packet)
  488. done()
  489. break
  490. case 'auth':
  491. this._handleAuth(packet)
  492. done()
  493. break
  494. case 'pingresp':
  495. this._handlePingresp(packet)
  496. done()
  497. break
  498. case 'disconnect':
  499. this._handleDisconnect(packet)
  500. done()
  501. break
  502. default:
  503. // do nothing
  504. // maybe we should do an error handling
  505. // or just log it
  506. break
  507. }
  508. }
  509. MqttClient.prototype._checkDisconnecting = function (callback) {
  510. if (this.disconnecting) {
  511. if (callback && callback !== nop) {
  512. callback(new Error('client disconnecting'))
  513. } else {
  514. this.emit('error', new Error('client disconnecting'))
  515. }
  516. }
  517. return this.disconnecting
  518. }
  519. /**
  520. * publish - publish <message> to <topic>
  521. *
  522. * @param {String} topic - topic to publish to
  523. * @param {String, Buffer} message - message to publish
  524. * @param {Object} [opts] - publish options, includes:
  525. * {Number} qos - qos level to publish on
  526. * {Boolean} retain - whether or not to retain the message
  527. * {Boolean} dup - whether or not mark a message as duplicate
  528. * {Function} cbStorePut - function(){} called when message is put into `outgoingStore`
  529. * @param {Function} [callback] - function(err){}
  530. * called when publish succeeds or fails
  531. * @returns {MqttClient} this - for chaining
  532. * @api public
  533. *
  534. * @example client.publish('topic', 'message');
  535. * @example
  536. * client.publish('topic', 'message', {qos: 1, retain: true, dup: true});
  537. * @example client.publish('topic', 'message', console.log);
  538. */
  539. MqttClient.prototype.publish = function (topic, message, opts, callback) {
  540. debug('publish :: message `%s` to topic `%s`', message, topic)
  541. const options = this.options
  542. // .publish(topic, payload, cb);
  543. if (typeof opts === 'function') {
  544. callback = opts
  545. opts = null
  546. }
  547. // default opts
  548. const defaultOpts = { qos: 0, retain: false, dup: false }
  549. opts = xtend(defaultOpts, opts)
  550. if (this._checkDisconnecting(callback)) {
  551. return this
  552. }
  553. const that = this
  554. const publishProc = function () {
  555. let messageId = 0
  556. if (opts.qos === 1 || opts.qos === 2) {
  557. messageId = that._nextId()
  558. if (messageId === null) {
  559. debug('No messageId left')
  560. return false
  561. }
  562. }
  563. const packet = {
  564. cmd: 'publish',
  565. topic: topic,
  566. payload: message,
  567. qos: opts.qos,
  568. retain: opts.retain,
  569. messageId: messageId,
  570. dup: opts.dup
  571. }
  572. if (options.protocolVersion === 5) {
  573. packet.properties = opts.properties
  574. }
  575. debug('publish :: qos', opts.qos)
  576. switch (opts.qos) {
  577. case 1:
  578. case 2:
  579. // Add to callbacks
  580. that.outgoing[packet.messageId] = {
  581. volatile: false,
  582. cb: callback || nop
  583. }
  584. debug('MqttClient:publish: packet cmd: %s', packet.cmd)
  585. that._sendPacket(packet, undefined, opts.cbStorePut)
  586. break
  587. default:
  588. debug('MqttClient:publish: packet cmd: %s', packet.cmd)
  589. that._sendPacket(packet, callback, opts.cbStorePut)
  590. break
  591. }
  592. return true
  593. }
  594. if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !publishProc()) {
  595. this._storeProcessingQueue.push(
  596. {
  597. invoke: publishProc,
  598. cbStorePut: opts.cbStorePut,
  599. callback: callback
  600. }
  601. )
  602. }
  603. return this
  604. }
  605. /**
  606. * subscribe - subscribe to <topic>
  607. *
  608. * @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
  609. * @param {Object} [opts] - optional subscription options, includes:
  610. * {Number} qos - subscribe qos level
  611. * @param {Function} [callback] - function(err, granted){} where:
  612. * {Error} err - subscription error (none at the moment!)
  613. * {Array} granted - array of {topic: 't', qos: 0}
  614. * @returns {MqttClient} this - for chaining
  615. * @api public
  616. * @example client.subscribe('topic');
  617. * @example client.subscribe('topic', {qos: 1});
  618. * @example client.subscribe({'topic': {qos: 0}, 'topic2': {qos: 1}}, console.log);
  619. * @example client.subscribe('topic', console.log);
  620. */
  621. MqttClient.prototype.subscribe = function () {
  622. const that = this
  623. const args = new Array(arguments.length)
  624. for (let i = 0; i < arguments.length; i++) {
  625. args[i] = arguments[i]
  626. }
  627. const subs = []
  628. let obj = args.shift()
  629. const resubscribe = obj.resubscribe
  630. let callback = args.pop() || nop
  631. let opts = args.pop()
  632. const version = this.options.protocolVersion
  633. delete obj.resubscribe
  634. if (typeof obj === 'string') {
  635. obj = [obj]
  636. }
  637. if (typeof callback !== 'function') {
  638. opts = callback
  639. callback = nop
  640. }
  641. const invalidTopic = validations.validateTopics(obj)
  642. if (invalidTopic !== null) {
  643. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  644. return this
  645. }
  646. if (this._checkDisconnecting(callback)) {
  647. debug('subscribe: discconecting true')
  648. return this
  649. }
  650. const defaultOpts = {
  651. qos: 0
  652. }
  653. if (version === 5) {
  654. defaultOpts.nl = false
  655. defaultOpts.rap = false
  656. defaultOpts.rh = 0
  657. }
  658. opts = xtend(defaultOpts, opts)
  659. if (Array.isArray(obj)) {
  660. obj.forEach(function (topic) {
  661. debug('subscribe: array topic %s', topic)
  662. if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, topic) ||
  663. that._resubscribeTopics[topic].qos < opts.qos ||
  664. resubscribe) {
  665. const currentOpts = {
  666. topic: topic,
  667. qos: opts.qos
  668. }
  669. if (version === 5) {
  670. currentOpts.nl = opts.nl
  671. currentOpts.rap = opts.rap
  672. currentOpts.rh = opts.rh
  673. currentOpts.properties = opts.properties
  674. }
  675. debug('subscribe: pushing topic `%s` and qos `%s` to subs list', currentOpts.topic, currentOpts.qos)
  676. subs.push(currentOpts)
  677. }
  678. })
  679. } else {
  680. Object
  681. .keys(obj)
  682. .forEach(function (k) {
  683. debug('subscribe: object topic %s', k)
  684. if (!Object.prototype.hasOwnProperty.call(that._resubscribeTopics, k) ||
  685. that._resubscribeTopics[k].qos < obj[k].qos ||
  686. resubscribe) {
  687. const currentOpts = {
  688. topic: k,
  689. qos: obj[k].qos
  690. }
  691. if (version === 5) {
  692. currentOpts.nl = obj[k].nl
  693. currentOpts.rap = obj[k].rap
  694. currentOpts.rh = obj[k].rh
  695. currentOpts.properties = opts.properties
  696. }
  697. debug('subscribe: pushing `%s` to subs list', currentOpts)
  698. subs.push(currentOpts)
  699. }
  700. })
  701. }
  702. if (!subs.length) {
  703. callback(null, [])
  704. return this
  705. }
  706. const subscribeProc = function () {
  707. const messageId = that._nextId()
  708. if (messageId === null) {
  709. debug('No messageId left')
  710. return false
  711. }
  712. const packet = {
  713. cmd: 'subscribe',
  714. subscriptions: subs,
  715. qos: 1,
  716. retain: false,
  717. dup: false,
  718. messageId: messageId
  719. }
  720. if (opts.properties) {
  721. packet.properties = opts.properties
  722. }
  723. // subscriptions to resubscribe to in case of disconnect
  724. if (that.options.resubscribe) {
  725. debug('subscribe :: resubscribe true')
  726. const topics = []
  727. subs.forEach(function (sub) {
  728. if (that.options.reconnectPeriod > 0) {
  729. const topic = { qos: sub.qos }
  730. if (version === 5) {
  731. topic.nl = sub.nl || false
  732. topic.rap = sub.rap || false
  733. topic.rh = sub.rh || 0
  734. topic.properties = sub.properties
  735. }
  736. that._resubscribeTopics[sub.topic] = topic
  737. topics.push(sub.topic)
  738. }
  739. })
  740. that.messageIdToTopic[packet.messageId] = topics
  741. }
  742. that.outgoing[packet.messageId] = {
  743. volatile: true,
  744. cb: function (err, packet) {
  745. if (!err) {
  746. const granted = packet.granted
  747. for (let i = 0; i < granted.length; i += 1) {
  748. subs[i].qos = granted[i]
  749. }
  750. }
  751. callback(err, subs)
  752. }
  753. }
  754. debug('subscribe :: call _sendPacket')
  755. that._sendPacket(packet)
  756. return true
  757. }
  758. if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !subscribeProc()) {
  759. this._storeProcessingQueue.push(
  760. {
  761. invoke: subscribeProc,
  762. callback: callback
  763. }
  764. )
  765. }
  766. return this
  767. }
  768. /**
  769. * unsubscribe - unsubscribe from topic(s)
  770. *
  771. * @param {String, Array} topic - topics to unsubscribe from
  772. * @param {Object} [opts] - optional subscription options, includes:
  773. * {Object} properties - properties of unsubscribe packet
  774. * @param {Function} [callback] - callback fired on unsuback
  775. * @returns {MqttClient} this - for chaining
  776. * @api public
  777. * @example client.unsubscribe('topic');
  778. * @example client.unsubscribe('topic', console.log);
  779. */
  780. MqttClient.prototype.unsubscribe = function () {
  781. const that = this
  782. const args = new Array(arguments.length)
  783. for (let i = 0; i < arguments.length; i++) {
  784. args[i] = arguments[i]
  785. }
  786. let topic = args.shift()
  787. let callback = args.pop() || nop
  788. let opts = args.pop()
  789. if (typeof topic === 'string') {
  790. topic = [topic]
  791. }
  792. if (typeof callback !== 'function') {
  793. opts = callback
  794. callback = nop
  795. }
  796. const invalidTopic = validations.validateTopics(topic)
  797. if (invalidTopic !== null) {
  798. setImmediate(callback, new Error('Invalid topic ' + invalidTopic))
  799. return this
  800. }
  801. if (that._checkDisconnecting(callback)) {
  802. return this
  803. }
  804. const unsubscribeProc = function () {
  805. const messageId = that._nextId()
  806. if (messageId === null) {
  807. debug('No messageId left')
  808. return false
  809. }
  810. const packet = {
  811. cmd: 'unsubscribe',
  812. qos: 1,
  813. messageId: messageId
  814. }
  815. if (typeof topic === 'string') {
  816. packet.unsubscriptions = [topic]
  817. } else if (Array.isArray(topic)) {
  818. packet.unsubscriptions = topic
  819. }
  820. if (that.options.resubscribe) {
  821. packet.unsubscriptions.forEach(function (topic) {
  822. delete that._resubscribeTopics[topic]
  823. })
  824. }
  825. if (typeof opts === 'object' && opts.properties) {
  826. packet.properties = opts.properties
  827. }
  828. that.outgoing[packet.messageId] = {
  829. volatile: true,
  830. cb: callback
  831. }
  832. debug('unsubscribe: call _sendPacket')
  833. that._sendPacket(packet)
  834. return true
  835. }
  836. if (this._storeProcessing || this._storeProcessingQueue.length > 0 || !unsubscribeProc()) {
  837. this._storeProcessingQueue.push(
  838. {
  839. invoke: unsubscribeProc,
  840. callback: callback
  841. }
  842. )
  843. }
  844. return this
  845. }
  846. /**
  847. * end - close connection
  848. *
  849. * @returns {MqttClient} this - for chaining
  850. * @param {Boolean} force - do not wait for all in-flight messages to be acked
  851. * @param {Object} opts - added to the disconnect packet
  852. * @param {Function} cb - called when the client has been closed
  853. *
  854. * @api public
  855. */
  856. MqttClient.prototype.end = function (force, opts, cb) {
  857. const that = this
  858. debug('end :: (%s)', this.options.clientId)
  859. if (force == null || typeof force !== 'boolean') {
  860. cb = opts || nop
  861. opts = force
  862. force = false
  863. if (typeof opts !== 'object') {
  864. cb = opts
  865. opts = null
  866. if (typeof cb !== 'function') {
  867. cb = nop
  868. }
  869. }
  870. }
  871. if (typeof opts !== 'object') {
  872. cb = opts
  873. opts = null
  874. }
  875. debug('end :: cb? %s', !!cb)
  876. cb = cb || nop
  877. function closeStores () {
  878. debug('end :: closeStores: closing incoming and outgoing stores')
  879. that.disconnected = true
  880. that.incomingStore.close(function (e1) {
  881. that.outgoingStore.close(function (e2) {
  882. debug('end :: closeStores: emitting end')
  883. that.emit('end')
  884. if (cb) {
  885. const err = e1 || e2
  886. debug('end :: closeStores: invoking callback with args')
  887. cb(err)
  888. }
  889. })
  890. })
  891. if (that._deferredReconnect) {
  892. that._deferredReconnect()
  893. }
  894. }
  895. function finish () {
  896. // defer closesStores of an I/O cycle,
  897. // just to make sure things are
  898. // ok for websockets
  899. debug('end :: (%s) :: finish :: calling _cleanUp with force %s', that.options.clientId, force)
  900. that._cleanUp(force, () => {
  901. debug('end :: finish :: calling process.nextTick on closeStores')
  902. // const boundProcess = nextTick.bind(null, closeStores)
  903. nextTick(closeStores.bind(that))
  904. }, opts)
  905. }
  906. if (this.disconnecting) {
  907. cb()
  908. return this
  909. }
  910. this._clearReconnect()
  911. this.disconnecting = true
  912. if (!force && Object.keys(this.outgoing).length > 0) {
  913. // wait 10ms, just to be sure we received all of it
  914. debug('end :: (%s) :: calling finish in 10ms once outgoing is empty', that.options.clientId)
  915. this.once('outgoingEmpty', setTimeout.bind(null, finish, 10))
  916. } else {
  917. debug('end :: (%s) :: immediately calling finish', that.options.clientId)
  918. finish()
  919. }
  920. return this
  921. }
  922. /**
  923. * removeOutgoingMessage - remove a message in outgoing store
  924. * the outgoing callback will be called withe Error('Message removed') if the message is removed
  925. *
  926. * @param {Number} messageId - messageId to remove message
  927. * @returns {MqttClient} this - for chaining
  928. * @api public
  929. *
  930. * @example client.removeOutgoingMessage(client.getLastAllocated());
  931. */
  932. MqttClient.prototype.removeOutgoingMessage = function (messageId) {
  933. const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
  934. delete this.outgoing[messageId]
  935. this.outgoingStore.del({ messageId: messageId }, function () {
  936. cb(new Error('Message removed'))
  937. })
  938. return this
  939. }
  940. /**
  941. * reconnect - connect again using the same options as connect()
  942. *
  943. * @param {Object} [opts] - optional reconnect options, includes:
  944. * {Store} incomingStore - a store for the incoming packets
  945. * {Store} outgoingStore - a store for the outgoing packets
  946. * if opts is not given, current stores are used
  947. * @returns {MqttClient} this - for chaining
  948. *
  949. * @api public
  950. */
  951. MqttClient.prototype.reconnect = function (opts) {
  952. debug('client reconnect')
  953. const that = this
  954. const f = function () {
  955. if (opts) {
  956. that.options.incomingStore = opts.incomingStore
  957. that.options.outgoingStore = opts.outgoingStore
  958. } else {
  959. that.options.incomingStore = null
  960. that.options.outgoingStore = null
  961. }
  962. that.incomingStore = that.options.incomingStore || new Store()
  963. that.outgoingStore = that.options.outgoingStore || new Store()
  964. that.disconnecting = false
  965. that.disconnected = false
  966. that._deferredReconnect = null
  967. that._reconnect()
  968. }
  969. if (this.disconnecting && !this.disconnected) {
  970. this._deferredReconnect = f
  971. } else {
  972. f()
  973. }
  974. return this
  975. }
  976. /**
  977. * _reconnect - implement reconnection
  978. * @api privateish
  979. */
  980. MqttClient.prototype._reconnect = function () {
  981. debug('_reconnect: emitting reconnect to client')
  982. this.emit('reconnect')
  983. if (this.connected) {
  984. this.end(() => { this._setupStream() })
  985. debug('client already connected. disconnecting first.')
  986. } else {
  987. debug('_reconnect: calling _setupStream')
  988. this._setupStream()
  989. }
  990. }
  991. /**
  992. * _setupReconnect - setup reconnect timer
  993. */
  994. MqttClient.prototype._setupReconnect = function () {
  995. const that = this
  996. if (!that.disconnecting && !that.reconnectTimer && (that.options.reconnectPeriod > 0)) {
  997. if (!this.reconnecting) {
  998. debug('_setupReconnect :: emit `offline` state')
  999. this.emit('offline')
  1000. debug('_setupReconnect :: set `reconnecting` to `true`')
  1001. this.reconnecting = true
  1002. }
  1003. debug('_setupReconnect :: setting reconnectTimer for %d ms', that.options.reconnectPeriod)
  1004. that.reconnectTimer = setInterval(function () {
  1005. debug('reconnectTimer :: reconnect triggered!')
  1006. that._reconnect()
  1007. }, that.options.reconnectPeriod)
  1008. } else {
  1009. debug('_setupReconnect :: doing nothing...')
  1010. }
  1011. }
  1012. /**
  1013. * _clearReconnect - clear the reconnect timer
  1014. */
  1015. MqttClient.prototype._clearReconnect = function () {
  1016. debug('_clearReconnect : clearing reconnect timer')
  1017. if (this.reconnectTimer) {
  1018. clearInterval(this.reconnectTimer)
  1019. this.reconnectTimer = null
  1020. }
  1021. }
  1022. /**
  1023. * _cleanUp - clean up on connection end
  1024. * @api private
  1025. */
  1026. MqttClient.prototype._cleanUp = function (forced, done) {
  1027. const opts = arguments[2]
  1028. if (done) {
  1029. debug('_cleanUp :: done callback provided for on stream close')
  1030. this.stream.on('close', done)
  1031. }
  1032. debug('_cleanUp :: forced? %s', forced)
  1033. if (forced) {
  1034. if ((this.options.reconnectPeriod === 0) && this.options.clean) {
  1035. flush(this.outgoing)
  1036. }
  1037. debug('_cleanUp :: (%s) :: destroying stream', this.options.clientId)
  1038. this.stream.destroy()
  1039. } else {
  1040. const packet = xtend({ cmd: 'disconnect' }, opts)
  1041. debug('_cleanUp :: (%s) :: call _sendPacket with disconnect packet', this.options.clientId)
  1042. this._sendPacket(
  1043. packet,
  1044. setImmediate.bind(
  1045. null,
  1046. this.stream.end.bind(this.stream)
  1047. )
  1048. )
  1049. }
  1050. if (!this.disconnecting) {
  1051. debug('_cleanUp :: client not disconnecting. Clearing and resetting reconnect.')
  1052. this._clearReconnect()
  1053. this._setupReconnect()
  1054. }
  1055. if (this.pingTimer !== null) {
  1056. debug('_cleanUp :: clearing pingTimer')
  1057. this.pingTimer.clear()
  1058. this.pingTimer = null
  1059. }
  1060. if (done && !this.connected) {
  1061. debug('_cleanUp :: (%s) :: removing stream `done` callback `close` listener', this.options.clientId)
  1062. this.stream.removeListener('close', done)
  1063. done()
  1064. }
  1065. }
  1066. /**
  1067. * _sendPacket - send or queue a packet
  1068. * @param {Object} packet - packet options
  1069. * @param {Function} cb - callback when the packet is sent
  1070. * @param {Function} cbStorePut - called when message is put into outgoingStore
  1071. * @api private
  1072. */
  1073. MqttClient.prototype._sendPacket = function (packet, cb, cbStorePut) {
  1074. debug('_sendPacket :: (%s) :: start', this.options.clientId)
  1075. cbStorePut = cbStorePut || nop
  1076. cb = cb || nop
  1077. const err = applyTopicAlias(this, packet)
  1078. if (err) {
  1079. cb(err)
  1080. return
  1081. }
  1082. if (!this.connected) {
  1083. // allow auth packets to be sent while authenticating with the broker (mqtt5 enhanced auth)
  1084. if (packet.cmd === 'auth') {
  1085. this._shiftPingInterval()
  1086. sendPacket(this, packet, cb)
  1087. return
  1088. }
  1089. debug('_sendPacket :: client not connected. Storing packet offline.')
  1090. this._storePacket(packet, cb, cbStorePut)
  1091. return
  1092. }
  1093. // When sending a packet, reschedule the ping timer
  1094. this._shiftPingInterval()
  1095. switch (packet.cmd) {
  1096. case 'publish':
  1097. break
  1098. case 'pubrel':
  1099. storeAndSend(this, packet, cb, cbStorePut)
  1100. return
  1101. default:
  1102. sendPacket(this, packet, cb)
  1103. return
  1104. }
  1105. switch (packet.qos) {
  1106. case 2:
  1107. case 1:
  1108. storeAndSend(this, packet, cb, cbStorePut)
  1109. break
  1110. /**
  1111. * no need of case here since it will be caught by default
  1112. * and jshint comply that before default it must be a break
  1113. * anyway it will result in -1 evaluation
  1114. */
  1115. case 0:
  1116. /* falls through */
  1117. default:
  1118. sendPacket(this, packet, cb)
  1119. break
  1120. }
  1121. debug('_sendPacket :: (%s) :: end', this.options.clientId)
  1122. }
  1123. /**
  1124. * _storePacket - queue a packet
  1125. * @param {Object} packet - packet options
  1126. * @param {Function} cb - callback when the packet is sent
  1127. * @param {Function} cbStorePut - called when message is put into outgoingStore
  1128. * @api private
  1129. */
  1130. MqttClient.prototype._storePacket = function (packet, cb, cbStorePut) {
  1131. debug('_storePacket :: packet: %o', packet)
  1132. debug('_storePacket :: cb? %s', !!cb)
  1133. cbStorePut = cbStorePut || nop
  1134. let storePacket = packet
  1135. if (storePacket.cmd === 'publish') {
  1136. // The original packet is for sending.
  1137. // The cloned storePacket is for storing to resend on reconnect.
  1138. // Topic Alias must not be used after disconnected.
  1139. storePacket = clone(packet)
  1140. const err = removeTopicAliasAndRecoverTopicName(this, storePacket)
  1141. if (err) {
  1142. return cb && cb(err)
  1143. }
  1144. }
  1145. // check that the packet is not a qos of 0, or that the command is not a publish
  1146. if (((storePacket.qos || 0) === 0 && this.queueQoSZero) || storePacket.cmd !== 'publish') {
  1147. this.queue.push({ packet: storePacket, cb: cb })
  1148. } else if (storePacket.qos > 0) {
  1149. cb = this.outgoing[storePacket.messageId] ? this.outgoing[storePacket.messageId].cb : null
  1150. this.outgoingStore.put(storePacket, function (err) {
  1151. if (err) {
  1152. return cb && cb(err)
  1153. }
  1154. cbStorePut()
  1155. })
  1156. } else if (cb) {
  1157. cb(new Error('No connection to broker'))
  1158. }
  1159. }
  1160. /**
  1161. * _setupPingTimer - setup the ping timer
  1162. *
  1163. * @api private
  1164. */
  1165. MqttClient.prototype._setupPingTimer = function () {
  1166. debug('_setupPingTimer :: keepalive %d (seconds)', this.options.keepalive)
  1167. const that = this
  1168. if (!this.pingTimer && this.options.keepalive) {
  1169. this.pingResp = true
  1170. this.pingTimer = reInterval(function () {
  1171. that._checkPing()
  1172. }, this.options.keepalive * 1000)
  1173. }
  1174. }
  1175. /**
  1176. * _shiftPingInterval - reschedule the ping interval
  1177. *
  1178. * @api private
  1179. */
  1180. MqttClient.prototype._shiftPingInterval = function () {
  1181. if (this.pingTimer && this.options.keepalive && this.options.reschedulePings) {
  1182. this.pingTimer.reschedule(this.options.keepalive * 1000)
  1183. }
  1184. }
  1185. /**
  1186. * _checkPing - check if a pingresp has come back, and ping the server again
  1187. *
  1188. * @api private
  1189. */
  1190. MqttClient.prototype._checkPing = function () {
  1191. debug('_checkPing :: checking ping...')
  1192. if (this.pingResp) {
  1193. debug('_checkPing :: ping response received. Clearing flag and sending `pingreq`')
  1194. this.pingResp = false
  1195. this._sendPacket({ cmd: 'pingreq' })
  1196. } else {
  1197. // do a forced cleanup since socket will be in bad shape
  1198. debug('_checkPing :: calling _cleanUp with force true')
  1199. this._cleanUp(true)
  1200. }
  1201. }
  1202. /**
  1203. * _handlePingresp - handle a pingresp
  1204. *
  1205. * @api private
  1206. */
  1207. MqttClient.prototype._handlePingresp = function () {
  1208. this.pingResp = true
  1209. }
  1210. /**
  1211. * _handleConnack
  1212. *
  1213. * @param {Object} packet
  1214. * @api private
  1215. */
  1216. MqttClient.prototype._handleConnack = function (packet) {
  1217. debug('_handleConnack')
  1218. const options = this.options
  1219. const version = options.protocolVersion
  1220. const rc = version === 5 ? packet.reasonCode : packet.returnCode
  1221. clearTimeout(this.connackTimer)
  1222. delete this.topicAliasSend
  1223. if (packet.properties) {
  1224. if (packet.properties.topicAliasMaximum) {
  1225. if (packet.properties.topicAliasMaximum > 0xffff) {
  1226. this.emit('error', new Error('topicAliasMaximum from broker is out of range'))
  1227. return
  1228. }
  1229. if (packet.properties.topicAliasMaximum > 0) {
  1230. this.topicAliasSend = new TopicAliasSend(packet.properties.topicAliasMaximum)
  1231. }
  1232. }
  1233. if (packet.properties.serverKeepAlive && options.keepalive) {
  1234. options.keepalive = packet.properties.serverKeepAlive
  1235. this._shiftPingInterval()
  1236. }
  1237. if (packet.properties.maximumPacketSize) {
  1238. if (!options.properties) { options.properties = {} }
  1239. options.properties.maximumPacketSize = packet.properties.maximumPacketSize
  1240. }
  1241. }
  1242. if (rc === 0) {
  1243. this.reconnecting = false
  1244. this._onConnect(packet)
  1245. } else if (rc > 0) {
  1246. const err = new Error('Connection refused: ' + errors[rc])
  1247. err.code = rc
  1248. this.emit('error', err)
  1249. }
  1250. }
  1251. MqttClient.prototype._handleAuth = function (packet) {
  1252. const options = this.options
  1253. const version = options.protocolVersion
  1254. const rc = version === 5 ? packet.reasonCode : packet.returnCode
  1255. if (version !== 5) {
  1256. const err = new Error('Protocol error: Auth packets are only supported in MQTT 5. Your version:' + version)
  1257. err.code = rc
  1258. this.emit('error', err)
  1259. return
  1260. }
  1261. const that = this
  1262. this.handleAuth(packet, function (err, packet) {
  1263. if (err) {
  1264. that.emit('error', err)
  1265. return
  1266. }
  1267. if (rc === 24) {
  1268. that.reconnecting = false
  1269. that._sendPacket(packet)
  1270. } else {
  1271. const error = new Error('Connection refused: ' + errors[rc])
  1272. err.code = rc
  1273. that.emit('error', error)
  1274. }
  1275. })
  1276. }
  1277. /**
  1278. * @param packet the packet received by the broker
  1279. * @return the auth packet to be returned to the broker
  1280. * @api public
  1281. */
  1282. MqttClient.prototype.handleAuth = function (packet, callback) {
  1283. callback()
  1284. }
  1285. /**
  1286. * _handlePublish
  1287. *
  1288. * @param {Object} packet
  1289. * @api private
  1290. */
  1291. /*
  1292. those late 2 case should be rewrite to comply with coding style:
  1293. case 1:
  1294. case 0:
  1295. // do not wait sending a puback
  1296. // no callback passed
  1297. if (1 === qos) {
  1298. this._sendPacket({
  1299. cmd: 'puback',
  1300. messageId: messageId
  1301. });
  1302. }
  1303. // emit the message event for both qos 1 and 0
  1304. this.emit('message', topic, message, packet);
  1305. this.handleMessage(packet, done);
  1306. break;
  1307. default:
  1308. // do nothing but every switch mus have a default
  1309. // log or throw an error about unknown qos
  1310. break;
  1311. for now i just suppressed the warnings
  1312. */
  1313. MqttClient.prototype._handlePublish = function (packet, done) {
  1314. debug('_handlePublish: packet %o', packet)
  1315. done = typeof done !== 'undefined' ? done : nop
  1316. let topic = packet.topic.toString()
  1317. const message = packet.payload
  1318. const qos = packet.qos
  1319. const messageId = packet.messageId
  1320. const that = this
  1321. const options = this.options
  1322. const validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
  1323. if (this.options.protocolVersion === 5) {
  1324. let alias
  1325. if (packet.properties) {
  1326. alias = packet.properties.topicAlias
  1327. }
  1328. if (typeof alias !== 'undefined') {
  1329. if (topic.length === 0) {
  1330. if (alias > 0 && alias <= 0xffff) {
  1331. const gotTopic = this.topicAliasRecv.getTopicByAlias(alias)
  1332. if (gotTopic) {
  1333. topic = gotTopic
  1334. debug('_handlePublish :: topic complemented by alias. topic: %s - alias: %d', topic, alias)
  1335. } else {
  1336. debug('_handlePublish :: unregistered topic alias. alias: %d', alias)
  1337. this.emit('error', new Error('Received unregistered Topic Alias'))
  1338. return
  1339. }
  1340. } else {
  1341. debug('_handlePublish :: topic alias out of range. alias: %d', alias)
  1342. this.emit('error', new Error('Received Topic Alias is out of range'))
  1343. return
  1344. }
  1345. } else {
  1346. if (this.topicAliasRecv.put(topic, alias)) {
  1347. debug('_handlePublish :: registered topic: %s - alias: %d', topic, alias)
  1348. } else {
  1349. debug('_handlePublish :: topic alias out of range. alias: %d', alias)
  1350. this.emit('error', new Error('Received Topic Alias is out of range'))
  1351. return
  1352. }
  1353. }
  1354. }
  1355. }
  1356. debug('_handlePublish: qos %d', qos)
  1357. switch (qos) {
  1358. case 2: {
  1359. options.customHandleAcks(topic, message, packet, function (error, code) {
  1360. if (!(error instanceof Error)) {
  1361. code = error
  1362. error = null
  1363. }
  1364. if (error) { return that.emit('error', error) }
  1365. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for pubrec')) }
  1366. if (code) {
  1367. that._sendPacket({ cmd: 'pubrec', messageId: messageId, reasonCode: code }, done)
  1368. } else {
  1369. that.incomingStore.put(packet, function () {
  1370. that._sendPacket({ cmd: 'pubrec', messageId: messageId }, done)
  1371. })
  1372. }
  1373. })
  1374. break
  1375. }
  1376. case 1: {
  1377. // emit the message event
  1378. options.customHandleAcks(topic, message, packet, function (error, code) {
  1379. if (!(error instanceof Error)) {
  1380. code = error
  1381. error = null
  1382. }
  1383. if (error) { return that.emit('error', error) }
  1384. if (validReasonCodes.indexOf(code) === -1) { return that.emit('error', new Error('Wrong reason code for puback')) }
  1385. if (!code) { that.emit('message', topic, message, packet) }
  1386. that.handleMessage(packet, function (err) {
  1387. if (err) {
  1388. return done && done(err)
  1389. }
  1390. that._sendPacket({ cmd: 'puback', messageId: messageId, reasonCode: code }, done)
  1391. })
  1392. })
  1393. break
  1394. }
  1395. case 0:
  1396. // emit the message event
  1397. this.emit('message', topic, message, packet)
  1398. this.handleMessage(packet, done)
  1399. break
  1400. default:
  1401. // do nothing
  1402. debug('_handlePublish: unknown QoS. Doing nothing.')
  1403. // log or throw an error about unknown qos
  1404. break
  1405. }
  1406. }
  1407. /**
  1408. * Handle messages with backpressure support, one at a time.
  1409. * Override at will.
  1410. *
  1411. * @param Packet packet the packet
  1412. * @param Function callback call when finished
  1413. * @api public
  1414. */
  1415. MqttClient.prototype.handleMessage = function (packet, callback) {
  1416. callback()
  1417. }
  1418. /**
  1419. * _handleAck
  1420. *
  1421. * @param {Object} packet
  1422. * @api private
  1423. */
  1424. MqttClient.prototype._handleAck = function (packet) {
  1425. /* eslint no-fallthrough: "off" */
  1426. const messageId = packet.messageId
  1427. const type = packet.cmd
  1428. let response = null
  1429. const cb = this.outgoing[messageId] ? this.outgoing[messageId].cb : null
  1430. const that = this
  1431. let err
  1432. // Checking `!cb` happens to work, but it's not technically "correct".
  1433. //
  1434. // Why? This code assumes that "no callback" is the same as that "we're not
  1435. // waiting for responses" (puback, pubrec, pubcomp, suback, or unsuback).
  1436. //
  1437. // It would be better to check `if (!this.outgoing[messageId])` here, but
  1438. // there's no reason to change it and risk (another) regression.
  1439. //
  1440. // The only reason this code works is becaues code in MqttClient.publish,
  1441. // MqttClinet.subscribe, and MqttClient.unsubscribe ensures that we will
  1442. // have a callback even if the user doesn't pass one in.)
  1443. if (!cb) {
  1444. debug('_handleAck :: Server sent an ack in error. Ignoring.')
  1445. // Server sent an ack in error, ignore it.
  1446. return
  1447. }
  1448. // Process
  1449. debug('_handleAck :: packet type', type)
  1450. switch (type) {
  1451. case 'pubcomp':
  1452. // same thing as puback for QoS 2
  1453. case 'puback': {
  1454. const pubackRC = packet.reasonCode
  1455. // Callback - we're done
  1456. if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
  1457. err = new Error('Publish error: ' + errors[pubackRC])
  1458. err.code = pubackRC
  1459. cb(err, packet)
  1460. }
  1461. delete this.outgoing[messageId]
  1462. this.outgoingStore.del(packet, cb)
  1463. this.messageIdProvider.deallocate(messageId)
  1464. this._invokeStoreProcessingQueue()
  1465. break
  1466. }
  1467. case 'pubrec': {
  1468. response = {
  1469. cmd: 'pubrel',
  1470. qos: 2,
  1471. messageId: messageId
  1472. }
  1473. const pubrecRC = packet.reasonCode
  1474. if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
  1475. err = new Error('Publish error: ' + errors[pubrecRC])
  1476. err.code = pubrecRC
  1477. cb(err, packet)
  1478. } else {
  1479. this._sendPacket(response)
  1480. }
  1481. break
  1482. }
  1483. case 'suback': {
  1484. delete this.outgoing[messageId]
  1485. this.messageIdProvider.deallocate(messageId)
  1486. for (let grantedI = 0; grantedI < packet.granted.length; grantedI++) {
  1487. if ((packet.granted[grantedI] & 0x80) !== 0) {
  1488. // suback with Failure status
  1489. const topics = this.messageIdToTopic[messageId]
  1490. if (topics) {
  1491. topics.forEach(function (topic) {
  1492. delete that._resubscribeTopics[topic]
  1493. })
  1494. }
  1495. }
  1496. }
  1497. this._invokeStoreProcessingQueue()
  1498. cb(null, packet)
  1499. break
  1500. }
  1501. case 'unsuback': {
  1502. delete this.outgoing[messageId]
  1503. this.messageIdProvider.deallocate(messageId)
  1504. this._invokeStoreProcessingQueue()
  1505. cb(null)
  1506. break
  1507. }
  1508. default:
  1509. that.emit('error', new Error('unrecognized packet type'))
  1510. }
  1511. if (this.disconnecting &&
  1512. Object.keys(this.outgoing).length === 0) {
  1513. this.emit('outgoingEmpty')
  1514. }
  1515. }
  1516. /**
  1517. * _handlePubrel
  1518. *
  1519. * @param {Object} packet
  1520. * @api private
  1521. */
  1522. MqttClient.prototype._handlePubrel = function (packet, callback) {
  1523. debug('handling pubrel packet')
  1524. callback = typeof callback !== 'undefined' ? callback : nop
  1525. const messageId = packet.messageId
  1526. const that = this
  1527. const comp = { cmd: 'pubcomp', messageId: messageId }
  1528. that.incomingStore.get(packet, function (err, pub) {
  1529. if (!err) {
  1530. that.emit('message', pub.topic, pub.payload, pub)
  1531. that.handleMessage(pub, function (err) {
  1532. if (err) {
  1533. return callback(err)
  1534. }
  1535. that.incomingStore.del(pub, nop)
  1536. that._sendPacket(comp, callback)
  1537. })
  1538. } else {
  1539. that._sendPacket(comp, callback)
  1540. }
  1541. })
  1542. }
  1543. /**
  1544. * _handleDisconnect
  1545. *
  1546. * @param {Object} packet
  1547. * @api private
  1548. */
  1549. MqttClient.prototype._handleDisconnect = function (packet) {
  1550. this.emit('disconnect', packet)
  1551. }
  1552. /**
  1553. * _nextId
  1554. * @return unsigned int
  1555. */
  1556. MqttClient.prototype._nextId = function () {
  1557. return this.messageIdProvider.allocate()
  1558. }
  1559. /**
  1560. * getLastMessageId
  1561. * @return unsigned int
  1562. */
  1563. MqttClient.prototype.getLastMessageId = function () {
  1564. return this.messageIdProvider.getLastAllocated()
  1565. }
  1566. /**
  1567. * _resubscribe
  1568. * @api private
  1569. */
  1570. MqttClient.prototype._resubscribe = function () {
  1571. debug('_resubscribe')
  1572. const _resubscribeTopicsKeys = Object.keys(this._resubscribeTopics)
  1573. if (!this._firstConnection &&
  1574. (this.options.clean || (this.options.protocolVersion === 5 && !this.connackPacket.sessionPresent)) &&
  1575. _resubscribeTopicsKeys.length > 0) {
  1576. if (this.options.resubscribe) {
  1577. if (this.options.protocolVersion === 5) {
  1578. debug('_resubscribe: protocolVersion 5')
  1579. for (let topicI = 0; topicI < _resubscribeTopicsKeys.length; topicI++) {
  1580. const resubscribeTopic = {}
  1581. resubscribeTopic[_resubscribeTopicsKeys[topicI]] = this._resubscribeTopics[_resubscribeTopicsKeys[topicI]]
  1582. resubscribeTopic.resubscribe = true
  1583. this.subscribe(resubscribeTopic, { properties: resubscribeTopic[_resubscribeTopicsKeys[topicI]].properties })
  1584. }
  1585. } else {
  1586. this._resubscribeTopics.resubscribe = true
  1587. this.subscribe(this._resubscribeTopics)
  1588. }
  1589. } else {
  1590. this._resubscribeTopics = {}
  1591. }
  1592. }
  1593. this._firstConnection = false
  1594. }
  1595. /**
  1596. * _onConnect
  1597. *
  1598. * @api private
  1599. */
  1600. MqttClient.prototype._onConnect = function (packet) {
  1601. if (this.disconnected) {
  1602. this.emit('connect', packet)
  1603. return
  1604. }
  1605. const that = this
  1606. this.connackPacket = packet
  1607. this.messageIdProvider.clear()
  1608. this._setupPingTimer()
  1609. this.connected = true
  1610. function startStreamProcess () {
  1611. let outStore = that.outgoingStore.createStream()
  1612. function clearStoreProcessing () {
  1613. that._storeProcessing = false
  1614. that._packetIdsDuringStoreProcessing = {}
  1615. }
  1616. that.once('close', remove)
  1617. outStore.on('error', function (err) {
  1618. clearStoreProcessing()
  1619. that._flushStoreProcessingQueue()
  1620. that.removeListener('close', remove)
  1621. that.emit('error', err)
  1622. })
  1623. function remove () {
  1624. outStore.destroy()
  1625. outStore = null
  1626. that._flushStoreProcessingQueue()
  1627. clearStoreProcessing()
  1628. }
  1629. function storeDeliver () {
  1630. // edge case, we wrapped this twice
  1631. if (!outStore) {
  1632. return
  1633. }
  1634. that._storeProcessing = true
  1635. const packet = outStore.read(1)
  1636. let cb
  1637. if (!packet) {
  1638. // read when data is available in the future
  1639. outStore.once('readable', storeDeliver)
  1640. return
  1641. }
  1642. // Skip already processed store packets
  1643. if (that._packetIdsDuringStoreProcessing[packet.messageId]) {
  1644. storeDeliver()
  1645. return
  1646. }
  1647. // Avoid unnecessary stream read operations when disconnected
  1648. if (!that.disconnecting && !that.reconnectTimer) {
  1649. cb = that.outgoing[packet.messageId] ? that.outgoing[packet.messageId].cb : null
  1650. that.outgoing[packet.messageId] = {
  1651. volatile: false,
  1652. cb: function (err, status) {
  1653. // Ensure that the original callback passed in to publish gets invoked
  1654. if (cb) {
  1655. cb(err, status)
  1656. }
  1657. storeDeliver()
  1658. }
  1659. }
  1660. that._packetIdsDuringStoreProcessing[packet.messageId] = true
  1661. if (that.messageIdProvider.register(packet.messageId)) {
  1662. that._sendPacket(packet)
  1663. } else {
  1664. debug('messageId: %d has already used.', packet.messageId)
  1665. }
  1666. } else if (outStore.destroy) {
  1667. outStore.destroy()
  1668. }
  1669. }
  1670. outStore.on('end', function () {
  1671. let allProcessed = true
  1672. for (const id in that._packetIdsDuringStoreProcessing) {
  1673. if (!that._packetIdsDuringStoreProcessing[id]) {
  1674. allProcessed = false
  1675. break
  1676. }
  1677. }
  1678. if (allProcessed) {
  1679. clearStoreProcessing()
  1680. that.removeListener('close', remove)
  1681. that._invokeAllStoreProcessingQueue()
  1682. that.emit('connect', packet)
  1683. } else {
  1684. startStreamProcess()
  1685. }
  1686. })
  1687. storeDeliver()
  1688. }
  1689. // start flowing
  1690. startStreamProcess()
  1691. }
  1692. MqttClient.prototype._invokeStoreProcessingQueue = function () {
  1693. if (this._storeProcessingQueue.length > 0) {
  1694. const f = this._storeProcessingQueue[0]
  1695. if (f && f.invoke()) {
  1696. this._storeProcessingQueue.shift()
  1697. return true
  1698. }
  1699. }
  1700. return false
  1701. }
  1702. MqttClient.prototype._invokeAllStoreProcessingQueue = function () {
  1703. while (this._invokeStoreProcessingQueue()) { /* empty */ }
  1704. }
  1705. MqttClient.prototype._flushStoreProcessingQueue = function () {
  1706. for (const f of this._storeProcessingQueue) {
  1707. if (f.cbStorePut) f.cbStorePut(new Error('Connection closed'))
  1708. if (f.callback) f.callback(new Error('Connection closed'))
  1709. }
  1710. this._storeProcessingQueue.splice(0)
  1711. }
  1712. module.exports = MqttClient
  1713. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1714. },{"./default-message-id-provider":7,"./store":8,"./topic-alias-recv":9,"./topic-alias-send":10,"./validations":11,"_process":50,"debug":18,"events":22,"inherits":24,"mqtt-packet":40,"readable-stream":69,"reinterval":70,"rfdc/default":71,"xtend":81}],2:[function(require,module,exports){
  1715. 'use strict'
  1716. const { Buffer } = require('buffer')
  1717. const Transform = require('readable-stream').Transform
  1718. const duplexify = require('duplexify')
  1719. /* global FileReader */
  1720. let my
  1721. let proxy
  1722. let stream
  1723. let isInitialized = false
  1724. function buildProxy () {
  1725. const proxy = new Transform()
  1726. proxy._write = function (chunk, encoding, next) {
  1727. my.sendSocketMessage({
  1728. data: chunk.buffer,
  1729. success: function () {
  1730. next()
  1731. },
  1732. fail: function () {
  1733. next(new Error())
  1734. }
  1735. })
  1736. }
  1737. proxy._flush = function socketEnd (done) {
  1738. my.closeSocket({
  1739. success: function () {
  1740. done()
  1741. }
  1742. })
  1743. }
  1744. return proxy
  1745. }
  1746. function setDefaultOpts (opts) {
  1747. if (!opts.hostname) {
  1748. opts.hostname = 'localhost'
  1749. }
  1750. if (!opts.path) {
  1751. opts.path = '/'
  1752. }
  1753. if (!opts.wsOptions) {
  1754. opts.wsOptions = {}
  1755. }
  1756. }
  1757. function buildUrl (opts, client) {
  1758. const protocol = opts.protocol === 'alis' ? 'wss' : 'ws'
  1759. let url = protocol + '://' + opts.hostname + opts.path
  1760. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  1761. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1762. }
  1763. if (typeof (opts.transformWsUrl) === 'function') {
  1764. url = opts.transformWsUrl(url, opts, client)
  1765. }
  1766. return url
  1767. }
  1768. function bindEventHandler () {
  1769. if (isInitialized) return
  1770. isInitialized = true
  1771. my.onSocketOpen(function () {
  1772. stream.setReadable(proxy)
  1773. stream.setWritable(proxy)
  1774. stream.emit('connect')
  1775. })
  1776. my.onSocketMessage(function (res) {
  1777. if (typeof res.data === 'string') {
  1778. const buffer = Buffer.from(res.data, 'base64')
  1779. proxy.push(buffer)
  1780. } else {
  1781. const reader = new FileReader()
  1782. reader.addEventListener('load', function () {
  1783. let data = reader.result
  1784. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  1785. else data = Buffer.from(data, 'utf8')
  1786. proxy.push(data)
  1787. })
  1788. reader.readAsArrayBuffer(res.data)
  1789. }
  1790. })
  1791. my.onSocketClose(function () {
  1792. stream.end()
  1793. stream.destroy()
  1794. })
  1795. my.onSocketError(function (res) {
  1796. stream.destroy(res)
  1797. })
  1798. }
  1799. function buildStream (client, opts) {
  1800. opts.hostname = opts.hostname || opts.host
  1801. if (!opts.hostname) {
  1802. throw new Error('Could not determine host. Specify host manually.')
  1803. }
  1804. const websocketSubProtocol =
  1805. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1806. ? 'mqttv3.1'
  1807. : 'mqtt'
  1808. setDefaultOpts(opts)
  1809. const url = buildUrl(opts, client)
  1810. my = opts.my
  1811. my.connectSocket({
  1812. url: url,
  1813. protocols: websocketSubProtocol
  1814. })
  1815. proxy = buildProxy()
  1816. stream = duplexify.obj()
  1817. bindEventHandler()
  1818. return stream
  1819. }
  1820. module.exports = buildStream
  1821. },{"buffer":17,"duplexify":20,"readable-stream":69}],3:[function(require,module,exports){
  1822. 'use strict'
  1823. const net = require('net')
  1824. const debug = require('debug')('mqttjs:tcp')
  1825. /*
  1826. variables port and host can be removed since
  1827. you have all required information in opts object
  1828. */
  1829. function streamBuilder (client, opts) {
  1830. opts.port = opts.port || 1883
  1831. opts.hostname = opts.hostname || opts.host || 'localhost'
  1832. const port = opts.port
  1833. const host = opts.hostname
  1834. debug('port %d and host %s', port, host)
  1835. return net.createConnection(port, host)
  1836. }
  1837. module.exports = streamBuilder
  1838. },{"debug":18,"net":16}],4:[function(require,module,exports){
  1839. 'use strict'
  1840. const tls = require('tls')
  1841. const net = require('net')
  1842. const debug = require('debug')('mqttjs:tls')
  1843. function buildBuilder (mqttClient, opts) {
  1844. opts.port = opts.port || 8883
  1845. opts.host = opts.hostname || opts.host || 'localhost'
  1846. if (net.isIP(opts.host) === 0) {
  1847. opts.servername = opts.host
  1848. }
  1849. opts.rejectUnauthorized = opts.rejectUnauthorized !== false
  1850. delete opts.path
  1851. debug('port %d host %s rejectUnauthorized %b', opts.port, opts.host, opts.rejectUnauthorized)
  1852. const connection = tls.connect(opts)
  1853. /* eslint no-use-before-define: [2, "nofunc"] */
  1854. connection.on('secureConnect', function () {
  1855. if (opts.rejectUnauthorized && !connection.authorized) {
  1856. connection.emit('error', new Error('TLS not authorized'))
  1857. } else {
  1858. connection.removeListener('error', handleTLSerrors)
  1859. }
  1860. })
  1861. function handleTLSerrors (err) {
  1862. // How can I get verify this error is a tls error?
  1863. if (opts.rejectUnauthorized) {
  1864. mqttClient.emit('error', err)
  1865. }
  1866. // close this connection to match the behaviour of net
  1867. // otherwise all we get is an error from the connection
  1868. // and close event doesn't fire. This is a work around
  1869. // to enable the reconnect code to work the same as with
  1870. // net.createConnection
  1871. connection.end()
  1872. }
  1873. connection.on('error', handleTLSerrors)
  1874. return connection
  1875. }
  1876. module.exports = buildBuilder
  1877. },{"debug":18,"net":16,"tls":16}],5:[function(require,module,exports){
  1878. (function (process){(function (){
  1879. 'use strict'
  1880. const { Buffer } = require('buffer')
  1881. const WS = require('ws')
  1882. const debug = require('debug')('mqttjs:ws')
  1883. const duplexify = require('duplexify')
  1884. const Transform = require('readable-stream').Transform
  1885. const WSS_OPTIONS = [
  1886. 'rejectUnauthorized',
  1887. 'ca',
  1888. 'cert',
  1889. 'key',
  1890. 'pfx',
  1891. 'passphrase'
  1892. ]
  1893. // eslint-disable-next-line camelcase
  1894. const IS_BROWSER = (typeof process !== 'undefined' && process.title === 'browser') || typeof __webpack_require__ === 'function'
  1895. function buildUrl (opts, client) {
  1896. let url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  1897. if (typeof (opts.transformWsUrl) === 'function') {
  1898. url = opts.transformWsUrl(url, opts, client)
  1899. }
  1900. return url
  1901. }
  1902. function setDefaultOpts (opts) {
  1903. const options = opts
  1904. if (!opts.hostname) {
  1905. options.hostname = 'localhost'
  1906. }
  1907. if (!opts.port) {
  1908. if (opts.protocol === 'wss') {
  1909. options.port = 443
  1910. } else {
  1911. options.port = 80
  1912. }
  1913. }
  1914. if (!opts.path) {
  1915. options.path = '/'
  1916. }
  1917. if (!opts.wsOptions) {
  1918. options.wsOptions = {}
  1919. }
  1920. if (!IS_BROWSER && opts.protocol === 'wss') {
  1921. // Add cert/key/ca etc options
  1922. WSS_OPTIONS.forEach(function (prop) {
  1923. if (Object.prototype.hasOwnProperty.call(opts, prop) && !Object.prototype.hasOwnProperty.call(opts.wsOptions, prop)) {
  1924. options.wsOptions[prop] = opts[prop]
  1925. }
  1926. })
  1927. }
  1928. return options
  1929. }
  1930. function setDefaultBrowserOpts (opts) {
  1931. const options = setDefaultOpts(opts)
  1932. if (!options.hostname) {
  1933. options.hostname = options.host
  1934. }
  1935. if (!options.hostname) {
  1936. // Throwing an error in a Web Worker if no `hostname` is given, because we
  1937. // can not determine the `hostname` automatically. If connecting to
  1938. // localhost, please supply the `hostname` as an argument.
  1939. if (typeof (document) === 'undefined') {
  1940. throw new Error('Could not determine host. Specify host manually.')
  1941. }
  1942. const parsed = new URL(document.URL)
  1943. options.hostname = parsed.hostname
  1944. if (!options.port) {
  1945. options.port = parsed.port
  1946. }
  1947. }
  1948. // objectMode should be defined for logic
  1949. if (options.objectMode === undefined) {
  1950. options.objectMode = !(options.binary === true || options.binary === undefined)
  1951. }
  1952. return options
  1953. }
  1954. function createWebSocket (client, url, opts) {
  1955. debug('createWebSocket')
  1956. debug('protocol: ' + opts.protocolId + ' ' + opts.protocolVersion)
  1957. const websocketSubProtocol =
  1958. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1959. ? 'mqttv3.1'
  1960. : 'mqtt'
  1961. debug('creating new Websocket for url: ' + url + ' and protocol: ' + websocketSubProtocol)
  1962. const socket = new WS(url, [websocketSubProtocol], opts.wsOptions)
  1963. return socket
  1964. }
  1965. function createBrowserWebSocket (client, opts) {
  1966. const websocketSubProtocol =
  1967. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  1968. ? 'mqttv3.1'
  1969. : 'mqtt'
  1970. const url = buildUrl(opts, client)
  1971. /* global WebSocket */
  1972. const socket = new WebSocket(url, [websocketSubProtocol])
  1973. socket.binaryType = 'arraybuffer'
  1974. return socket
  1975. }
  1976. function streamBuilder (client, opts) {
  1977. debug('streamBuilder')
  1978. const options = setDefaultOpts(opts)
  1979. const url = buildUrl(options, client)
  1980. const socket = createWebSocket(client, url, options)
  1981. const webSocketStream = WS.createWebSocketStream(socket, options.wsOptions)
  1982. webSocketStream.url = url
  1983. socket.on('close', () => { webSocketStream.destroy() })
  1984. return webSocketStream
  1985. }
  1986. function browserStreamBuilder (client, opts) {
  1987. debug('browserStreamBuilder')
  1988. let stream
  1989. const options = setDefaultBrowserOpts(opts)
  1990. // sets the maximum socket buffer size before throttling
  1991. const bufferSize = options.browserBufferSize || 1024 * 512
  1992. const bufferTimeout = opts.browserBufferTimeout || 1000
  1993. const coerceToBuffer = !opts.objectMode
  1994. const socket = createBrowserWebSocket(client, opts)
  1995. const proxy = buildProxy(opts, socketWriteBrowser, socketEndBrowser)
  1996. if (!opts.objectMode) {
  1997. proxy._writev = writev
  1998. }
  1999. proxy.on('close', () => { socket.close() })
  2000. const eventListenerSupport = (typeof socket.addEventListener !== 'undefined')
  2001. // was already open when passed in
  2002. if (socket.readyState === socket.OPEN) {
  2003. stream = proxy
  2004. } else {
  2005. stream = stream = duplexify(undefined, undefined, opts)
  2006. if (!opts.objectMode) {
  2007. stream._writev = writev
  2008. }
  2009. if (eventListenerSupport) {
  2010. socket.addEventListener('open', onopen)
  2011. } else {
  2012. socket.onopen = onopen
  2013. }
  2014. }
  2015. stream.socket = socket
  2016. if (eventListenerSupport) {
  2017. socket.addEventListener('close', onclose)
  2018. socket.addEventListener('error', onerror)
  2019. socket.addEventListener('message', onmessage)
  2020. } else {
  2021. socket.onclose = onclose
  2022. socket.onerror = onerror
  2023. socket.onmessage = onmessage
  2024. }
  2025. // methods for browserStreamBuilder
  2026. function buildProxy (options, socketWrite, socketEnd) {
  2027. const proxy = new Transform({
  2028. objectModeMode: options.objectMode
  2029. })
  2030. proxy._write = socketWrite
  2031. proxy._flush = socketEnd
  2032. return proxy
  2033. }
  2034. function onopen () {
  2035. stream.setReadable(proxy)
  2036. stream.setWritable(proxy)
  2037. stream.emit('connect')
  2038. }
  2039. function onclose () {
  2040. stream.end()
  2041. stream.destroy()
  2042. }
  2043. function onerror (err) {
  2044. stream.destroy(err)
  2045. }
  2046. function onmessage (event) {
  2047. let data = event.data
  2048. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  2049. else data = Buffer.from(data, 'utf8')
  2050. proxy.push(data)
  2051. }
  2052. // this is to be enabled only if objectMode is false
  2053. function writev (chunks, cb) {
  2054. const buffers = new Array(chunks.length)
  2055. for (let i = 0; i < chunks.length; i++) {
  2056. if (typeof chunks[i].chunk === 'string') {
  2057. buffers[i] = Buffer.from(chunks[i], 'utf8')
  2058. } else {
  2059. buffers[i] = chunks[i].chunk
  2060. }
  2061. }
  2062. this._write(Buffer.concat(buffers), 'binary', cb)
  2063. }
  2064. function socketWriteBrowser (chunk, enc, next) {
  2065. if (socket.bufferedAmount > bufferSize) {
  2066. // throttle data until buffered amount is reduced.
  2067. setTimeout(socketWriteBrowser, bufferTimeout, chunk, enc, next)
  2068. }
  2069. if (coerceToBuffer && typeof chunk === 'string') {
  2070. chunk = Buffer.from(chunk, 'utf8')
  2071. }
  2072. try {
  2073. socket.send(chunk)
  2074. } catch (err) {
  2075. return next(err)
  2076. }
  2077. next()
  2078. }
  2079. function socketEndBrowser (done) {
  2080. socket.close()
  2081. done()
  2082. }
  2083. // end methods for browserStreamBuilder
  2084. return stream
  2085. }
  2086. if (IS_BROWSER) {
  2087. module.exports = browserStreamBuilder
  2088. } else {
  2089. module.exports = streamBuilder
  2090. }
  2091. }).call(this)}).call(this,require('_process'))
  2092. },{"_process":50,"buffer":17,"debug":18,"duplexify":20,"readable-stream":69,"ws":80}],6:[function(require,module,exports){
  2093. 'use strict'
  2094. const { Buffer } = require('buffer')
  2095. const Transform = require('readable-stream').Transform
  2096. const duplexify = require('duplexify')
  2097. /* global wx */
  2098. let socketTask, proxy, stream
  2099. function buildProxy () {
  2100. const proxy = new Transform()
  2101. proxy._write = function (chunk, encoding, next) {
  2102. socketTask.send({
  2103. data: chunk.buffer,
  2104. success: function () {
  2105. next()
  2106. },
  2107. fail: function (errMsg) {
  2108. next(new Error(errMsg))
  2109. }
  2110. })
  2111. }
  2112. proxy._flush = function socketEnd (done) {
  2113. socketTask.close({
  2114. success: function () {
  2115. done()
  2116. }
  2117. })
  2118. }
  2119. return proxy
  2120. }
  2121. function setDefaultOpts (opts) {
  2122. if (!opts.hostname) {
  2123. opts.hostname = 'localhost'
  2124. }
  2125. if (!opts.path) {
  2126. opts.path = '/'
  2127. }
  2128. if (!opts.wsOptions) {
  2129. opts.wsOptions = {}
  2130. }
  2131. }
  2132. function buildUrl (opts, client) {
  2133. const protocol = opts.protocol === 'wxs' ? 'wss' : 'ws'
  2134. let url = protocol + '://' + opts.hostname + opts.path
  2135. if (opts.port && opts.port !== 80 && opts.port !== 443) {
  2136. url = protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  2137. }
  2138. if (typeof (opts.transformWsUrl) === 'function') {
  2139. url = opts.transformWsUrl(url, opts, client)
  2140. }
  2141. return url
  2142. }
  2143. function bindEventHandler () {
  2144. socketTask.onOpen(function () {
  2145. stream.setReadable(proxy)
  2146. stream.setWritable(proxy)
  2147. stream.emit('connect')
  2148. })
  2149. socketTask.onMessage(function (res) {
  2150. let data = res.data
  2151. if (data instanceof ArrayBuffer) data = Buffer.from(data)
  2152. else data = Buffer.from(data, 'utf8')
  2153. proxy.push(data)
  2154. })
  2155. socketTask.onClose(function () {
  2156. stream.end()
  2157. stream.destroy()
  2158. })
  2159. socketTask.onError(function (res) {
  2160. stream.destroy(new Error(res.errMsg))
  2161. })
  2162. }
  2163. function buildStream (client, opts) {
  2164. opts.hostname = opts.hostname || opts.host
  2165. if (!opts.hostname) {
  2166. throw new Error('Could not determine host. Specify host manually.')
  2167. }
  2168. const websocketSubProtocol =
  2169. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  2170. ? 'mqttv3.1'
  2171. : 'mqtt'
  2172. setDefaultOpts(opts)
  2173. const url = buildUrl(opts, client)
  2174. socketTask = wx.connectSocket({
  2175. url: url,
  2176. protocols: [websocketSubProtocol]
  2177. })
  2178. proxy = buildProxy()
  2179. stream = duplexify.obj()
  2180. stream._destroy = function (err, cb) {
  2181. socketTask.close({
  2182. success: function () {
  2183. cb && cb(err)
  2184. }
  2185. })
  2186. }
  2187. const destroyRef = stream.destroy
  2188. stream.destroy = function () {
  2189. stream.destroy = destroyRef
  2190. const self = this
  2191. setTimeout(function () {
  2192. socketTask.close({
  2193. fail: function () {
  2194. self._destroy(new Error())
  2195. }
  2196. })
  2197. }, 0)
  2198. }.bind(stream)
  2199. bindEventHandler()
  2200. return stream
  2201. }
  2202. module.exports = buildStream
  2203. },{"buffer":17,"duplexify":20,"readable-stream":69}],7:[function(require,module,exports){
  2204. 'use strict'
  2205. /**
  2206. * DefaultMessageAllocator constructor
  2207. * @constructor
  2208. */
  2209. function DefaultMessageIdProvider () {
  2210. if (!(this instanceof DefaultMessageIdProvider)) {
  2211. return new DefaultMessageIdProvider()
  2212. }
  2213. /**
  2214. * MessageIDs starting with 1
  2215. * ensure that nextId is min. 1, see https://github.com/mqttjs/MQTT.js/issues/810
  2216. */
  2217. this.nextId = Math.max(1, Math.floor(Math.random() * 65535))
  2218. }
  2219. /**
  2220. * allocate
  2221. *
  2222. * Get the next messageId.
  2223. * @return unsigned int
  2224. */
  2225. DefaultMessageIdProvider.prototype.allocate = function () {
  2226. // id becomes current state of this.nextId and increments afterwards
  2227. const id = this.nextId++
  2228. // Ensure 16 bit unsigned int (max 65535, nextId got one higher)
  2229. if (this.nextId === 65536) {
  2230. this.nextId = 1
  2231. }
  2232. return id
  2233. }
  2234. /**
  2235. * getLastAllocated
  2236. * Get the last allocated messageId.
  2237. * @return unsigned int
  2238. */
  2239. DefaultMessageIdProvider.prototype.getLastAllocated = function () {
  2240. return (this.nextId === 1) ? 65535 : (this.nextId - 1)
  2241. }
  2242. /**
  2243. * register
  2244. * Register messageId. If success return true, otherwise return false.
  2245. * @param { unsigned int } - messageId to register,
  2246. * @return boolean
  2247. */
  2248. DefaultMessageIdProvider.prototype.register = function (messageId) {
  2249. return true
  2250. }
  2251. /**
  2252. * deallocate
  2253. * Deallocate messageId.
  2254. * @param { unsigned int } - messageId to deallocate,
  2255. */
  2256. DefaultMessageIdProvider.prototype.deallocate = function (messageId) {
  2257. }
  2258. /**
  2259. * clear
  2260. * Deallocate all messageIds.
  2261. */
  2262. DefaultMessageIdProvider.prototype.clear = function () {
  2263. }
  2264. module.exports = DefaultMessageIdProvider
  2265. },{}],8:[function(require,module,exports){
  2266. 'use strict'
  2267. /**
  2268. * Module dependencies
  2269. */
  2270. const xtend = require('xtend')
  2271. const Readable = require('readable-stream').Readable
  2272. const streamsOpts = { objectMode: true }
  2273. const defaultStoreOptions = {
  2274. clean: true
  2275. }
  2276. /**
  2277. * In-memory implementation of the message store
  2278. * This can actually be saved into files.
  2279. *
  2280. * @param {Object} [options] - store options
  2281. */
  2282. function Store (options) {
  2283. if (!(this instanceof Store)) {
  2284. return new Store(options)
  2285. }
  2286. this.options = options || {}
  2287. // Defaults
  2288. this.options = xtend(defaultStoreOptions, options)
  2289. this._inflights = new Map()
  2290. }
  2291. /**
  2292. * Adds a packet to the store, a packet is
  2293. * anything that has a messageId property.
  2294. *
  2295. */
  2296. Store.prototype.put = function (packet, cb) {
  2297. this._inflights.set(packet.messageId, packet)
  2298. if (cb) {
  2299. cb()
  2300. }
  2301. return this
  2302. }
  2303. /**
  2304. * Creates a stream with all the packets in the store
  2305. *
  2306. */
  2307. Store.prototype.createStream = function () {
  2308. const stream = new Readable(streamsOpts)
  2309. const values = []
  2310. let destroyed = false
  2311. let i = 0
  2312. this._inflights.forEach(function (value, key) {
  2313. values.push(value)
  2314. })
  2315. stream._read = function () {
  2316. if (!destroyed && i < values.length) {
  2317. this.push(values[i++])
  2318. } else {
  2319. this.push(null)
  2320. }
  2321. }
  2322. stream.destroy = function () {
  2323. if (destroyed) {
  2324. return
  2325. }
  2326. const self = this
  2327. destroyed = true
  2328. setTimeout(function () {
  2329. self.emit('close')
  2330. }, 0)
  2331. }
  2332. return stream
  2333. }
  2334. /**
  2335. * deletes a packet from the store.
  2336. */
  2337. Store.prototype.del = function (packet, cb) {
  2338. packet = this._inflights.get(packet.messageId)
  2339. if (packet) {
  2340. this._inflights.delete(packet.messageId)
  2341. cb(null, packet)
  2342. } else if (cb) {
  2343. cb(new Error('missing packet'))
  2344. }
  2345. return this
  2346. }
  2347. /**
  2348. * get a packet from the store.
  2349. */
  2350. Store.prototype.get = function (packet, cb) {
  2351. packet = this._inflights.get(packet.messageId)
  2352. if (packet) {
  2353. cb(null, packet)
  2354. } else if (cb) {
  2355. cb(new Error('missing packet'))
  2356. }
  2357. return this
  2358. }
  2359. /**
  2360. * Close the store
  2361. */
  2362. Store.prototype.close = function (cb) {
  2363. if (this.options.clean) {
  2364. this._inflights = null
  2365. }
  2366. if (cb) {
  2367. cb()
  2368. }
  2369. }
  2370. module.exports = Store
  2371. },{"readable-stream":69,"xtend":81}],9:[function(require,module,exports){
  2372. 'use strict'
  2373. /**
  2374. * Topic Alias receiving manager
  2375. * This holds alias to topic map
  2376. * @param {Number} [max] - topic alias maximum entries
  2377. */
  2378. function TopicAliasRecv (max) {
  2379. if (!(this instanceof TopicAliasRecv)) {
  2380. return new TopicAliasRecv(max)
  2381. }
  2382. this.aliasToTopic = {}
  2383. this.max = max
  2384. }
  2385. /**
  2386. * Insert or update topic - alias entry.
  2387. * @param {String} [topic] - topic
  2388. * @param {Number} [alias] - topic alias
  2389. * @returns {Boolean} - if success return true otherwise false
  2390. */
  2391. TopicAliasRecv.prototype.put = function (topic, alias) {
  2392. if (alias === 0 || alias > this.max) {
  2393. return false
  2394. }
  2395. this.aliasToTopic[alias] = topic
  2396. this.length = Object.keys(this.aliasToTopic).length
  2397. return true
  2398. }
  2399. /**
  2400. * Get topic by alias
  2401. * @param {String} [topic] - topic
  2402. * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined
  2403. */
  2404. TopicAliasRecv.prototype.getTopicByAlias = function (alias) {
  2405. return this.aliasToTopic[alias]
  2406. }
  2407. /**
  2408. * Clear all entries
  2409. */
  2410. TopicAliasRecv.prototype.clear = function () {
  2411. this.aliasToTopic = {}
  2412. }
  2413. module.exports = TopicAliasRecv
  2414. },{}],10:[function(require,module,exports){
  2415. 'use strict'
  2416. /**
  2417. * Module dependencies
  2418. */
  2419. const LruMap = require('lru-cache')
  2420. const NumberAllocator = require('number-allocator').NumberAllocator
  2421. /**
  2422. * Topic Alias sending manager
  2423. * This holds both topic to alias and alias to topic map
  2424. * @param {Number} [max] - topic alias maximum entries
  2425. */
  2426. function TopicAliasSend (max) {
  2427. if (!(this instanceof TopicAliasSend)) {
  2428. return new TopicAliasSend(max)
  2429. }
  2430. if (max > 0) {
  2431. this.aliasToTopic = new LruMap({ max: max })
  2432. this.topicToAlias = {}
  2433. this.numberAllocator = new NumberAllocator(1, max)
  2434. this.max = max
  2435. this.length = 0
  2436. }
  2437. }
  2438. /**
  2439. * Insert or update topic - alias entry.
  2440. * @param {String} [topic] - topic
  2441. * @param {Number} [alias] - topic alias
  2442. * @returns {Boolean} - if success return true otherwise false
  2443. */
  2444. TopicAliasSend.prototype.put = function (topic, alias) {
  2445. if (alias === 0 || alias > this.max) {
  2446. return false
  2447. }
  2448. const entry = this.aliasToTopic.get(alias)
  2449. if (entry) {
  2450. delete this.topicToAlias[entry]
  2451. }
  2452. this.aliasToTopic.set(alias, topic)
  2453. this.topicToAlias[topic] = alias
  2454. this.numberAllocator.use(alias)
  2455. this.length = this.aliasToTopic.length
  2456. return true
  2457. }
  2458. /**
  2459. * Get topic by alias
  2460. * @param {Number} [alias] - topic alias
  2461. * @returns {String} - if mapped topic exists return topic, otherwise return undefined
  2462. */
  2463. TopicAliasSend.prototype.getTopicByAlias = function (alias) {
  2464. return this.aliasToTopic.get(alias)
  2465. }
  2466. /**
  2467. * Get topic by alias
  2468. * @param {String} [topic] - topic
  2469. * @returns {Number} - if mapped topic exists return topic alias, otherwise return undefined
  2470. */
  2471. TopicAliasSend.prototype.getAliasByTopic = function (topic) {
  2472. const alias = this.topicToAlias[topic]
  2473. if (typeof alias !== 'undefined') {
  2474. this.aliasToTopic.get(alias) // LRU update
  2475. }
  2476. return alias
  2477. }
  2478. /**
  2479. * Clear all entries
  2480. */
  2481. TopicAliasSend.prototype.clear = function () {
  2482. this.aliasToTopic.reset()
  2483. this.topicToAlias = {}
  2484. this.numberAllocator.clear()
  2485. this.length = 0
  2486. }
  2487. /**
  2488. * Get Least Recently Used (LRU) topic alias
  2489. * @returns {Number} - if vacant alias exists then return it, otherwise then return LRU alias
  2490. */
  2491. TopicAliasSend.prototype.getLruAlias = function () {
  2492. const alias = this.numberAllocator.firstVacant()
  2493. if (alias) return alias
  2494. return this.aliasToTopic.keys()[this.aliasToTopic.length - 1]
  2495. }
  2496. module.exports = TopicAliasSend
  2497. },{"lru-cache":37,"number-allocator":46}],11:[function(require,module,exports){
  2498. 'use strict'
  2499. /**
  2500. * Validate a topic to see if it's valid or not.
  2501. * A topic is valid if it follow below rules:
  2502. * - Rule #1: If any part of the topic is not `+` or `#`, then it must not contain `+` and '#'
  2503. * - Rule #2: Part `#` must be located at the end of the mailbox
  2504. *
  2505. * @param {String} topic - A topic
  2506. * @returns {Boolean} If the topic is valid, returns true. Otherwise, returns false.
  2507. */
  2508. function validateTopic (topic) {
  2509. const parts = topic.split('/')
  2510. for (let i = 0; i < parts.length; i++) {
  2511. if (parts[i] === '+') {
  2512. continue
  2513. }
  2514. if (parts[i] === '#') {
  2515. // for Rule #2
  2516. return i === parts.length - 1
  2517. }
  2518. if (parts[i].indexOf('+') !== -1 || parts[i].indexOf('#') !== -1) {
  2519. return false
  2520. }
  2521. }
  2522. return true
  2523. }
  2524. /**
  2525. * Validate an array of topics to see if any of them is valid or not
  2526. * @param {Array} topics - Array of topics
  2527. * @returns {String} If the topics is valid, returns null. Otherwise, returns the invalid one
  2528. */
  2529. function validateTopics (topics) {
  2530. if (topics.length === 0) {
  2531. return 'empty_topic_list'
  2532. }
  2533. for (let i = 0; i < topics.length; i++) {
  2534. if (!validateTopic(topics[i])) {
  2535. return topics[i]
  2536. }
  2537. }
  2538. return null
  2539. }
  2540. module.exports = {
  2541. validateTopics: validateTopics
  2542. }
  2543. },{}],12:[function(require,module,exports){
  2544. (function (process){(function (){
  2545. 'use strict'
  2546. const MqttClient = require('../client')
  2547. const Store = require('../store')
  2548. const url = require('url')
  2549. const xtend = require('xtend')
  2550. const debug = require('debug')('mqttjs')
  2551. const protocols = {}
  2552. // eslint-disable-next-line camelcase
  2553. if ((typeof process !== 'undefined' && process.title !== 'browser') || typeof __webpack_require__ !== 'function') {
  2554. protocols.mqtt = require('./tcp')
  2555. protocols.tcp = require('./tcp')
  2556. protocols.ssl = require('./tls')
  2557. protocols.tls = require('./tls')
  2558. protocols.mqtts = require('./tls')
  2559. } else {
  2560. protocols.wx = require('./wx')
  2561. protocols.wxs = require('./wx')
  2562. protocols.ali = require('./ali')
  2563. protocols.alis = require('./ali')
  2564. }
  2565. protocols.ws = require('./ws')
  2566. protocols.wss = require('./ws')
  2567. /**
  2568. * Parse the auth attribute and merge username and password in the options object.
  2569. *
  2570. * @param {Object} [opts] option object
  2571. */
  2572. function parseAuthOptions (opts) {
  2573. let matches
  2574. if (opts.auth) {
  2575. matches = opts.auth.match(/^(.+):(.+)$/)
  2576. if (matches) {
  2577. opts.username = matches[1]
  2578. opts.password = matches[2]
  2579. } else {
  2580. opts.username = opts.auth
  2581. }
  2582. }
  2583. }
  2584. /**
  2585. * connect - connect to an MQTT broker.
  2586. *
  2587. * @param {String} [brokerUrl] - url of the broker, optional
  2588. * @param {Object} opts - see MqttClient#constructor
  2589. */
  2590. function connect (brokerUrl, opts) {
  2591. debug('connecting to an MQTT broker...')
  2592. if ((typeof brokerUrl === 'object') && !opts) {
  2593. opts = brokerUrl
  2594. brokerUrl = null
  2595. }
  2596. opts = opts || {}
  2597. if (brokerUrl) {
  2598. // eslint-disable-next-line
  2599. const parsed = url.parse(brokerUrl, true)
  2600. if (parsed.port != null) {
  2601. parsed.port = Number(parsed.port)
  2602. }
  2603. opts = xtend(parsed, opts)
  2604. if (opts.protocol === null) {
  2605. throw new Error('Missing protocol')
  2606. }
  2607. opts.protocol = opts.protocol.replace(/:$/, '')
  2608. }
  2609. // merge in the auth options if supplied
  2610. parseAuthOptions(opts)
  2611. // support clientId passed in the query string of the url
  2612. if (opts.query && typeof opts.query.clientId === 'string') {
  2613. opts.clientId = opts.query.clientId
  2614. }
  2615. if (opts.cert && opts.key) {
  2616. if (opts.protocol) {
  2617. if (['mqtts', 'wss', 'wxs', 'alis'].indexOf(opts.protocol) === -1) {
  2618. switch (opts.protocol) {
  2619. case 'mqtt':
  2620. opts.protocol = 'mqtts'
  2621. break
  2622. case 'ws':
  2623. opts.protocol = 'wss'
  2624. break
  2625. case 'wx':
  2626. opts.protocol = 'wxs'
  2627. break
  2628. case 'ali':
  2629. opts.protocol = 'alis'
  2630. break
  2631. default:
  2632. throw new Error('Unknown protocol for secure connection: "' + opts.protocol + '"!')
  2633. }
  2634. }
  2635. } else {
  2636. // A cert and key was provided, however no protocol was specified, so we will throw an error.
  2637. throw new Error('Missing secure protocol key')
  2638. }
  2639. }
  2640. if (!protocols[opts.protocol]) {
  2641. const isSecure = ['mqtts', 'wss'].indexOf(opts.protocol) !== -1
  2642. opts.protocol = [
  2643. 'mqtt',
  2644. 'mqtts',
  2645. 'ws',
  2646. 'wss',
  2647. 'wx',
  2648. 'wxs',
  2649. 'ali',
  2650. 'alis'
  2651. ].filter(function (key, index) {
  2652. if (isSecure && index % 2 === 0) {
  2653. // Skip insecure protocols when requesting a secure one.
  2654. return false
  2655. }
  2656. return (typeof protocols[key] === 'function')
  2657. })[0]
  2658. }
  2659. if (opts.clean === false && !opts.clientId) {
  2660. throw new Error('Missing clientId for unclean clients')
  2661. }
  2662. if (opts.protocol) {
  2663. opts.defaultProtocol = opts.protocol
  2664. }
  2665. function wrapper (client) {
  2666. if (opts.servers) {
  2667. if (!client._reconnectCount || client._reconnectCount === opts.servers.length) {
  2668. client._reconnectCount = 0
  2669. }
  2670. opts.host = opts.servers[client._reconnectCount].host
  2671. opts.port = opts.servers[client._reconnectCount].port
  2672. opts.protocol = (!opts.servers[client._reconnectCount].protocol ? opts.defaultProtocol : opts.servers[client._reconnectCount].protocol)
  2673. opts.hostname = opts.host
  2674. client._reconnectCount++
  2675. }
  2676. debug('calling streambuilder for', opts.protocol)
  2677. return protocols[opts.protocol](client, opts)
  2678. }
  2679. const client = new MqttClient(wrapper, opts)
  2680. client.on('error', function () { /* Automatically set up client error handling */ })
  2681. return client
  2682. }
  2683. module.exports = connect
  2684. module.exports.connect = connect
  2685. module.exports.MqttClient = MqttClient
  2686. module.exports.Store = Store
  2687. }).call(this)}).call(this,require('_process'))
  2688. },{"../client":1,"../store":8,"./ali":2,"./tcp":3,"./tls":4,"./ws":5,"./wx":6,"_process":50,"debug":18,"url":76,"xtend":81}],13:[function(require,module,exports){
  2689. 'use strict'
  2690. exports.byteLength = byteLength
  2691. exports.toByteArray = toByteArray
  2692. exports.fromByteArray = fromByteArray
  2693. var lookup = []
  2694. var revLookup = []
  2695. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  2696. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  2697. for (var i = 0, len = code.length; i < len; ++i) {
  2698. lookup[i] = code[i]
  2699. revLookup[code.charCodeAt(i)] = i
  2700. }
  2701. // Support decoding URL-safe base64 strings, as Node.js does.
  2702. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  2703. revLookup['-'.charCodeAt(0)] = 62
  2704. revLookup['_'.charCodeAt(0)] = 63
  2705. function getLens (b64) {
  2706. var len = b64.length
  2707. if (len % 4 > 0) {
  2708. throw new Error('Invalid string. Length must be a multiple of 4')
  2709. }
  2710. // Trim off extra bytes after placeholder bytes are found
  2711. // See: https://github.com/beatgammit/base64-js/issues/42
  2712. var validLen = b64.indexOf('=')
  2713. if (validLen === -1) validLen = len
  2714. var placeHoldersLen = validLen === len
  2715. ? 0
  2716. : 4 - (validLen % 4)
  2717. return [validLen, placeHoldersLen]
  2718. }
  2719. // base64 is 4/3 + up to two characters of the original data
  2720. function byteLength (b64) {
  2721. var lens = getLens(b64)
  2722. var validLen = lens[0]
  2723. var placeHoldersLen = lens[1]
  2724. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2725. }
  2726. function _byteLength (b64, validLen, placeHoldersLen) {
  2727. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2728. }
  2729. function toByteArray (b64) {
  2730. var tmp
  2731. var lens = getLens(b64)
  2732. var validLen = lens[0]
  2733. var placeHoldersLen = lens[1]
  2734. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  2735. var curByte = 0
  2736. // if there are placeholders, only get up to the last complete 4 chars
  2737. var len = placeHoldersLen > 0
  2738. ? validLen - 4
  2739. : validLen
  2740. var i
  2741. for (i = 0; i < len; i += 4) {
  2742. tmp =
  2743. (revLookup[b64.charCodeAt(i)] << 18) |
  2744. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  2745. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  2746. revLookup[b64.charCodeAt(i + 3)]
  2747. arr[curByte++] = (tmp >> 16) & 0xFF
  2748. arr[curByte++] = (tmp >> 8) & 0xFF
  2749. arr[curByte++] = tmp & 0xFF
  2750. }
  2751. if (placeHoldersLen === 2) {
  2752. tmp =
  2753. (revLookup[b64.charCodeAt(i)] << 2) |
  2754. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  2755. arr[curByte++] = tmp & 0xFF
  2756. }
  2757. if (placeHoldersLen === 1) {
  2758. tmp =
  2759. (revLookup[b64.charCodeAt(i)] << 10) |
  2760. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  2761. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  2762. arr[curByte++] = (tmp >> 8) & 0xFF
  2763. arr[curByte++] = tmp & 0xFF
  2764. }
  2765. return arr
  2766. }
  2767. function tripletToBase64 (num) {
  2768. return lookup[num >> 18 & 0x3F] +
  2769. lookup[num >> 12 & 0x3F] +
  2770. lookup[num >> 6 & 0x3F] +
  2771. lookup[num & 0x3F]
  2772. }
  2773. function encodeChunk (uint8, start, end) {
  2774. var tmp
  2775. var output = []
  2776. for (var i = start; i < end; i += 3) {
  2777. tmp =
  2778. ((uint8[i] << 16) & 0xFF0000) +
  2779. ((uint8[i + 1] << 8) & 0xFF00) +
  2780. (uint8[i + 2] & 0xFF)
  2781. output.push(tripletToBase64(tmp))
  2782. }
  2783. return output.join('')
  2784. }
  2785. function fromByteArray (uint8) {
  2786. var tmp
  2787. var len = uint8.length
  2788. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  2789. var parts = []
  2790. var maxChunkLength = 16383 // must be multiple of 3
  2791. // go through the array every three bytes, we'll deal with trailing stuff later
  2792. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  2793. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  2794. }
  2795. // pad the end with zeros, but make sure to not forget the extra bytes
  2796. if (extraBytes === 1) {
  2797. tmp = uint8[len - 1]
  2798. parts.push(
  2799. lookup[tmp >> 2] +
  2800. lookup[(tmp << 4) & 0x3F] +
  2801. '=='
  2802. )
  2803. } else if (extraBytes === 2) {
  2804. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  2805. parts.push(
  2806. lookup[tmp >> 10] +
  2807. lookup[(tmp >> 4) & 0x3F] +
  2808. lookup[(tmp << 2) & 0x3F] +
  2809. '='
  2810. )
  2811. }
  2812. return parts.join('')
  2813. }
  2814. },{}],14:[function(require,module,exports){
  2815. 'use strict'
  2816. const { Buffer } = require('buffer')
  2817. const symbol = Symbol.for('BufferList')
  2818. function BufferList (buf) {
  2819. if (!(this instanceof BufferList)) {
  2820. return new BufferList(buf)
  2821. }
  2822. BufferList._init.call(this, buf)
  2823. }
  2824. BufferList._init = function _init (buf) {
  2825. Object.defineProperty(this, symbol, { value: true })
  2826. this._bufs = []
  2827. this.length = 0
  2828. if (buf) {
  2829. this.append(buf)
  2830. }
  2831. }
  2832. BufferList.prototype._new = function _new (buf) {
  2833. return new BufferList(buf)
  2834. }
  2835. BufferList.prototype._offset = function _offset (offset) {
  2836. if (offset === 0) {
  2837. return [0, 0]
  2838. }
  2839. let tot = 0
  2840. for (let i = 0; i < this._bufs.length; i++) {
  2841. const _t = tot + this._bufs[i].length
  2842. if (offset < _t || i === this._bufs.length - 1) {
  2843. return [i, offset - tot]
  2844. }
  2845. tot = _t
  2846. }
  2847. }
  2848. BufferList.prototype._reverseOffset = function (blOffset) {
  2849. const bufferId = blOffset[0]
  2850. let offset = blOffset[1]
  2851. for (let i = 0; i < bufferId; i++) {
  2852. offset += this._bufs[i].length
  2853. }
  2854. return offset
  2855. }
  2856. BufferList.prototype.get = function get (index) {
  2857. if (index > this.length || index < 0) {
  2858. return undefined
  2859. }
  2860. const offset = this._offset(index)
  2861. return this._bufs[offset[0]][offset[1]]
  2862. }
  2863. BufferList.prototype.slice = function slice (start, end) {
  2864. if (typeof start === 'number' && start < 0) {
  2865. start += this.length
  2866. }
  2867. if (typeof end === 'number' && end < 0) {
  2868. end += this.length
  2869. }
  2870. return this.copy(null, 0, start, end)
  2871. }
  2872. BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
  2873. if (typeof srcStart !== 'number' || srcStart < 0) {
  2874. srcStart = 0
  2875. }
  2876. if (typeof srcEnd !== 'number' || srcEnd > this.length) {
  2877. srcEnd = this.length
  2878. }
  2879. if (srcStart >= this.length) {
  2880. return dst || Buffer.alloc(0)
  2881. }
  2882. if (srcEnd <= 0) {
  2883. return dst || Buffer.alloc(0)
  2884. }
  2885. const copy = !!dst
  2886. const off = this._offset(srcStart)
  2887. const len = srcEnd - srcStart
  2888. let bytes = len
  2889. let bufoff = (copy && dstStart) || 0
  2890. let start = off[1]
  2891. // copy/slice everything
  2892. if (srcStart === 0 && srcEnd === this.length) {
  2893. if (!copy) {
  2894. // slice, but full concat if multiple buffers
  2895. return this._bufs.length === 1
  2896. ? this._bufs[0]
  2897. : Buffer.concat(this._bufs, this.length)
  2898. }
  2899. // copy, need to copy individual buffers
  2900. for (let i = 0; i < this._bufs.length; i++) {
  2901. this._bufs[i].copy(dst, bufoff)
  2902. bufoff += this._bufs[i].length
  2903. }
  2904. return dst
  2905. }
  2906. // easy, cheap case where it's a subset of one of the buffers
  2907. if (bytes <= this._bufs[off[0]].length - start) {
  2908. return copy
  2909. ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
  2910. : this._bufs[off[0]].slice(start, start + bytes)
  2911. }
  2912. if (!copy) {
  2913. // a slice, we need something to copy in to
  2914. dst = Buffer.allocUnsafe(len)
  2915. }
  2916. for (let i = off[0]; i < this._bufs.length; i++) {
  2917. const l = this._bufs[i].length - start
  2918. if (bytes > l) {
  2919. this._bufs[i].copy(dst, bufoff, start)
  2920. bufoff += l
  2921. } else {
  2922. this._bufs[i].copy(dst, bufoff, start, start + bytes)
  2923. bufoff += l
  2924. break
  2925. }
  2926. bytes -= l
  2927. if (start) {
  2928. start = 0
  2929. }
  2930. }
  2931. // safeguard so that we don't return uninitialized memory
  2932. if (dst.length > bufoff) return dst.slice(0, bufoff)
  2933. return dst
  2934. }
  2935. BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
  2936. start = start || 0
  2937. end = typeof end !== 'number' ? this.length : end
  2938. if (start < 0) {
  2939. start += this.length
  2940. }
  2941. if (end < 0) {
  2942. end += this.length
  2943. }
  2944. if (start === end) {
  2945. return this._new()
  2946. }
  2947. const startOffset = this._offset(start)
  2948. const endOffset = this._offset(end)
  2949. const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
  2950. if (endOffset[1] === 0) {
  2951. buffers.pop()
  2952. } else {
  2953. buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1])
  2954. }
  2955. if (startOffset[1] !== 0) {
  2956. buffers[0] = buffers[0].slice(startOffset[1])
  2957. }
  2958. return this._new(buffers)
  2959. }
  2960. BufferList.prototype.toString = function toString (encoding, start, end) {
  2961. return this.slice(start, end).toString(encoding)
  2962. }
  2963. BufferList.prototype.consume = function consume (bytes) {
  2964. // first, normalize the argument, in accordance with how Buffer does it
  2965. bytes = Math.trunc(bytes)
  2966. // do nothing if not a positive number
  2967. if (Number.isNaN(bytes) || bytes <= 0) return this
  2968. while (this._bufs.length) {
  2969. if (bytes >= this._bufs[0].length) {
  2970. bytes -= this._bufs[0].length
  2971. this.length -= this._bufs[0].length
  2972. this._bufs.shift()
  2973. } else {
  2974. this._bufs[0] = this._bufs[0].slice(bytes)
  2975. this.length -= bytes
  2976. break
  2977. }
  2978. }
  2979. return this
  2980. }
  2981. BufferList.prototype.duplicate = function duplicate () {
  2982. const copy = this._new()
  2983. for (let i = 0; i < this._bufs.length; i++) {
  2984. copy.append(this._bufs[i])
  2985. }
  2986. return copy
  2987. }
  2988. BufferList.prototype.append = function append (buf) {
  2989. if (buf == null) {
  2990. return this
  2991. }
  2992. if (buf.buffer) {
  2993. // append a view of the underlying ArrayBuffer
  2994. this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength))
  2995. } else if (Array.isArray(buf)) {
  2996. for (let i = 0; i < buf.length; i++) {
  2997. this.append(buf[i])
  2998. }
  2999. } else if (this._isBufferList(buf)) {
  3000. // unwrap argument into individual BufferLists
  3001. for (let i = 0; i < buf._bufs.length; i++) {
  3002. this.append(buf._bufs[i])
  3003. }
  3004. } else {
  3005. // coerce number arguments to strings, since Buffer(number) does
  3006. // uninitialized memory allocation
  3007. if (typeof buf === 'number') {
  3008. buf = buf.toString()
  3009. }
  3010. this._appendBuffer(Buffer.from(buf))
  3011. }
  3012. return this
  3013. }
  3014. BufferList.prototype._appendBuffer = function appendBuffer (buf) {
  3015. this._bufs.push(buf)
  3016. this.length += buf.length
  3017. }
  3018. BufferList.prototype.indexOf = function (search, offset, encoding) {
  3019. if (encoding === undefined && typeof offset === 'string') {
  3020. encoding = offset
  3021. offset = undefined
  3022. }
  3023. if (typeof search === 'function' || Array.isArray(search)) {
  3024. throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.')
  3025. } else if (typeof search === 'number') {
  3026. search = Buffer.from([search])
  3027. } else if (typeof search === 'string') {
  3028. search = Buffer.from(search, encoding)
  3029. } else if (this._isBufferList(search)) {
  3030. search = search.slice()
  3031. } else if (Array.isArray(search.buffer)) {
  3032. search = Buffer.from(search.buffer, search.byteOffset, search.byteLength)
  3033. } else if (!Buffer.isBuffer(search)) {
  3034. search = Buffer.from(search)
  3035. }
  3036. offset = Number(offset || 0)
  3037. if (isNaN(offset)) {
  3038. offset = 0
  3039. }
  3040. if (offset < 0) {
  3041. offset = this.length + offset
  3042. }
  3043. if (offset < 0) {
  3044. offset = 0
  3045. }
  3046. if (search.length === 0) {
  3047. return offset > this.length ? this.length : offset
  3048. }
  3049. const blOffset = this._offset(offset)
  3050. let blIndex = blOffset[0] // index of which internal buffer we're working on
  3051. let buffOffset = blOffset[1] // offset of the internal buffer we're working on
  3052. // scan over each buffer
  3053. for (; blIndex < this._bufs.length; blIndex++) {
  3054. const buff = this._bufs[blIndex]
  3055. while (buffOffset < buff.length) {
  3056. const availableWindow = buff.length - buffOffset
  3057. if (availableWindow >= search.length) {
  3058. const nativeSearchResult = buff.indexOf(search, buffOffset)
  3059. if (nativeSearchResult !== -1) {
  3060. return this._reverseOffset([blIndex, nativeSearchResult])
  3061. }
  3062. buffOffset = buff.length - search.length + 1 // end of native search window
  3063. } else {
  3064. const revOffset = this._reverseOffset([blIndex, buffOffset])
  3065. if (this._match(revOffset, search)) {
  3066. return revOffset
  3067. }
  3068. buffOffset++
  3069. }
  3070. }
  3071. buffOffset = 0
  3072. }
  3073. return -1
  3074. }
  3075. BufferList.prototype._match = function (offset, search) {
  3076. if (this.length - offset < search.length) {
  3077. return false
  3078. }
  3079. for (let searchOffset = 0; searchOffset < search.length; searchOffset++) {
  3080. if (this.get(offset + searchOffset) !== search[searchOffset]) {
  3081. return false
  3082. }
  3083. }
  3084. return true
  3085. }
  3086. ;(function () {
  3087. const methods = {
  3088. readDoubleBE: 8,
  3089. readDoubleLE: 8,
  3090. readFloatBE: 4,
  3091. readFloatLE: 4,
  3092. readInt32BE: 4,
  3093. readInt32LE: 4,
  3094. readUInt32BE: 4,
  3095. readUInt32LE: 4,
  3096. readInt16BE: 2,
  3097. readInt16LE: 2,
  3098. readUInt16BE: 2,
  3099. readUInt16LE: 2,
  3100. readInt8: 1,
  3101. readUInt8: 1,
  3102. readIntBE: null,
  3103. readIntLE: null,
  3104. readUIntBE: null,
  3105. readUIntLE: null
  3106. }
  3107. for (const m in methods) {
  3108. (function (m) {
  3109. if (methods[m] === null) {
  3110. BufferList.prototype[m] = function (offset, byteLength) {
  3111. return this.slice(offset, offset + byteLength)[m](0, byteLength)
  3112. }
  3113. } else {
  3114. BufferList.prototype[m] = function (offset = 0) {
  3115. return this.slice(offset, offset + methods[m])[m](0)
  3116. }
  3117. }
  3118. }(m))
  3119. }
  3120. }())
  3121. // Used internally by the class and also as an indicator of this object being
  3122. // a `BufferList`. It's not possible to use `instanceof BufferList` in a browser
  3123. // environment because there could be multiple different copies of the
  3124. // BufferList class and some `BufferList`s might be `BufferList`s.
  3125. BufferList.prototype._isBufferList = function _isBufferList (b) {
  3126. return b instanceof BufferList || BufferList.isBufferList(b)
  3127. }
  3128. BufferList.isBufferList = function isBufferList (b) {
  3129. return b != null && b[symbol]
  3130. }
  3131. module.exports = BufferList
  3132. },{"buffer":17}],15:[function(require,module,exports){
  3133. 'use strict'
  3134. const DuplexStream = require('readable-stream').Duplex
  3135. const inherits = require('inherits')
  3136. const BufferList = require('./BufferList')
  3137. function BufferListStream (callback) {
  3138. if (!(this instanceof BufferListStream)) {
  3139. return new BufferListStream(callback)
  3140. }
  3141. if (typeof callback === 'function') {
  3142. this._callback = callback
  3143. const piper = function piper (err) {
  3144. if (this._callback) {
  3145. this._callback(err)
  3146. this._callback = null
  3147. }
  3148. }.bind(this)
  3149. this.on('pipe', function onPipe (src) {
  3150. src.on('error', piper)
  3151. })
  3152. this.on('unpipe', function onUnpipe (src) {
  3153. src.removeListener('error', piper)
  3154. })
  3155. callback = null
  3156. }
  3157. BufferList._init.call(this, callback)
  3158. DuplexStream.call(this)
  3159. }
  3160. inherits(BufferListStream, DuplexStream)
  3161. Object.assign(BufferListStream.prototype, BufferList.prototype)
  3162. BufferListStream.prototype._new = function _new (callback) {
  3163. return new BufferListStream(callback)
  3164. }
  3165. BufferListStream.prototype._write = function _write (buf, encoding, callback) {
  3166. this._appendBuffer(buf)
  3167. if (typeof callback === 'function') {
  3168. callback()
  3169. }
  3170. }
  3171. BufferListStream.prototype._read = function _read (size) {
  3172. if (!this.length) {
  3173. return this.push(null)
  3174. }
  3175. size = Math.min(size, this.length)
  3176. this.push(this.slice(0, size))
  3177. this.consume(size)
  3178. }
  3179. BufferListStream.prototype.end = function end (chunk) {
  3180. DuplexStream.prototype.end.call(this, chunk)
  3181. if (this._callback) {
  3182. this._callback(null, this.slice())
  3183. this._callback = null
  3184. }
  3185. }
  3186. BufferListStream.prototype._destroy = function _destroy (err, cb) {
  3187. this._bufs.length = 0
  3188. this.length = 0
  3189. cb(err)
  3190. }
  3191. BufferListStream.prototype._isBufferList = function _isBufferList (b) {
  3192. return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b)
  3193. }
  3194. BufferListStream.isBufferList = BufferList.isBufferList
  3195. module.exports = BufferListStream
  3196. module.exports.BufferListStream = BufferListStream
  3197. module.exports.BufferList = BufferList
  3198. },{"./BufferList":14,"inherits":24,"readable-stream":69}],16:[function(require,module,exports){
  3199. },{}],17:[function(require,module,exports){
  3200. (function (Buffer){(function (){
  3201. /*!
  3202. * The buffer module from node.js, for the browser.
  3203. *
  3204. * @author Feross Aboukhadijeh <https://feross.org>
  3205. * @license MIT
  3206. */
  3207. /* eslint-disable no-proto */
  3208. 'use strict'
  3209. var base64 = require('base64-js')
  3210. var ieee754 = require('ieee754')
  3211. exports.Buffer = Buffer
  3212. exports.SlowBuffer = SlowBuffer
  3213. exports.INSPECT_MAX_BYTES = 50
  3214. var K_MAX_LENGTH = 0x7fffffff
  3215. exports.kMaxLength = K_MAX_LENGTH
  3216. /**
  3217. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  3218. * === true Use Uint8Array implementation (fastest)
  3219. * === false Print warning and recommend using `buffer` v4.x which has an Object
  3220. * implementation (most compatible, even IE6)
  3221. *
  3222. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  3223. * Opera 11.6+, iOS 4.2+.
  3224. *
  3225. * We report that the browser does not support typed arrays if the are not subclassable
  3226. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  3227. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  3228. * for __proto__ and has a buggy typed array implementation.
  3229. */
  3230. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  3231. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  3232. typeof console.error === 'function') {
  3233. console.error(
  3234. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  3235. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  3236. )
  3237. }
  3238. function typedArraySupport () {
  3239. // Can typed array instances can be augmented?
  3240. try {
  3241. var arr = new Uint8Array(1)
  3242. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  3243. return arr.foo() === 42
  3244. } catch (e) {
  3245. return false
  3246. }
  3247. }
  3248. Object.defineProperty(Buffer.prototype, 'parent', {
  3249. enumerable: true,
  3250. get: function () {
  3251. if (!Buffer.isBuffer(this)) return undefined
  3252. return this.buffer
  3253. }
  3254. })
  3255. Object.defineProperty(Buffer.prototype, 'offset', {
  3256. enumerable: true,
  3257. get: function () {
  3258. if (!Buffer.isBuffer(this)) return undefined
  3259. return this.byteOffset
  3260. }
  3261. })
  3262. function createBuffer (length) {
  3263. if (length > K_MAX_LENGTH) {
  3264. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  3265. }
  3266. // Return an augmented `Uint8Array` instance
  3267. var buf = new Uint8Array(length)
  3268. buf.__proto__ = Buffer.prototype
  3269. return buf
  3270. }
  3271. /**
  3272. * The Buffer constructor returns instances of `Uint8Array` that have their
  3273. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  3274. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  3275. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  3276. * returns a single octet.
  3277. *
  3278. * The `Uint8Array` prototype remains unmodified.
  3279. */
  3280. function Buffer (arg, encodingOrOffset, length) {
  3281. // Common case.
  3282. if (typeof arg === 'number') {
  3283. if (typeof encodingOrOffset === 'string') {
  3284. throw new TypeError(
  3285. 'The "string" argument must be of type string. Received type number'
  3286. )
  3287. }
  3288. return allocUnsafe(arg)
  3289. }
  3290. return from(arg, encodingOrOffset, length)
  3291. }
  3292. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  3293. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  3294. Buffer[Symbol.species] === Buffer) {
  3295. Object.defineProperty(Buffer, Symbol.species, {
  3296. value: null,
  3297. configurable: true,
  3298. enumerable: false,
  3299. writable: false
  3300. })
  3301. }
  3302. Buffer.poolSize = 8192 // not used by this implementation
  3303. function from (value, encodingOrOffset, length) {
  3304. if (typeof value === 'string') {
  3305. return fromString(value, encodingOrOffset)
  3306. }
  3307. if (ArrayBuffer.isView(value)) {
  3308. return fromArrayLike(value)
  3309. }
  3310. if (value == null) {
  3311. throw TypeError(
  3312. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  3313. 'or Array-like Object. Received type ' + (typeof value)
  3314. )
  3315. }
  3316. if (isInstance(value, ArrayBuffer) ||
  3317. (value && isInstance(value.buffer, ArrayBuffer))) {
  3318. return fromArrayBuffer(value, encodingOrOffset, length)
  3319. }
  3320. if (typeof value === 'number') {
  3321. throw new TypeError(
  3322. 'The "value" argument must not be of type number. Received type number'
  3323. )
  3324. }
  3325. var valueOf = value.valueOf && value.valueOf()
  3326. if (valueOf != null && valueOf !== value) {
  3327. return Buffer.from(valueOf, encodingOrOffset, length)
  3328. }
  3329. var b = fromObject(value)
  3330. if (b) return b
  3331. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  3332. typeof value[Symbol.toPrimitive] === 'function') {
  3333. return Buffer.from(
  3334. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  3335. )
  3336. }
  3337. throw new TypeError(
  3338. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  3339. 'or Array-like Object. Received type ' + (typeof value)
  3340. )
  3341. }
  3342. /**
  3343. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  3344. * if value is a number.
  3345. * Buffer.from(str[, encoding])
  3346. * Buffer.from(array)
  3347. * Buffer.from(buffer)
  3348. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  3349. **/
  3350. Buffer.from = function (value, encodingOrOffset, length) {
  3351. return from(value, encodingOrOffset, length)
  3352. }
  3353. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  3354. // https://github.com/feross/buffer/pull/148
  3355. Buffer.prototype.__proto__ = Uint8Array.prototype
  3356. Buffer.__proto__ = Uint8Array
  3357. function assertSize (size) {
  3358. if (typeof size !== 'number') {
  3359. throw new TypeError('"size" argument must be of type number')
  3360. } else if (size < 0) {
  3361. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  3362. }
  3363. }
  3364. function alloc (size, fill, encoding) {
  3365. assertSize(size)
  3366. if (size <= 0) {
  3367. return createBuffer(size)
  3368. }
  3369. if (fill !== undefined) {
  3370. // Only pay attention to encoding if it's a string. This
  3371. // prevents accidentally sending in a number that would
  3372. // be interpretted as a start offset.
  3373. return typeof encoding === 'string'
  3374. ? createBuffer(size).fill(fill, encoding)
  3375. : createBuffer(size).fill(fill)
  3376. }
  3377. return createBuffer(size)
  3378. }
  3379. /**
  3380. * Creates a new filled Buffer instance.
  3381. * alloc(size[, fill[, encoding]])
  3382. **/
  3383. Buffer.alloc = function (size, fill, encoding) {
  3384. return alloc(size, fill, encoding)
  3385. }
  3386. function allocUnsafe (size) {
  3387. assertSize(size)
  3388. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  3389. }
  3390. /**
  3391. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  3392. * */
  3393. Buffer.allocUnsafe = function (size) {
  3394. return allocUnsafe(size)
  3395. }
  3396. /**
  3397. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  3398. */
  3399. Buffer.allocUnsafeSlow = function (size) {
  3400. return allocUnsafe(size)
  3401. }
  3402. function fromString (string, encoding) {
  3403. if (typeof encoding !== 'string' || encoding === '') {
  3404. encoding = 'utf8'
  3405. }
  3406. if (!Buffer.isEncoding(encoding)) {
  3407. throw new TypeError('Unknown encoding: ' + encoding)
  3408. }
  3409. var length = byteLength(string, encoding) | 0
  3410. var buf = createBuffer(length)
  3411. var actual = buf.write(string, encoding)
  3412. if (actual !== length) {
  3413. // Writing a hex string, for example, that contains invalid characters will
  3414. // cause everything after the first invalid character to be ignored. (e.g.
  3415. // 'abxxcd' will be treated as 'ab')
  3416. buf = buf.slice(0, actual)
  3417. }
  3418. return buf
  3419. }
  3420. function fromArrayLike (array) {
  3421. var length = array.length < 0 ? 0 : checked(array.length) | 0
  3422. var buf = createBuffer(length)
  3423. for (var i = 0; i < length; i += 1) {
  3424. buf[i] = array[i] & 255
  3425. }
  3426. return buf
  3427. }
  3428. function fromArrayBuffer (array, byteOffset, length) {
  3429. if (byteOffset < 0 || array.byteLength < byteOffset) {
  3430. throw new RangeError('"offset" is outside of buffer bounds')
  3431. }
  3432. if (array.byteLength < byteOffset + (length || 0)) {
  3433. throw new RangeError('"length" is outside of buffer bounds')
  3434. }
  3435. var buf
  3436. if (byteOffset === undefined && length === undefined) {
  3437. buf = new Uint8Array(array)
  3438. } else if (length === undefined) {
  3439. buf = new Uint8Array(array, byteOffset)
  3440. } else {
  3441. buf = new Uint8Array(array, byteOffset, length)
  3442. }
  3443. // Return an augmented `Uint8Array` instance
  3444. buf.__proto__ = Buffer.prototype
  3445. return buf
  3446. }
  3447. function fromObject (obj) {
  3448. if (Buffer.isBuffer(obj)) {
  3449. var len = checked(obj.length) | 0
  3450. var buf = createBuffer(len)
  3451. if (buf.length === 0) {
  3452. return buf
  3453. }
  3454. obj.copy(buf, 0, 0, len)
  3455. return buf
  3456. }
  3457. if (obj.length !== undefined) {
  3458. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  3459. return createBuffer(0)
  3460. }
  3461. return fromArrayLike(obj)
  3462. }
  3463. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  3464. return fromArrayLike(obj.data)
  3465. }
  3466. }
  3467. function checked (length) {
  3468. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  3469. // length is NaN (which is otherwise coerced to zero.)
  3470. if (length >= K_MAX_LENGTH) {
  3471. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  3472. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  3473. }
  3474. return length | 0
  3475. }
  3476. function SlowBuffer (length) {
  3477. if (+length != length) { // eslint-disable-line eqeqeq
  3478. length = 0
  3479. }
  3480. return Buffer.alloc(+length)
  3481. }
  3482. Buffer.isBuffer = function isBuffer (b) {
  3483. return b != null && b._isBuffer === true &&
  3484. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  3485. }
  3486. Buffer.compare = function compare (a, b) {
  3487. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  3488. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  3489. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  3490. throw new TypeError(
  3491. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  3492. )
  3493. }
  3494. if (a === b) return 0
  3495. var x = a.length
  3496. var y = b.length
  3497. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  3498. if (a[i] !== b[i]) {
  3499. x = a[i]
  3500. y = b[i]
  3501. break
  3502. }
  3503. }
  3504. if (x < y) return -1
  3505. if (y < x) return 1
  3506. return 0
  3507. }
  3508. Buffer.isEncoding = function isEncoding (encoding) {
  3509. switch (String(encoding).toLowerCase()) {
  3510. case 'hex':
  3511. case 'utf8':
  3512. case 'utf-8':
  3513. case 'ascii':
  3514. case 'latin1':
  3515. case 'binary':
  3516. case 'base64':
  3517. case 'ucs2':
  3518. case 'ucs-2':
  3519. case 'utf16le':
  3520. case 'utf-16le':
  3521. return true
  3522. default:
  3523. return false
  3524. }
  3525. }
  3526. Buffer.concat = function concat (list, length) {
  3527. if (!Array.isArray(list)) {
  3528. throw new TypeError('"list" argument must be an Array of Buffers')
  3529. }
  3530. if (list.length === 0) {
  3531. return Buffer.alloc(0)
  3532. }
  3533. var i
  3534. if (length === undefined) {
  3535. length = 0
  3536. for (i = 0; i < list.length; ++i) {
  3537. length += list[i].length
  3538. }
  3539. }
  3540. var buffer = Buffer.allocUnsafe(length)
  3541. var pos = 0
  3542. for (i = 0; i < list.length; ++i) {
  3543. var buf = list[i]
  3544. if (isInstance(buf, Uint8Array)) {
  3545. buf = Buffer.from(buf)
  3546. }
  3547. if (!Buffer.isBuffer(buf)) {
  3548. throw new TypeError('"list" argument must be an Array of Buffers')
  3549. }
  3550. buf.copy(buffer, pos)
  3551. pos += buf.length
  3552. }
  3553. return buffer
  3554. }
  3555. function byteLength (string, encoding) {
  3556. if (Buffer.isBuffer(string)) {
  3557. return string.length
  3558. }
  3559. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  3560. return string.byteLength
  3561. }
  3562. if (typeof string !== 'string') {
  3563. throw new TypeError(
  3564. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  3565. 'Received type ' + typeof string
  3566. )
  3567. }
  3568. var len = string.length
  3569. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  3570. if (!mustMatch && len === 0) return 0
  3571. // Use a for loop to avoid recursion
  3572. var loweredCase = false
  3573. for (;;) {
  3574. switch (encoding) {
  3575. case 'ascii':
  3576. case 'latin1':
  3577. case 'binary':
  3578. return len
  3579. case 'utf8':
  3580. case 'utf-8':
  3581. return utf8ToBytes(string).length
  3582. case 'ucs2':
  3583. case 'ucs-2':
  3584. case 'utf16le':
  3585. case 'utf-16le':
  3586. return len * 2
  3587. case 'hex':
  3588. return len >>> 1
  3589. case 'base64':
  3590. return base64ToBytes(string).length
  3591. default:
  3592. if (loweredCase) {
  3593. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  3594. }
  3595. encoding = ('' + encoding).toLowerCase()
  3596. loweredCase = true
  3597. }
  3598. }
  3599. }
  3600. Buffer.byteLength = byteLength
  3601. function slowToString (encoding, start, end) {
  3602. var loweredCase = false
  3603. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  3604. // property of a typed array.
  3605. // This behaves neither like String nor Uint8Array in that we set start/end
  3606. // to their upper/lower bounds if the value passed is out of range.
  3607. // undefined is handled specially as per ECMA-262 6th Edition,
  3608. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  3609. if (start === undefined || start < 0) {
  3610. start = 0
  3611. }
  3612. // Return early if start > this.length. Done here to prevent potential uint32
  3613. // coercion fail below.
  3614. if (start > this.length) {
  3615. return ''
  3616. }
  3617. if (end === undefined || end > this.length) {
  3618. end = this.length
  3619. }
  3620. if (end <= 0) {
  3621. return ''
  3622. }
  3623. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  3624. end >>>= 0
  3625. start >>>= 0
  3626. if (end <= start) {
  3627. return ''
  3628. }
  3629. if (!encoding) encoding = 'utf8'
  3630. while (true) {
  3631. switch (encoding) {
  3632. case 'hex':
  3633. return hexSlice(this, start, end)
  3634. case 'utf8':
  3635. case 'utf-8':
  3636. return utf8Slice(this, start, end)
  3637. case 'ascii':
  3638. return asciiSlice(this, start, end)
  3639. case 'latin1':
  3640. case 'binary':
  3641. return latin1Slice(this, start, end)
  3642. case 'base64':
  3643. return base64Slice(this, start, end)
  3644. case 'ucs2':
  3645. case 'ucs-2':
  3646. case 'utf16le':
  3647. case 'utf-16le':
  3648. return utf16leSlice(this, start, end)
  3649. default:
  3650. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3651. encoding = (encoding + '').toLowerCase()
  3652. loweredCase = true
  3653. }
  3654. }
  3655. }
  3656. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  3657. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  3658. // reliably in a browserify context because there could be multiple different
  3659. // copies of the 'buffer' package in use. This method works even for Buffer
  3660. // instances that were created from another copy of the `buffer` package.
  3661. // See: https://github.com/feross/buffer/issues/154
  3662. Buffer.prototype._isBuffer = true
  3663. function swap (b, n, m) {
  3664. var i = b[n]
  3665. b[n] = b[m]
  3666. b[m] = i
  3667. }
  3668. Buffer.prototype.swap16 = function swap16 () {
  3669. var len = this.length
  3670. if (len % 2 !== 0) {
  3671. throw new RangeError('Buffer size must be a multiple of 16-bits')
  3672. }
  3673. for (var i = 0; i < len; i += 2) {
  3674. swap(this, i, i + 1)
  3675. }
  3676. return this
  3677. }
  3678. Buffer.prototype.swap32 = function swap32 () {
  3679. var len = this.length
  3680. if (len % 4 !== 0) {
  3681. throw new RangeError('Buffer size must be a multiple of 32-bits')
  3682. }
  3683. for (var i = 0; i < len; i += 4) {
  3684. swap(this, i, i + 3)
  3685. swap(this, i + 1, i + 2)
  3686. }
  3687. return this
  3688. }
  3689. Buffer.prototype.swap64 = function swap64 () {
  3690. var len = this.length
  3691. if (len % 8 !== 0) {
  3692. throw new RangeError('Buffer size must be a multiple of 64-bits')
  3693. }
  3694. for (var i = 0; i < len; i += 8) {
  3695. swap(this, i, i + 7)
  3696. swap(this, i + 1, i + 6)
  3697. swap(this, i + 2, i + 5)
  3698. swap(this, i + 3, i + 4)
  3699. }
  3700. return this
  3701. }
  3702. Buffer.prototype.toString = function toString () {
  3703. var length = this.length
  3704. if (length === 0) return ''
  3705. if (arguments.length === 0) return utf8Slice(this, 0, length)
  3706. return slowToString.apply(this, arguments)
  3707. }
  3708. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  3709. Buffer.prototype.equals = function equals (b) {
  3710. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  3711. if (this === b) return true
  3712. return Buffer.compare(this, b) === 0
  3713. }
  3714. Buffer.prototype.inspect = function inspect () {
  3715. var str = ''
  3716. var max = exports.INSPECT_MAX_BYTES
  3717. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  3718. if (this.length > max) str += ' ... '
  3719. return '<Buffer ' + str + '>'
  3720. }
  3721. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  3722. if (isInstance(target, Uint8Array)) {
  3723. target = Buffer.from(target, target.offset, target.byteLength)
  3724. }
  3725. if (!Buffer.isBuffer(target)) {
  3726. throw new TypeError(
  3727. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  3728. 'Received type ' + (typeof target)
  3729. )
  3730. }
  3731. if (start === undefined) {
  3732. start = 0
  3733. }
  3734. if (end === undefined) {
  3735. end = target ? target.length : 0
  3736. }
  3737. if (thisStart === undefined) {
  3738. thisStart = 0
  3739. }
  3740. if (thisEnd === undefined) {
  3741. thisEnd = this.length
  3742. }
  3743. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  3744. throw new RangeError('out of range index')
  3745. }
  3746. if (thisStart >= thisEnd && start >= end) {
  3747. return 0
  3748. }
  3749. if (thisStart >= thisEnd) {
  3750. return -1
  3751. }
  3752. if (start >= end) {
  3753. return 1
  3754. }
  3755. start >>>= 0
  3756. end >>>= 0
  3757. thisStart >>>= 0
  3758. thisEnd >>>= 0
  3759. if (this === target) return 0
  3760. var x = thisEnd - thisStart
  3761. var y = end - start
  3762. var len = Math.min(x, y)
  3763. var thisCopy = this.slice(thisStart, thisEnd)
  3764. var targetCopy = target.slice(start, end)
  3765. for (var i = 0; i < len; ++i) {
  3766. if (thisCopy[i] !== targetCopy[i]) {
  3767. x = thisCopy[i]
  3768. y = targetCopy[i]
  3769. break
  3770. }
  3771. }
  3772. if (x < y) return -1
  3773. if (y < x) return 1
  3774. return 0
  3775. }
  3776. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  3777. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  3778. //
  3779. // Arguments:
  3780. // - buffer - a Buffer to search
  3781. // - val - a string, Buffer, or number
  3782. // - byteOffset - an index into `buffer`; will be clamped to an int32
  3783. // - encoding - an optional encoding, relevant is val is a string
  3784. // - dir - true for indexOf, false for lastIndexOf
  3785. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  3786. // Empty buffer means no match
  3787. if (buffer.length === 0) return -1
  3788. // Normalize byteOffset
  3789. if (typeof byteOffset === 'string') {
  3790. encoding = byteOffset
  3791. byteOffset = 0
  3792. } else if (byteOffset > 0x7fffffff) {
  3793. byteOffset = 0x7fffffff
  3794. } else if (byteOffset < -0x80000000) {
  3795. byteOffset = -0x80000000
  3796. }
  3797. byteOffset = +byteOffset // Coerce to Number.
  3798. if (numberIsNaN(byteOffset)) {
  3799. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  3800. byteOffset = dir ? 0 : (buffer.length - 1)
  3801. }
  3802. // Normalize byteOffset: negative offsets start from the end of the buffer
  3803. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  3804. if (byteOffset >= buffer.length) {
  3805. if (dir) return -1
  3806. else byteOffset = buffer.length - 1
  3807. } else if (byteOffset < 0) {
  3808. if (dir) byteOffset = 0
  3809. else return -1
  3810. }
  3811. // Normalize val
  3812. if (typeof val === 'string') {
  3813. val = Buffer.from(val, encoding)
  3814. }
  3815. // Finally, search either indexOf (if dir is true) or lastIndexOf
  3816. if (Buffer.isBuffer(val)) {
  3817. // Special case: looking for empty string/buffer always fails
  3818. if (val.length === 0) {
  3819. return -1
  3820. }
  3821. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  3822. } else if (typeof val === 'number') {
  3823. val = val & 0xFF // Search for a byte value [0-255]
  3824. if (typeof Uint8Array.prototype.indexOf === 'function') {
  3825. if (dir) {
  3826. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  3827. } else {
  3828. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  3829. }
  3830. }
  3831. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  3832. }
  3833. throw new TypeError('val must be string, number or Buffer')
  3834. }
  3835. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  3836. var indexSize = 1
  3837. var arrLength = arr.length
  3838. var valLength = val.length
  3839. if (encoding !== undefined) {
  3840. encoding = String(encoding).toLowerCase()
  3841. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  3842. encoding === 'utf16le' || encoding === 'utf-16le') {
  3843. if (arr.length < 2 || val.length < 2) {
  3844. return -1
  3845. }
  3846. indexSize = 2
  3847. arrLength /= 2
  3848. valLength /= 2
  3849. byteOffset /= 2
  3850. }
  3851. }
  3852. function read (buf, i) {
  3853. if (indexSize === 1) {
  3854. return buf[i]
  3855. } else {
  3856. return buf.readUInt16BE(i * indexSize)
  3857. }
  3858. }
  3859. var i
  3860. if (dir) {
  3861. var foundIndex = -1
  3862. for (i = byteOffset; i < arrLength; i++) {
  3863. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  3864. if (foundIndex === -1) foundIndex = i
  3865. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  3866. } else {
  3867. if (foundIndex !== -1) i -= i - foundIndex
  3868. foundIndex = -1
  3869. }
  3870. }
  3871. } else {
  3872. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  3873. for (i = byteOffset; i >= 0; i--) {
  3874. var found = true
  3875. for (var j = 0; j < valLength; j++) {
  3876. if (read(arr, i + j) !== read(val, j)) {
  3877. found = false
  3878. break
  3879. }
  3880. }
  3881. if (found) return i
  3882. }
  3883. }
  3884. return -1
  3885. }
  3886. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  3887. return this.indexOf(val, byteOffset, encoding) !== -1
  3888. }
  3889. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  3890. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  3891. }
  3892. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  3893. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  3894. }
  3895. function hexWrite (buf, string, offset, length) {
  3896. offset = Number(offset) || 0
  3897. var remaining = buf.length - offset
  3898. if (!length) {
  3899. length = remaining
  3900. } else {
  3901. length = Number(length)
  3902. if (length > remaining) {
  3903. length = remaining
  3904. }
  3905. }
  3906. var strLen = string.length
  3907. if (length > strLen / 2) {
  3908. length = strLen / 2
  3909. }
  3910. for (var i = 0; i < length; ++i) {
  3911. var parsed = parseInt(string.substr(i * 2, 2), 16)
  3912. if (numberIsNaN(parsed)) return i
  3913. buf[offset + i] = parsed
  3914. }
  3915. return i
  3916. }
  3917. function utf8Write (buf, string, offset, length) {
  3918. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  3919. }
  3920. function asciiWrite (buf, string, offset, length) {
  3921. return blitBuffer(asciiToBytes(string), buf, offset, length)
  3922. }
  3923. function latin1Write (buf, string, offset, length) {
  3924. return asciiWrite(buf, string, offset, length)
  3925. }
  3926. function base64Write (buf, string, offset, length) {
  3927. return blitBuffer(base64ToBytes(string), buf, offset, length)
  3928. }
  3929. function ucs2Write (buf, string, offset, length) {
  3930. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  3931. }
  3932. Buffer.prototype.write = function write (string, offset, length, encoding) {
  3933. // Buffer#write(string)
  3934. if (offset === undefined) {
  3935. encoding = 'utf8'
  3936. length = this.length
  3937. offset = 0
  3938. // Buffer#write(string, encoding)
  3939. } else if (length === undefined && typeof offset === 'string') {
  3940. encoding = offset
  3941. length = this.length
  3942. offset = 0
  3943. // Buffer#write(string, offset[, length][, encoding])
  3944. } else if (isFinite(offset)) {
  3945. offset = offset >>> 0
  3946. if (isFinite(length)) {
  3947. length = length >>> 0
  3948. if (encoding === undefined) encoding = 'utf8'
  3949. } else {
  3950. encoding = length
  3951. length = undefined
  3952. }
  3953. } else {
  3954. throw new Error(
  3955. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  3956. )
  3957. }
  3958. var remaining = this.length - offset
  3959. if (length === undefined || length > remaining) length = remaining
  3960. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  3961. throw new RangeError('Attempt to write outside buffer bounds')
  3962. }
  3963. if (!encoding) encoding = 'utf8'
  3964. var loweredCase = false
  3965. for (;;) {
  3966. switch (encoding) {
  3967. case 'hex':
  3968. return hexWrite(this, string, offset, length)
  3969. case 'utf8':
  3970. case 'utf-8':
  3971. return utf8Write(this, string, offset, length)
  3972. case 'ascii':
  3973. return asciiWrite(this, string, offset, length)
  3974. case 'latin1':
  3975. case 'binary':
  3976. return latin1Write(this, string, offset, length)
  3977. case 'base64':
  3978. // Warning: maxLength not taken into account in base64Write
  3979. return base64Write(this, string, offset, length)
  3980. case 'ucs2':
  3981. case 'ucs-2':
  3982. case 'utf16le':
  3983. case 'utf-16le':
  3984. return ucs2Write(this, string, offset, length)
  3985. default:
  3986. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3987. encoding = ('' + encoding).toLowerCase()
  3988. loweredCase = true
  3989. }
  3990. }
  3991. }
  3992. Buffer.prototype.toJSON = function toJSON () {
  3993. return {
  3994. type: 'Buffer',
  3995. data: Array.prototype.slice.call(this._arr || this, 0)
  3996. }
  3997. }
  3998. function base64Slice (buf, start, end) {
  3999. if (start === 0 && end === buf.length) {
  4000. return base64.fromByteArray(buf)
  4001. } else {
  4002. return base64.fromByteArray(buf.slice(start, end))
  4003. }
  4004. }
  4005. function utf8Slice (buf, start, end) {
  4006. end = Math.min(buf.length, end)
  4007. var res = []
  4008. var i = start
  4009. while (i < end) {
  4010. var firstByte = buf[i]
  4011. var codePoint = null
  4012. var bytesPerSequence = (firstByte > 0xEF) ? 4
  4013. : (firstByte > 0xDF) ? 3
  4014. : (firstByte > 0xBF) ? 2
  4015. : 1
  4016. if (i + bytesPerSequence <= end) {
  4017. var secondByte, thirdByte, fourthByte, tempCodePoint
  4018. switch (bytesPerSequence) {
  4019. case 1:
  4020. if (firstByte < 0x80) {
  4021. codePoint = firstByte
  4022. }
  4023. break
  4024. case 2:
  4025. secondByte = buf[i + 1]
  4026. if ((secondByte & 0xC0) === 0x80) {
  4027. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  4028. if (tempCodePoint > 0x7F) {
  4029. codePoint = tempCodePoint
  4030. }
  4031. }
  4032. break
  4033. case 3:
  4034. secondByte = buf[i + 1]
  4035. thirdByte = buf[i + 2]
  4036. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  4037. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  4038. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  4039. codePoint = tempCodePoint
  4040. }
  4041. }
  4042. break
  4043. case 4:
  4044. secondByte = buf[i + 1]
  4045. thirdByte = buf[i + 2]
  4046. fourthByte = buf[i + 3]
  4047. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  4048. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  4049. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  4050. codePoint = tempCodePoint
  4051. }
  4052. }
  4053. }
  4054. }
  4055. if (codePoint === null) {
  4056. // we did not generate a valid codePoint so insert a
  4057. // replacement char (U+FFFD) and advance only 1 byte
  4058. codePoint = 0xFFFD
  4059. bytesPerSequence = 1
  4060. } else if (codePoint > 0xFFFF) {
  4061. // encode to utf16 (surrogate pair dance)
  4062. codePoint -= 0x10000
  4063. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  4064. codePoint = 0xDC00 | codePoint & 0x3FF
  4065. }
  4066. res.push(codePoint)
  4067. i += bytesPerSequence
  4068. }
  4069. return decodeCodePointsArray(res)
  4070. }
  4071. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  4072. // the lowest limit is Chrome, with 0x10000 args.
  4073. // We go 1 magnitude less, for safety
  4074. var MAX_ARGUMENTS_LENGTH = 0x1000
  4075. function decodeCodePointsArray (codePoints) {
  4076. var len = codePoints.length
  4077. if (len <= MAX_ARGUMENTS_LENGTH) {
  4078. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  4079. }
  4080. // Decode in chunks to avoid "call stack size exceeded".
  4081. var res = ''
  4082. var i = 0
  4083. while (i < len) {
  4084. res += String.fromCharCode.apply(
  4085. String,
  4086. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  4087. )
  4088. }
  4089. return res
  4090. }
  4091. function asciiSlice (buf, start, end) {
  4092. var ret = ''
  4093. end = Math.min(buf.length, end)
  4094. for (var i = start; i < end; ++i) {
  4095. ret += String.fromCharCode(buf[i] & 0x7F)
  4096. }
  4097. return ret
  4098. }
  4099. function latin1Slice (buf, start, end) {
  4100. var ret = ''
  4101. end = Math.min(buf.length, end)
  4102. for (var i = start; i < end; ++i) {
  4103. ret += String.fromCharCode(buf[i])
  4104. }
  4105. return ret
  4106. }
  4107. function hexSlice (buf, start, end) {
  4108. var len = buf.length
  4109. if (!start || start < 0) start = 0
  4110. if (!end || end < 0 || end > len) end = len
  4111. var out = ''
  4112. for (var i = start; i < end; ++i) {
  4113. out += toHex(buf[i])
  4114. }
  4115. return out
  4116. }
  4117. function utf16leSlice (buf, start, end) {
  4118. var bytes = buf.slice(start, end)
  4119. var res = ''
  4120. for (var i = 0; i < bytes.length; i += 2) {
  4121. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  4122. }
  4123. return res
  4124. }
  4125. Buffer.prototype.slice = function slice (start, end) {
  4126. var len = this.length
  4127. start = ~~start
  4128. end = end === undefined ? len : ~~end
  4129. if (start < 0) {
  4130. start += len
  4131. if (start < 0) start = 0
  4132. } else if (start > len) {
  4133. start = len
  4134. }
  4135. if (end < 0) {
  4136. end += len
  4137. if (end < 0) end = 0
  4138. } else if (end > len) {
  4139. end = len
  4140. }
  4141. if (end < start) end = start
  4142. var newBuf = this.subarray(start, end)
  4143. // Return an augmented `Uint8Array` instance
  4144. newBuf.__proto__ = Buffer.prototype
  4145. return newBuf
  4146. }
  4147. /*
  4148. * Need to make sure that buffer isn't trying to write out of bounds.
  4149. */
  4150. function checkOffset (offset, ext, length) {
  4151. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  4152. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  4153. }
  4154. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  4155. offset = offset >>> 0
  4156. byteLength = byteLength >>> 0
  4157. if (!noAssert) checkOffset(offset, byteLength, this.length)
  4158. var val = this[offset]
  4159. var mul = 1
  4160. var i = 0
  4161. while (++i < byteLength && (mul *= 0x100)) {
  4162. val += this[offset + i] * mul
  4163. }
  4164. return val
  4165. }
  4166. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  4167. offset = offset >>> 0
  4168. byteLength = byteLength >>> 0
  4169. if (!noAssert) {
  4170. checkOffset(offset, byteLength, this.length)
  4171. }
  4172. var val = this[offset + --byteLength]
  4173. var mul = 1
  4174. while (byteLength > 0 && (mul *= 0x100)) {
  4175. val += this[offset + --byteLength] * mul
  4176. }
  4177. return val
  4178. }
  4179. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  4180. offset = offset >>> 0
  4181. if (!noAssert) checkOffset(offset, 1, this.length)
  4182. return this[offset]
  4183. }
  4184. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  4185. offset = offset >>> 0
  4186. if (!noAssert) checkOffset(offset, 2, this.length)
  4187. return this[offset] | (this[offset + 1] << 8)
  4188. }
  4189. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  4190. offset = offset >>> 0
  4191. if (!noAssert) checkOffset(offset, 2, this.length)
  4192. return (this[offset] << 8) | this[offset + 1]
  4193. }
  4194. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  4195. offset = offset >>> 0
  4196. if (!noAssert) checkOffset(offset, 4, this.length)
  4197. return ((this[offset]) |
  4198. (this[offset + 1] << 8) |
  4199. (this[offset + 2] << 16)) +
  4200. (this[offset + 3] * 0x1000000)
  4201. }
  4202. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  4203. offset = offset >>> 0
  4204. if (!noAssert) checkOffset(offset, 4, this.length)
  4205. return (this[offset] * 0x1000000) +
  4206. ((this[offset + 1] << 16) |
  4207. (this[offset + 2] << 8) |
  4208. this[offset + 3])
  4209. }
  4210. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  4211. offset = offset >>> 0
  4212. byteLength = byteLength >>> 0
  4213. if (!noAssert) checkOffset(offset, byteLength, this.length)
  4214. var val = this[offset]
  4215. var mul = 1
  4216. var i = 0
  4217. while (++i < byteLength && (mul *= 0x100)) {
  4218. val += this[offset + i] * mul
  4219. }
  4220. mul *= 0x80
  4221. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  4222. return val
  4223. }
  4224. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  4225. offset = offset >>> 0
  4226. byteLength = byteLength >>> 0
  4227. if (!noAssert) checkOffset(offset, byteLength, this.length)
  4228. var i = byteLength
  4229. var mul = 1
  4230. var val = this[offset + --i]
  4231. while (i > 0 && (mul *= 0x100)) {
  4232. val += this[offset + --i] * mul
  4233. }
  4234. mul *= 0x80
  4235. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  4236. return val
  4237. }
  4238. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  4239. offset = offset >>> 0
  4240. if (!noAssert) checkOffset(offset, 1, this.length)
  4241. if (!(this[offset] & 0x80)) return (this[offset])
  4242. return ((0xff - this[offset] + 1) * -1)
  4243. }
  4244. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  4245. offset = offset >>> 0
  4246. if (!noAssert) checkOffset(offset, 2, this.length)
  4247. var val = this[offset] | (this[offset + 1] << 8)
  4248. return (val & 0x8000) ? val | 0xFFFF0000 : val
  4249. }
  4250. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  4251. offset = offset >>> 0
  4252. if (!noAssert) checkOffset(offset, 2, this.length)
  4253. var val = this[offset + 1] | (this[offset] << 8)
  4254. return (val & 0x8000) ? val | 0xFFFF0000 : val
  4255. }
  4256. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  4257. offset = offset >>> 0
  4258. if (!noAssert) checkOffset(offset, 4, this.length)
  4259. return (this[offset]) |
  4260. (this[offset + 1] << 8) |
  4261. (this[offset + 2] << 16) |
  4262. (this[offset + 3] << 24)
  4263. }
  4264. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  4265. offset = offset >>> 0
  4266. if (!noAssert) checkOffset(offset, 4, this.length)
  4267. return (this[offset] << 24) |
  4268. (this[offset + 1] << 16) |
  4269. (this[offset + 2] << 8) |
  4270. (this[offset + 3])
  4271. }
  4272. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  4273. offset = offset >>> 0
  4274. if (!noAssert) checkOffset(offset, 4, this.length)
  4275. return ieee754.read(this, offset, true, 23, 4)
  4276. }
  4277. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  4278. offset = offset >>> 0
  4279. if (!noAssert) checkOffset(offset, 4, this.length)
  4280. return ieee754.read(this, offset, false, 23, 4)
  4281. }
  4282. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  4283. offset = offset >>> 0
  4284. if (!noAssert) checkOffset(offset, 8, this.length)
  4285. return ieee754.read(this, offset, true, 52, 8)
  4286. }
  4287. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  4288. offset = offset >>> 0
  4289. if (!noAssert) checkOffset(offset, 8, this.length)
  4290. return ieee754.read(this, offset, false, 52, 8)
  4291. }
  4292. function checkInt (buf, value, offset, ext, max, min) {
  4293. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  4294. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  4295. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  4296. }
  4297. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  4298. value = +value
  4299. offset = offset >>> 0
  4300. byteLength = byteLength >>> 0
  4301. if (!noAssert) {
  4302. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  4303. checkInt(this, value, offset, byteLength, maxBytes, 0)
  4304. }
  4305. var mul = 1
  4306. var i = 0
  4307. this[offset] = value & 0xFF
  4308. while (++i < byteLength && (mul *= 0x100)) {
  4309. this[offset + i] = (value / mul) & 0xFF
  4310. }
  4311. return offset + byteLength
  4312. }
  4313. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  4314. value = +value
  4315. offset = offset >>> 0
  4316. byteLength = byteLength >>> 0
  4317. if (!noAssert) {
  4318. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  4319. checkInt(this, value, offset, byteLength, maxBytes, 0)
  4320. }
  4321. var i = byteLength - 1
  4322. var mul = 1
  4323. this[offset + i] = value & 0xFF
  4324. while (--i >= 0 && (mul *= 0x100)) {
  4325. this[offset + i] = (value / mul) & 0xFF
  4326. }
  4327. return offset + byteLength
  4328. }
  4329. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  4330. value = +value
  4331. offset = offset >>> 0
  4332. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  4333. this[offset] = (value & 0xff)
  4334. return offset + 1
  4335. }
  4336. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  4337. value = +value
  4338. offset = offset >>> 0
  4339. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  4340. this[offset] = (value & 0xff)
  4341. this[offset + 1] = (value >>> 8)
  4342. return offset + 2
  4343. }
  4344. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  4345. value = +value
  4346. offset = offset >>> 0
  4347. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  4348. this[offset] = (value >>> 8)
  4349. this[offset + 1] = (value & 0xff)
  4350. return offset + 2
  4351. }
  4352. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  4353. value = +value
  4354. offset = offset >>> 0
  4355. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  4356. this[offset + 3] = (value >>> 24)
  4357. this[offset + 2] = (value >>> 16)
  4358. this[offset + 1] = (value >>> 8)
  4359. this[offset] = (value & 0xff)
  4360. return offset + 4
  4361. }
  4362. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  4363. value = +value
  4364. offset = offset >>> 0
  4365. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  4366. this[offset] = (value >>> 24)
  4367. this[offset + 1] = (value >>> 16)
  4368. this[offset + 2] = (value >>> 8)
  4369. this[offset + 3] = (value & 0xff)
  4370. return offset + 4
  4371. }
  4372. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  4373. value = +value
  4374. offset = offset >>> 0
  4375. if (!noAssert) {
  4376. var limit = Math.pow(2, (8 * byteLength) - 1)
  4377. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  4378. }
  4379. var i = 0
  4380. var mul = 1
  4381. var sub = 0
  4382. this[offset] = value & 0xFF
  4383. while (++i < byteLength && (mul *= 0x100)) {
  4384. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  4385. sub = 1
  4386. }
  4387. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  4388. }
  4389. return offset + byteLength
  4390. }
  4391. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  4392. value = +value
  4393. offset = offset >>> 0
  4394. if (!noAssert) {
  4395. var limit = Math.pow(2, (8 * byteLength) - 1)
  4396. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  4397. }
  4398. var i = byteLength - 1
  4399. var mul = 1
  4400. var sub = 0
  4401. this[offset + i] = value & 0xFF
  4402. while (--i >= 0 && (mul *= 0x100)) {
  4403. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  4404. sub = 1
  4405. }
  4406. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  4407. }
  4408. return offset + byteLength
  4409. }
  4410. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  4411. value = +value
  4412. offset = offset >>> 0
  4413. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  4414. if (value < 0) value = 0xff + value + 1
  4415. this[offset] = (value & 0xff)
  4416. return offset + 1
  4417. }
  4418. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  4419. value = +value
  4420. offset = offset >>> 0
  4421. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  4422. this[offset] = (value & 0xff)
  4423. this[offset + 1] = (value >>> 8)
  4424. return offset + 2
  4425. }
  4426. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  4427. value = +value
  4428. offset = offset >>> 0
  4429. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  4430. this[offset] = (value >>> 8)
  4431. this[offset + 1] = (value & 0xff)
  4432. return offset + 2
  4433. }
  4434. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  4435. value = +value
  4436. offset = offset >>> 0
  4437. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  4438. this[offset] = (value & 0xff)
  4439. this[offset + 1] = (value >>> 8)
  4440. this[offset + 2] = (value >>> 16)
  4441. this[offset + 3] = (value >>> 24)
  4442. return offset + 4
  4443. }
  4444. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  4445. value = +value
  4446. offset = offset >>> 0
  4447. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  4448. if (value < 0) value = 0xffffffff + value + 1
  4449. this[offset] = (value >>> 24)
  4450. this[offset + 1] = (value >>> 16)
  4451. this[offset + 2] = (value >>> 8)
  4452. this[offset + 3] = (value & 0xff)
  4453. return offset + 4
  4454. }
  4455. function checkIEEE754 (buf, value, offset, ext, max, min) {
  4456. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  4457. if (offset < 0) throw new RangeError('Index out of range')
  4458. }
  4459. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  4460. value = +value
  4461. offset = offset >>> 0
  4462. if (!noAssert) {
  4463. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  4464. }
  4465. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  4466. return offset + 4
  4467. }
  4468. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  4469. return writeFloat(this, value, offset, true, noAssert)
  4470. }
  4471. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  4472. return writeFloat(this, value, offset, false, noAssert)
  4473. }
  4474. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  4475. value = +value
  4476. offset = offset >>> 0
  4477. if (!noAssert) {
  4478. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  4479. }
  4480. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  4481. return offset + 8
  4482. }
  4483. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  4484. return writeDouble(this, value, offset, true, noAssert)
  4485. }
  4486. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  4487. return writeDouble(this, value, offset, false, noAssert)
  4488. }
  4489. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  4490. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  4491. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  4492. if (!start) start = 0
  4493. if (!end && end !== 0) end = this.length
  4494. if (targetStart >= target.length) targetStart = target.length
  4495. if (!targetStart) targetStart = 0
  4496. if (end > 0 && end < start) end = start
  4497. // Copy 0 bytes; we're done
  4498. if (end === start) return 0
  4499. if (target.length === 0 || this.length === 0) return 0
  4500. // Fatal error conditions
  4501. if (targetStart < 0) {
  4502. throw new RangeError('targetStart out of bounds')
  4503. }
  4504. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  4505. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  4506. // Are we oob?
  4507. if (end > this.length) end = this.length
  4508. if (target.length - targetStart < end - start) {
  4509. end = target.length - targetStart + start
  4510. }
  4511. var len = end - start
  4512. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  4513. // Use built-in when available, missing from IE11
  4514. this.copyWithin(targetStart, start, end)
  4515. } else if (this === target && start < targetStart && targetStart < end) {
  4516. // descending copy from end
  4517. for (var i = len - 1; i >= 0; --i) {
  4518. target[i + targetStart] = this[i + start]
  4519. }
  4520. } else {
  4521. Uint8Array.prototype.set.call(
  4522. target,
  4523. this.subarray(start, end),
  4524. targetStart
  4525. )
  4526. }
  4527. return len
  4528. }
  4529. // Usage:
  4530. // buffer.fill(number[, offset[, end]])
  4531. // buffer.fill(buffer[, offset[, end]])
  4532. // buffer.fill(string[, offset[, end]][, encoding])
  4533. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  4534. // Handle string cases:
  4535. if (typeof val === 'string') {
  4536. if (typeof start === 'string') {
  4537. encoding = start
  4538. start = 0
  4539. end = this.length
  4540. } else if (typeof end === 'string') {
  4541. encoding = end
  4542. end = this.length
  4543. }
  4544. if (encoding !== undefined && typeof encoding !== 'string') {
  4545. throw new TypeError('encoding must be a string')
  4546. }
  4547. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  4548. throw new TypeError('Unknown encoding: ' + encoding)
  4549. }
  4550. if (val.length === 1) {
  4551. var code = val.charCodeAt(0)
  4552. if ((encoding === 'utf8' && code < 128) ||
  4553. encoding === 'latin1') {
  4554. // Fast path: If `val` fits into a single byte, use that numeric value.
  4555. val = code
  4556. }
  4557. }
  4558. } else if (typeof val === 'number') {
  4559. val = val & 255
  4560. }
  4561. // Invalid ranges are not set to a default, so can range check early.
  4562. if (start < 0 || this.length < start || this.length < end) {
  4563. throw new RangeError('Out of range index')
  4564. }
  4565. if (end <= start) {
  4566. return this
  4567. }
  4568. start = start >>> 0
  4569. end = end === undefined ? this.length : end >>> 0
  4570. if (!val) val = 0
  4571. var i
  4572. if (typeof val === 'number') {
  4573. for (i = start; i < end; ++i) {
  4574. this[i] = val
  4575. }
  4576. } else {
  4577. var bytes = Buffer.isBuffer(val)
  4578. ? val
  4579. : Buffer.from(val, encoding)
  4580. var len = bytes.length
  4581. if (len === 0) {
  4582. throw new TypeError('The value "' + val +
  4583. '" is invalid for argument "value"')
  4584. }
  4585. for (i = 0; i < end - start; ++i) {
  4586. this[i + start] = bytes[i % len]
  4587. }
  4588. }
  4589. return this
  4590. }
  4591. // HELPER FUNCTIONS
  4592. // ================
  4593. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  4594. function base64clean (str) {
  4595. // Node takes equal signs as end of the Base64 encoding
  4596. str = str.split('=')[0]
  4597. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  4598. str = str.trim().replace(INVALID_BASE64_RE, '')
  4599. // Node converts strings with length < 2 to ''
  4600. if (str.length < 2) return ''
  4601. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  4602. while (str.length % 4 !== 0) {
  4603. str = str + '='
  4604. }
  4605. return str
  4606. }
  4607. function toHex (n) {
  4608. if (n < 16) return '0' + n.toString(16)
  4609. return n.toString(16)
  4610. }
  4611. function utf8ToBytes (string, units) {
  4612. units = units || Infinity
  4613. var codePoint
  4614. var length = string.length
  4615. var leadSurrogate = null
  4616. var bytes = []
  4617. for (var i = 0; i < length; ++i) {
  4618. codePoint = string.charCodeAt(i)
  4619. // is surrogate component
  4620. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  4621. // last char was a lead
  4622. if (!leadSurrogate) {
  4623. // no lead yet
  4624. if (codePoint > 0xDBFF) {
  4625. // unexpected trail
  4626. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4627. continue
  4628. } else if (i + 1 === length) {
  4629. // unpaired lead
  4630. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4631. continue
  4632. }
  4633. // valid lead
  4634. leadSurrogate = codePoint
  4635. continue
  4636. }
  4637. // 2 leads in a row
  4638. if (codePoint < 0xDC00) {
  4639. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4640. leadSurrogate = codePoint
  4641. continue
  4642. }
  4643. // valid surrogate pair
  4644. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  4645. } else if (leadSurrogate) {
  4646. // valid bmp char, but last char was a lead
  4647. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4648. }
  4649. leadSurrogate = null
  4650. // encode utf8
  4651. if (codePoint < 0x80) {
  4652. if ((units -= 1) < 0) break
  4653. bytes.push(codePoint)
  4654. } else if (codePoint < 0x800) {
  4655. if ((units -= 2) < 0) break
  4656. bytes.push(
  4657. codePoint >> 0x6 | 0xC0,
  4658. codePoint & 0x3F | 0x80
  4659. )
  4660. } else if (codePoint < 0x10000) {
  4661. if ((units -= 3) < 0) break
  4662. bytes.push(
  4663. codePoint >> 0xC | 0xE0,
  4664. codePoint >> 0x6 & 0x3F | 0x80,
  4665. codePoint & 0x3F | 0x80
  4666. )
  4667. } else if (codePoint < 0x110000) {
  4668. if ((units -= 4) < 0) break
  4669. bytes.push(
  4670. codePoint >> 0x12 | 0xF0,
  4671. codePoint >> 0xC & 0x3F | 0x80,
  4672. codePoint >> 0x6 & 0x3F | 0x80,
  4673. codePoint & 0x3F | 0x80
  4674. )
  4675. } else {
  4676. throw new Error('Invalid code point')
  4677. }
  4678. }
  4679. return bytes
  4680. }
  4681. function asciiToBytes (str) {
  4682. var byteArray = []
  4683. for (var i = 0; i < str.length; ++i) {
  4684. // Node's code seems to be doing this and not & 0x7F..
  4685. byteArray.push(str.charCodeAt(i) & 0xFF)
  4686. }
  4687. return byteArray
  4688. }
  4689. function utf16leToBytes (str, units) {
  4690. var c, hi, lo
  4691. var byteArray = []
  4692. for (var i = 0; i < str.length; ++i) {
  4693. if ((units -= 2) < 0) break
  4694. c = str.charCodeAt(i)
  4695. hi = c >> 8
  4696. lo = c % 256
  4697. byteArray.push(lo)
  4698. byteArray.push(hi)
  4699. }
  4700. return byteArray
  4701. }
  4702. function base64ToBytes (str) {
  4703. return base64.toByteArray(base64clean(str))
  4704. }
  4705. function blitBuffer (src, dst, offset, length) {
  4706. for (var i = 0; i < length; ++i) {
  4707. if ((i + offset >= dst.length) || (i >= src.length)) break
  4708. dst[i + offset] = src[i]
  4709. }
  4710. return i
  4711. }
  4712. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  4713. // the `instanceof` check but they should be treated as of that type.
  4714. // See: https://github.com/feross/buffer/issues/166
  4715. function isInstance (obj, type) {
  4716. return obj instanceof type ||
  4717. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  4718. obj.constructor.name === type.name)
  4719. }
  4720. function numberIsNaN (obj) {
  4721. // For IE11 support
  4722. return obj !== obj // eslint-disable-line no-self-compare
  4723. }
  4724. }).call(this)}).call(this,require("buffer").Buffer)
  4725. },{"base64-js":13,"buffer":17,"ieee754":23}],18:[function(require,module,exports){
  4726. (function (process){(function (){
  4727. /* eslint-env browser */
  4728. /**
  4729. * This is the web browser implementation of `debug()`.
  4730. */
  4731. exports.formatArgs = formatArgs;
  4732. exports.save = save;
  4733. exports.load = load;
  4734. exports.useColors = useColors;
  4735. exports.storage = localstorage();
  4736. exports.destroy = (() => {
  4737. let warned = false;
  4738. return () => {
  4739. if (!warned) {
  4740. warned = true;
  4741. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  4742. }
  4743. };
  4744. })();
  4745. /**
  4746. * Colors.
  4747. */
  4748. exports.colors = [
  4749. '#0000CC',
  4750. '#0000FF',
  4751. '#0033CC',
  4752. '#0033FF',
  4753. '#0066CC',
  4754. '#0066FF',
  4755. '#0099CC',
  4756. '#0099FF',
  4757. '#00CC00',
  4758. '#00CC33',
  4759. '#00CC66',
  4760. '#00CC99',
  4761. '#00CCCC',
  4762. '#00CCFF',
  4763. '#3300CC',
  4764. '#3300FF',
  4765. '#3333CC',
  4766. '#3333FF',
  4767. '#3366CC',
  4768. '#3366FF',
  4769. '#3399CC',
  4770. '#3399FF',
  4771. '#33CC00',
  4772. '#33CC33',
  4773. '#33CC66',
  4774. '#33CC99',
  4775. '#33CCCC',
  4776. '#33CCFF',
  4777. '#6600CC',
  4778. '#6600FF',
  4779. '#6633CC',
  4780. '#6633FF',
  4781. '#66CC00',
  4782. '#66CC33',
  4783. '#9900CC',
  4784. '#9900FF',
  4785. '#9933CC',
  4786. '#9933FF',
  4787. '#99CC00',
  4788. '#99CC33',
  4789. '#CC0000',
  4790. '#CC0033',
  4791. '#CC0066',
  4792. '#CC0099',
  4793. '#CC00CC',
  4794. '#CC00FF',
  4795. '#CC3300',
  4796. '#CC3333',
  4797. '#CC3366',
  4798. '#CC3399',
  4799. '#CC33CC',
  4800. '#CC33FF',
  4801. '#CC6600',
  4802. '#CC6633',
  4803. '#CC9900',
  4804. '#CC9933',
  4805. '#CCCC00',
  4806. '#CCCC33',
  4807. '#FF0000',
  4808. '#FF0033',
  4809. '#FF0066',
  4810. '#FF0099',
  4811. '#FF00CC',
  4812. '#FF00FF',
  4813. '#FF3300',
  4814. '#FF3333',
  4815. '#FF3366',
  4816. '#FF3399',
  4817. '#FF33CC',
  4818. '#FF33FF',
  4819. '#FF6600',
  4820. '#FF6633',
  4821. '#FF9900',
  4822. '#FF9933',
  4823. '#FFCC00',
  4824. '#FFCC33'
  4825. ];
  4826. /**
  4827. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  4828. * and the Firebug extension (any Firefox version) are known
  4829. * to support "%c" CSS customizations.
  4830. *
  4831. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  4832. */
  4833. // eslint-disable-next-line complexity
  4834. function useColors() {
  4835. // NB: In an Electron preload script, document will be defined but not fully
  4836. // initialized. Since we know we're in Chrome, we'll just detect this case
  4837. // explicitly
  4838. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  4839. return true;
  4840. }
  4841. // Internet Explorer and Edge do not support colors.
  4842. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  4843. return false;
  4844. }
  4845. // Is webkit? http://stackoverflow.com/a/16459606/376773
  4846. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  4847. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  4848. // Is firebug? http://stackoverflow.com/a/398120/376773
  4849. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  4850. // Is firefox >= v31?
  4851. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  4852. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  4853. // Double check webkit in userAgent just in case we are in a worker
  4854. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  4855. }
  4856. /**
  4857. * Colorize log arguments if enabled.
  4858. *
  4859. * @api public
  4860. */
  4861. function formatArgs(args) {
  4862. args[0] = (this.useColors ? '%c' : '') +
  4863. this.namespace +
  4864. (this.useColors ? ' %c' : ' ') +
  4865. args[0] +
  4866. (this.useColors ? '%c ' : ' ') +
  4867. '+' + module.exports.humanize(this.diff);
  4868. if (!this.useColors) {
  4869. return;
  4870. }
  4871. const c = 'color: ' + this.color;
  4872. args.splice(1, 0, c, 'color: inherit');
  4873. // The final "%c" is somewhat tricky, because there could be other
  4874. // arguments passed either before or after the %c, so we need to
  4875. // figure out the correct index to insert the CSS into
  4876. let index = 0;
  4877. let lastC = 0;
  4878. args[0].replace(/%[a-zA-Z%]/g, match => {
  4879. if (match === '%%') {
  4880. return;
  4881. }
  4882. index++;
  4883. if (match === '%c') {
  4884. // We only are interested in the *last* %c
  4885. // (the user may have provided their own)
  4886. lastC = index;
  4887. }
  4888. });
  4889. args.splice(lastC, 0, c);
  4890. }
  4891. /**
  4892. * Invokes `console.debug()` when available.
  4893. * No-op when `console.debug` is not a "function".
  4894. * If `console.debug` is not available, falls back
  4895. * to `console.log`.
  4896. *
  4897. * @api public
  4898. */
  4899. exports.log = console.debug || console.log || (() => {});
  4900. /**
  4901. * Save `namespaces`.
  4902. *
  4903. * @param {String} namespaces
  4904. * @api private
  4905. */
  4906. function save(namespaces) {
  4907. try {
  4908. if (namespaces) {
  4909. exports.storage.setItem('debug', namespaces);
  4910. } else {
  4911. exports.storage.removeItem('debug');
  4912. }
  4913. } catch (error) {
  4914. // Swallow
  4915. // XXX (@Qix-) should we be logging these?
  4916. }
  4917. }
  4918. /**
  4919. * Load `namespaces`.
  4920. *
  4921. * @return {String} returns the previously persisted debug modes
  4922. * @api private
  4923. */
  4924. function load() {
  4925. let r;
  4926. try {
  4927. r = exports.storage.getItem('debug');
  4928. } catch (error) {
  4929. // Swallow
  4930. // XXX (@Qix-) should we be logging these?
  4931. }
  4932. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  4933. if (!r && typeof process !== 'undefined' && 'env' in process) {
  4934. r = process.env.DEBUG;
  4935. }
  4936. return r;
  4937. }
  4938. /**
  4939. * Localstorage attempts to return the localstorage.
  4940. *
  4941. * This is necessary because safari throws
  4942. * when a user disables cookies/localstorage
  4943. * and you attempt to access it.
  4944. *
  4945. * @return {LocalStorage}
  4946. * @api private
  4947. */
  4948. function localstorage() {
  4949. try {
  4950. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  4951. // The Browser also has localStorage in the global context.
  4952. return localStorage;
  4953. } catch (error) {
  4954. // Swallow
  4955. // XXX (@Qix-) should we be logging these?
  4956. }
  4957. }
  4958. module.exports = require('./common')(exports);
  4959. const {formatters} = module.exports;
  4960. /**
  4961. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  4962. */
  4963. formatters.j = function (v) {
  4964. try {
  4965. return JSON.stringify(v);
  4966. } catch (error) {
  4967. return '[UnexpectedJSONParseError]: ' + error.message;
  4968. }
  4969. };
  4970. }).call(this)}).call(this,require('_process'))
  4971. },{"./common":19,"_process":50}],19:[function(require,module,exports){
  4972. /**
  4973. * This is the common logic for both the Node.js and web browser
  4974. * implementations of `debug()`.
  4975. */
  4976. function setup(env) {
  4977. createDebug.debug = createDebug;
  4978. createDebug.default = createDebug;
  4979. createDebug.coerce = coerce;
  4980. createDebug.disable = disable;
  4981. createDebug.enable = enable;
  4982. createDebug.enabled = enabled;
  4983. createDebug.humanize = require('ms');
  4984. createDebug.destroy = destroy;
  4985. Object.keys(env).forEach(key => {
  4986. createDebug[key] = env[key];
  4987. });
  4988. /**
  4989. * The currently active debug mode names, and names to skip.
  4990. */
  4991. createDebug.names = [];
  4992. createDebug.skips = [];
  4993. /**
  4994. * Map of special "%n" handling functions, for the debug "format" argument.
  4995. *
  4996. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  4997. */
  4998. createDebug.formatters = {};
  4999. /**
  5000. * Selects a color for a debug namespace
  5001. * @param {String} namespace The namespace string for the debug instance to be colored
  5002. * @return {Number|String} An ANSI color code for the given namespace
  5003. * @api private
  5004. */
  5005. function selectColor(namespace) {
  5006. let hash = 0;
  5007. for (let i = 0; i < namespace.length; i++) {
  5008. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  5009. hash |= 0; // Convert to 32bit integer
  5010. }
  5011. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  5012. }
  5013. createDebug.selectColor = selectColor;
  5014. /**
  5015. * Create a debugger with the given `namespace`.
  5016. *
  5017. * @param {String} namespace
  5018. * @return {Function}
  5019. * @api public
  5020. */
  5021. function createDebug(namespace) {
  5022. let prevTime;
  5023. let enableOverride = null;
  5024. let namespacesCache;
  5025. let enabledCache;
  5026. function debug(...args) {
  5027. // Disabled?
  5028. if (!debug.enabled) {
  5029. return;
  5030. }
  5031. const self = debug;
  5032. // Set `diff` timestamp
  5033. const curr = Number(new Date());
  5034. const ms = curr - (prevTime || curr);
  5035. self.diff = ms;
  5036. self.prev = prevTime;
  5037. self.curr = curr;
  5038. prevTime = curr;
  5039. args[0] = createDebug.coerce(args[0]);
  5040. if (typeof args[0] !== 'string') {
  5041. // Anything else let's inspect with %O
  5042. args.unshift('%O');
  5043. }
  5044. // Apply any `formatters` transformations
  5045. let index = 0;
  5046. args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
  5047. // If we encounter an escaped % then don't increase the array index
  5048. if (match === '%%') {
  5049. return '%';
  5050. }
  5051. index++;
  5052. const formatter = createDebug.formatters[format];
  5053. if (typeof formatter === 'function') {
  5054. const val = args[index];
  5055. match = formatter.call(self, val);
  5056. // Now we need to remove `args[index]` since it's inlined in the `format`
  5057. args.splice(index, 1);
  5058. index--;
  5059. }
  5060. return match;
  5061. });
  5062. // Apply env-specific formatting (colors, etc.)
  5063. createDebug.formatArgs.call(self, args);
  5064. const logFn = self.log || createDebug.log;
  5065. logFn.apply(self, args);
  5066. }
  5067. debug.namespace = namespace;
  5068. debug.useColors = createDebug.useColors();
  5069. debug.color = createDebug.selectColor(namespace);
  5070. debug.extend = extend;
  5071. debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
  5072. Object.defineProperty(debug, 'enabled', {
  5073. enumerable: true,
  5074. configurable: false,
  5075. get: () => {
  5076. if (enableOverride !== null) {
  5077. return enableOverride;
  5078. }
  5079. if (namespacesCache !== createDebug.namespaces) {
  5080. namespacesCache = createDebug.namespaces;
  5081. enabledCache = createDebug.enabled(namespace);
  5082. }
  5083. return enabledCache;
  5084. },
  5085. set: v => {
  5086. enableOverride = v;
  5087. }
  5088. });
  5089. // Env-specific initialization logic for debug instances
  5090. if (typeof createDebug.init === 'function') {
  5091. createDebug.init(debug);
  5092. }
  5093. return debug;
  5094. }
  5095. function extend(namespace, delimiter) {
  5096. const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  5097. newDebug.log = this.log;
  5098. return newDebug;
  5099. }
  5100. /**
  5101. * Enables a debug mode by namespaces. This can include modes
  5102. * separated by a colon and wildcards.
  5103. *
  5104. * @param {String} namespaces
  5105. * @api public
  5106. */
  5107. function enable(namespaces) {
  5108. createDebug.save(namespaces);
  5109. createDebug.namespaces = namespaces;
  5110. createDebug.names = [];
  5111. createDebug.skips = [];
  5112. let i;
  5113. const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  5114. const len = split.length;
  5115. for (i = 0; i < len; i++) {
  5116. if (!split[i]) {
  5117. // ignore empty strings
  5118. continue;
  5119. }
  5120. namespaces = split[i].replace(/\*/g, '.*?');
  5121. if (namespaces[0] === '-') {
  5122. createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  5123. } else {
  5124. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  5125. }
  5126. }
  5127. }
  5128. /**
  5129. * Disable debug output.
  5130. *
  5131. * @return {String} namespaces
  5132. * @api public
  5133. */
  5134. function disable() {
  5135. const namespaces = [
  5136. ...createDebug.names.map(toNamespace),
  5137. ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
  5138. ].join(',');
  5139. createDebug.enable('');
  5140. return namespaces;
  5141. }
  5142. /**
  5143. * Returns true if the given mode name is enabled, false otherwise.
  5144. *
  5145. * @param {String} name
  5146. * @return {Boolean}
  5147. * @api public
  5148. */
  5149. function enabled(name) {
  5150. if (name[name.length - 1] === '*') {
  5151. return true;
  5152. }
  5153. let i;
  5154. let len;
  5155. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  5156. if (createDebug.skips[i].test(name)) {
  5157. return false;
  5158. }
  5159. }
  5160. for (i = 0, len = createDebug.names.length; i < len; i++) {
  5161. if (createDebug.names[i].test(name)) {
  5162. return true;
  5163. }
  5164. }
  5165. return false;
  5166. }
  5167. /**
  5168. * Convert regexp to namespace
  5169. *
  5170. * @param {RegExp} regxep
  5171. * @return {String} namespace
  5172. * @api private
  5173. */
  5174. function toNamespace(regexp) {
  5175. return regexp.toString()
  5176. .substring(2, regexp.toString().length - 2)
  5177. .replace(/\.\*\?$/, '*');
  5178. }
  5179. /**
  5180. * Coerce `val`.
  5181. *
  5182. * @param {Mixed} val
  5183. * @return {Mixed}
  5184. * @api private
  5185. */
  5186. function coerce(val) {
  5187. if (val instanceof Error) {
  5188. return val.stack || val.message;
  5189. }
  5190. return val;
  5191. }
  5192. /**
  5193. * XXX DO NOT USE. This is a temporary stub function.
  5194. * XXX It WILL be removed in the next major release.
  5195. */
  5196. function destroy() {
  5197. console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
  5198. }
  5199. createDebug.enable(createDebug.load());
  5200. return createDebug;
  5201. }
  5202. module.exports = setup;
  5203. },{"ms":45}],20:[function(require,module,exports){
  5204. (function (process,Buffer){(function (){
  5205. var stream = require('readable-stream')
  5206. var eos = require('end-of-stream')
  5207. var inherits = require('inherits')
  5208. var shift = require('stream-shift')
  5209. var SIGNAL_FLUSH = (Buffer.from && Buffer.from !== Uint8Array.from)
  5210. ? Buffer.from([0])
  5211. : new Buffer([0])
  5212. var onuncork = function(self, fn) {
  5213. if (self._corked) self.once('uncork', fn)
  5214. else fn()
  5215. }
  5216. var autoDestroy = function (self, err) {
  5217. if (self._autoDestroy) self.destroy(err)
  5218. }
  5219. var destroyer = function(self, end) {
  5220. return function(err) {
  5221. if (err) autoDestroy(self, err.message === 'premature close' ? null : err)
  5222. else if (end && !self._ended) self.end()
  5223. }
  5224. }
  5225. var end = function(ws, fn) {
  5226. if (!ws) return fn()
  5227. if (ws._writableState && ws._writableState.finished) return fn()
  5228. if (ws._writableState) return ws.end(fn)
  5229. ws.end()
  5230. fn()
  5231. }
  5232. var noop = function() {}
  5233. var toStreams2 = function(rs) {
  5234. return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs)
  5235. }
  5236. var Duplexify = function(writable, readable, opts) {
  5237. if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts)
  5238. stream.Duplex.call(this, opts)
  5239. this._writable = null
  5240. this._readable = null
  5241. this._readable2 = null
  5242. this._autoDestroy = !opts || opts.autoDestroy !== false
  5243. this._forwardDestroy = !opts || opts.destroy !== false
  5244. this._forwardEnd = !opts || opts.end !== false
  5245. this._corked = 1 // start corked
  5246. this._ondrain = null
  5247. this._drained = false
  5248. this._forwarding = false
  5249. this._unwrite = null
  5250. this._unread = null
  5251. this._ended = false
  5252. this.destroyed = false
  5253. if (writable) this.setWritable(writable)
  5254. if (readable) this.setReadable(readable)
  5255. }
  5256. inherits(Duplexify, stream.Duplex)
  5257. Duplexify.obj = function(writable, readable, opts) {
  5258. if (!opts) opts = {}
  5259. opts.objectMode = true
  5260. opts.highWaterMark = 16
  5261. return new Duplexify(writable, readable, opts)
  5262. }
  5263. Duplexify.prototype.cork = function() {
  5264. if (++this._corked === 1) this.emit('cork')
  5265. }
  5266. Duplexify.prototype.uncork = function() {
  5267. if (this._corked && --this._corked === 0) this.emit('uncork')
  5268. }
  5269. Duplexify.prototype.setWritable = function(writable) {
  5270. if (this._unwrite) this._unwrite()
  5271. if (this.destroyed) {
  5272. if (writable && writable.destroy) writable.destroy()
  5273. return
  5274. }
  5275. if (writable === null || writable === false) {
  5276. this.end()
  5277. return
  5278. }
  5279. var self = this
  5280. var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd))
  5281. var ondrain = function() {
  5282. var ondrain = self._ondrain
  5283. self._ondrain = null
  5284. if (ondrain) ondrain()
  5285. }
  5286. var clear = function() {
  5287. self._writable.removeListener('drain', ondrain)
  5288. unend()
  5289. }
  5290. if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks
  5291. this._writable = writable
  5292. this._writable.on('drain', ondrain)
  5293. this._unwrite = clear
  5294. this.uncork() // always uncork setWritable
  5295. }
  5296. Duplexify.prototype.setReadable = function(readable) {
  5297. if (this._unread) this._unread()
  5298. if (this.destroyed) {
  5299. if (readable && readable.destroy) readable.destroy()
  5300. return
  5301. }
  5302. if (readable === null || readable === false) {
  5303. this.push(null)
  5304. this.resume()
  5305. return
  5306. }
  5307. var self = this
  5308. var unend = eos(readable, {writable:false, readable:true}, destroyer(this))
  5309. var onreadable = function() {
  5310. self._forward()
  5311. }
  5312. var onend = function() {
  5313. self.push(null)
  5314. }
  5315. var clear = function() {
  5316. self._readable2.removeListener('readable', onreadable)
  5317. self._readable2.removeListener('end', onend)
  5318. unend()
  5319. }
  5320. this._drained = true
  5321. this._readable = readable
  5322. this._readable2 = readable._readableState ? readable : toStreams2(readable)
  5323. this._readable2.on('readable', onreadable)
  5324. this._readable2.on('end', onend)
  5325. this._unread = clear
  5326. this._forward()
  5327. }
  5328. Duplexify.prototype._read = function() {
  5329. this._drained = true
  5330. this._forward()
  5331. }
  5332. Duplexify.prototype._forward = function() {
  5333. if (this._forwarding || !this._readable2 || !this._drained) return
  5334. this._forwarding = true
  5335. var data
  5336. while (this._drained && (data = shift(this._readable2)) !== null) {
  5337. if (this.destroyed) continue
  5338. this._drained = this.push(data)
  5339. }
  5340. this._forwarding = false
  5341. }
  5342. Duplexify.prototype.destroy = function(err, cb) {
  5343. if (!cb) cb = noop
  5344. if (this.destroyed) return cb(null)
  5345. this.destroyed = true
  5346. var self = this
  5347. process.nextTick(function() {
  5348. self._destroy(err)
  5349. cb(null)
  5350. })
  5351. }
  5352. Duplexify.prototype._destroy = function(err) {
  5353. if (err) {
  5354. var ondrain = this._ondrain
  5355. this._ondrain = null
  5356. if (ondrain) ondrain(err)
  5357. else this.emit('error', err)
  5358. }
  5359. if (this._forwardDestroy) {
  5360. if (this._readable && this._readable.destroy) this._readable.destroy()
  5361. if (this._writable && this._writable.destroy) this._writable.destroy()
  5362. }
  5363. this.emit('close')
  5364. }
  5365. Duplexify.prototype._write = function(data, enc, cb) {
  5366. if (this.destroyed) return
  5367. if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb))
  5368. if (data === SIGNAL_FLUSH) return this._finish(cb)
  5369. if (!this._writable) return cb()
  5370. if (this._writable.write(data) === false) this._ondrain = cb
  5371. else if (!this.destroyed) cb()
  5372. }
  5373. Duplexify.prototype._finish = function(cb) {
  5374. var self = this
  5375. this.emit('preend')
  5376. onuncork(this, function() {
  5377. end(self._forwardEnd && self._writable, function() {
  5378. // haxx to not emit prefinish twice
  5379. if (self._writableState.prefinished === false) self._writableState.prefinished = true
  5380. self.emit('prefinish')
  5381. onuncork(self, cb)
  5382. })
  5383. })
  5384. }
  5385. Duplexify.prototype.end = function(data, enc, cb) {
  5386. if (typeof data === 'function') return this.end(null, null, data)
  5387. if (typeof enc === 'function') return this.end(data, null, enc)
  5388. this._ended = true
  5389. if (data) this.write(data)
  5390. if (!this._writableState.ending && !this._writableState.destroyed) this.write(SIGNAL_FLUSH)
  5391. return stream.Writable.prototype.end.call(this, cb)
  5392. }
  5393. module.exports = Duplexify
  5394. }).call(this)}).call(this,require('_process'),require("buffer").Buffer)
  5395. },{"_process":50,"buffer":17,"end-of-stream":21,"inherits":24,"readable-stream":69,"stream-shift":74}],21:[function(require,module,exports){
  5396. (function (process){(function (){
  5397. var once = require('once');
  5398. var noop = function() {};
  5399. var isRequest = function(stream) {
  5400. return stream.setHeader && typeof stream.abort === 'function';
  5401. };
  5402. var isChildProcess = function(stream) {
  5403. return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
  5404. };
  5405. var eos = function(stream, opts, callback) {
  5406. if (typeof opts === 'function') return eos(stream, null, opts);
  5407. if (!opts) opts = {};
  5408. callback = once(callback || noop);
  5409. var ws = stream._writableState;
  5410. var rs = stream._readableState;
  5411. var readable = opts.readable || (opts.readable !== false && stream.readable);
  5412. var writable = opts.writable || (opts.writable !== false && stream.writable);
  5413. var cancelled = false;
  5414. var onlegacyfinish = function() {
  5415. if (!stream.writable) onfinish();
  5416. };
  5417. var onfinish = function() {
  5418. writable = false;
  5419. if (!readable) callback.call(stream);
  5420. };
  5421. var onend = function() {
  5422. readable = false;
  5423. if (!writable) callback.call(stream);
  5424. };
  5425. var onexit = function(exitCode) {
  5426. callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
  5427. };
  5428. var onerror = function(err) {
  5429. callback.call(stream, err);
  5430. };
  5431. var onclose = function() {
  5432. process.nextTick(onclosenexttick);
  5433. };
  5434. var onclosenexttick = function() {
  5435. if (cancelled) return;
  5436. if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));
  5437. if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));
  5438. };
  5439. var onrequest = function() {
  5440. stream.req.on('finish', onfinish);
  5441. };
  5442. if (isRequest(stream)) {
  5443. stream.on('complete', onfinish);
  5444. stream.on('abort', onclose);
  5445. if (stream.req) onrequest();
  5446. else stream.on('request', onrequest);
  5447. } else if (writable && !ws) { // legacy streams
  5448. stream.on('end', onlegacyfinish);
  5449. stream.on('close', onlegacyfinish);
  5450. }
  5451. if (isChildProcess(stream)) stream.on('exit', onexit);
  5452. stream.on('end', onend);
  5453. stream.on('finish', onfinish);
  5454. if (opts.error !== false) stream.on('error', onerror);
  5455. stream.on('close', onclose);
  5456. return function() {
  5457. cancelled = true;
  5458. stream.removeListener('complete', onfinish);
  5459. stream.removeListener('abort', onclose);
  5460. stream.removeListener('request', onrequest);
  5461. if (stream.req) stream.req.removeListener('finish', onfinish);
  5462. stream.removeListener('end', onlegacyfinish);
  5463. stream.removeListener('close', onlegacyfinish);
  5464. stream.removeListener('finish', onfinish);
  5465. stream.removeListener('exit', onexit);
  5466. stream.removeListener('end', onend);
  5467. stream.removeListener('error', onerror);
  5468. stream.removeListener('close', onclose);
  5469. };
  5470. };
  5471. module.exports = eos;
  5472. }).call(this)}).call(this,require('_process'))
  5473. },{"_process":50,"once":48}],22:[function(require,module,exports){
  5474. // Copyright Joyent, Inc. and other Node contributors.
  5475. //
  5476. // Permission is hereby granted, free of charge, to any person obtaining a
  5477. // copy of this software and associated documentation files (the
  5478. // "Software"), to deal in the Software without restriction, including
  5479. // without limitation the rights to use, copy, modify, merge, publish,
  5480. // distribute, sublicense, and/or sell copies of the Software, and to permit
  5481. // persons to whom the Software is furnished to do so, subject to the
  5482. // following conditions:
  5483. //
  5484. // The above copyright notice and this permission notice shall be included
  5485. // in all copies or substantial portions of the Software.
  5486. //
  5487. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  5488. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  5489. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  5490. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  5491. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  5492. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  5493. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  5494. var objectCreate = Object.create || objectCreatePolyfill
  5495. var objectKeys = Object.keys || objectKeysPolyfill
  5496. var bind = Function.prototype.bind || functionBindPolyfill
  5497. function EventEmitter() {
  5498. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  5499. this._events = objectCreate(null);
  5500. this._eventsCount = 0;
  5501. }
  5502. this._maxListeners = this._maxListeners || undefined;
  5503. }
  5504. module.exports = EventEmitter;
  5505. // Backwards-compat with node 0.10.x
  5506. EventEmitter.EventEmitter = EventEmitter;
  5507. EventEmitter.prototype._events = undefined;
  5508. EventEmitter.prototype._maxListeners = undefined;
  5509. // By default EventEmitters will print a warning if more than 10 listeners are
  5510. // added to it. This is a useful default which helps finding memory leaks.
  5511. var defaultMaxListeners = 10;
  5512. var hasDefineProperty;
  5513. try {
  5514. var o = {};
  5515. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  5516. hasDefineProperty = o.x === 0;
  5517. } catch (err) { hasDefineProperty = false }
  5518. if (hasDefineProperty) {
  5519. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  5520. enumerable: true,
  5521. get: function() {
  5522. return defaultMaxListeners;
  5523. },
  5524. set: function(arg) {
  5525. // check whether the input is a positive number (whose value is zero or
  5526. // greater and not a NaN).
  5527. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  5528. throw new TypeError('"defaultMaxListeners" must be a positive number');
  5529. defaultMaxListeners = arg;
  5530. }
  5531. });
  5532. } else {
  5533. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  5534. }
  5535. // Obviously not all Emitters should be limited to 10. This function allows
  5536. // that to be increased. Set to zero for unlimited.
  5537. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  5538. if (typeof n !== 'number' || n < 0 || isNaN(n))
  5539. throw new TypeError('"n" argument must be a positive number');
  5540. this._maxListeners = n;
  5541. return this;
  5542. };
  5543. function $getMaxListeners(that) {
  5544. if (that._maxListeners === undefined)
  5545. return EventEmitter.defaultMaxListeners;
  5546. return that._maxListeners;
  5547. }
  5548. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  5549. return $getMaxListeners(this);
  5550. };
  5551. // These standalone emit* functions are used to optimize calling of event
  5552. // handlers for fast cases because emit() itself often has a variable number of
  5553. // arguments and can be deoptimized because of that. These functions always have
  5554. // the same number of arguments and thus do not get deoptimized, so the code
  5555. // inside them can execute faster.
  5556. function emitNone(handler, isFn, self) {
  5557. if (isFn)
  5558. handler.call(self);
  5559. else {
  5560. var len = handler.length;
  5561. var listeners = arrayClone(handler, len);
  5562. for (var i = 0; i < len; ++i)
  5563. listeners[i].call(self);
  5564. }
  5565. }
  5566. function emitOne(handler, isFn, self, arg1) {
  5567. if (isFn)
  5568. handler.call(self, arg1);
  5569. else {
  5570. var len = handler.length;
  5571. var listeners = arrayClone(handler, len);
  5572. for (var i = 0; i < len; ++i)
  5573. listeners[i].call(self, arg1);
  5574. }
  5575. }
  5576. function emitTwo(handler, isFn, self, arg1, arg2) {
  5577. if (isFn)
  5578. handler.call(self, arg1, arg2);
  5579. else {
  5580. var len = handler.length;
  5581. var listeners = arrayClone(handler, len);
  5582. for (var i = 0; i < len; ++i)
  5583. listeners[i].call(self, arg1, arg2);
  5584. }
  5585. }
  5586. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  5587. if (isFn)
  5588. handler.call(self, arg1, arg2, arg3);
  5589. else {
  5590. var len = handler.length;
  5591. var listeners = arrayClone(handler, len);
  5592. for (var i = 0; i < len; ++i)
  5593. listeners[i].call(self, arg1, arg2, arg3);
  5594. }
  5595. }
  5596. function emitMany(handler, isFn, self, args) {
  5597. if (isFn)
  5598. handler.apply(self, args);
  5599. else {
  5600. var len = handler.length;
  5601. var listeners = arrayClone(handler, len);
  5602. for (var i = 0; i < len; ++i)
  5603. listeners[i].apply(self, args);
  5604. }
  5605. }
  5606. EventEmitter.prototype.emit = function emit(type) {
  5607. var er, handler, len, args, i, events;
  5608. var doError = (type === 'error');
  5609. events = this._events;
  5610. if (events)
  5611. doError = (doError && events.error == null);
  5612. else if (!doError)
  5613. return false;
  5614. // If there is no 'error' event listener then throw.
  5615. if (doError) {
  5616. if (arguments.length > 1)
  5617. er = arguments[1];
  5618. if (er instanceof Error) {
  5619. throw er; // Unhandled 'error' event
  5620. } else {
  5621. // At least give some kind of context to the user
  5622. var err = new Error('Unhandled "error" event. (' + er + ')');
  5623. err.context = er;
  5624. throw err;
  5625. }
  5626. return false;
  5627. }
  5628. handler = events[type];
  5629. if (!handler)
  5630. return false;
  5631. var isFn = typeof handler === 'function';
  5632. len = arguments.length;
  5633. switch (len) {
  5634. // fast cases
  5635. case 1:
  5636. emitNone(handler, isFn, this);
  5637. break;
  5638. case 2:
  5639. emitOne(handler, isFn, this, arguments[1]);
  5640. break;
  5641. case 3:
  5642. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  5643. break;
  5644. case 4:
  5645. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  5646. break;
  5647. // slower
  5648. default:
  5649. args = new Array(len - 1);
  5650. for (i = 1; i < len; i++)
  5651. args[i - 1] = arguments[i];
  5652. emitMany(handler, isFn, this, args);
  5653. }
  5654. return true;
  5655. };
  5656. function _addListener(target, type, listener, prepend) {
  5657. var m;
  5658. var events;
  5659. var existing;
  5660. if (typeof listener !== 'function')
  5661. throw new TypeError('"listener" argument must be a function');
  5662. events = target._events;
  5663. if (!events) {
  5664. events = target._events = objectCreate(null);
  5665. target._eventsCount = 0;
  5666. } else {
  5667. // To avoid recursion in the case that type === "newListener"! Before
  5668. // adding it to the listeners, first emit "newListener".
  5669. if (events.newListener) {
  5670. target.emit('newListener', type,
  5671. listener.listener ? listener.listener : listener);
  5672. // Re-assign `events` because a newListener handler could have caused the
  5673. // this._events to be assigned to a new object
  5674. events = target._events;
  5675. }
  5676. existing = events[type];
  5677. }
  5678. if (!existing) {
  5679. // Optimize the case of one listener. Don't need the extra array object.
  5680. existing = events[type] = listener;
  5681. ++target._eventsCount;
  5682. } else {
  5683. if (typeof existing === 'function') {
  5684. // Adding the second element, need to change to array.
  5685. existing = events[type] =
  5686. prepend ? [listener, existing] : [existing, listener];
  5687. } else {
  5688. // If we've already got an array, just append.
  5689. if (prepend) {
  5690. existing.unshift(listener);
  5691. } else {
  5692. existing.push(listener);
  5693. }
  5694. }
  5695. // Check for listener leak
  5696. if (!existing.warned) {
  5697. m = $getMaxListeners(target);
  5698. if (m && m > 0 && existing.length > m) {
  5699. existing.warned = true;
  5700. var w = new Error('Possible EventEmitter memory leak detected. ' +
  5701. existing.length + ' "' + String(type) + '" listeners ' +
  5702. 'added. Use emitter.setMaxListeners() to ' +
  5703. 'increase limit.');
  5704. w.name = 'MaxListenersExceededWarning';
  5705. w.emitter = target;
  5706. w.type = type;
  5707. w.count = existing.length;
  5708. if (typeof console === 'object' && console.warn) {
  5709. console.warn('%s: %s', w.name, w.message);
  5710. }
  5711. }
  5712. }
  5713. }
  5714. return target;
  5715. }
  5716. EventEmitter.prototype.addListener = function addListener(type, listener) {
  5717. return _addListener(this, type, listener, false);
  5718. };
  5719. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  5720. EventEmitter.prototype.prependListener =
  5721. function prependListener(type, listener) {
  5722. return _addListener(this, type, listener, true);
  5723. };
  5724. function onceWrapper() {
  5725. if (!this.fired) {
  5726. this.target.removeListener(this.type, this.wrapFn);
  5727. this.fired = true;
  5728. switch (arguments.length) {
  5729. case 0:
  5730. return this.listener.call(this.target);
  5731. case 1:
  5732. return this.listener.call(this.target, arguments[0]);
  5733. case 2:
  5734. return this.listener.call(this.target, arguments[0], arguments[1]);
  5735. case 3:
  5736. return this.listener.call(this.target, arguments[0], arguments[1],
  5737. arguments[2]);
  5738. default:
  5739. var args = new Array(arguments.length);
  5740. for (var i = 0; i < args.length; ++i)
  5741. args[i] = arguments[i];
  5742. this.listener.apply(this.target, args);
  5743. }
  5744. }
  5745. }
  5746. function _onceWrap(target, type, listener) {
  5747. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  5748. var wrapped = bind.call(onceWrapper, state);
  5749. wrapped.listener = listener;
  5750. state.wrapFn = wrapped;
  5751. return wrapped;
  5752. }
  5753. EventEmitter.prototype.once = function once(type, listener) {
  5754. if (typeof listener !== 'function')
  5755. throw new TypeError('"listener" argument must be a function');
  5756. this.on(type, _onceWrap(this, type, listener));
  5757. return this;
  5758. };
  5759. EventEmitter.prototype.prependOnceListener =
  5760. function prependOnceListener(type, listener) {
  5761. if (typeof listener !== 'function')
  5762. throw new TypeError('"listener" argument must be a function');
  5763. this.prependListener(type, _onceWrap(this, type, listener));
  5764. return this;
  5765. };
  5766. // Emits a 'removeListener' event if and only if the listener was removed.
  5767. EventEmitter.prototype.removeListener =
  5768. function removeListener(type, listener) {
  5769. var list, events, position, i, originalListener;
  5770. if (typeof listener !== 'function')
  5771. throw new TypeError('"listener" argument must be a function');
  5772. events = this._events;
  5773. if (!events)
  5774. return this;
  5775. list = events[type];
  5776. if (!list)
  5777. return this;
  5778. if (list === listener || list.listener === listener) {
  5779. if (--this._eventsCount === 0)
  5780. this._events = objectCreate(null);
  5781. else {
  5782. delete events[type];
  5783. if (events.removeListener)
  5784. this.emit('removeListener', type, list.listener || listener);
  5785. }
  5786. } else if (typeof list !== 'function') {
  5787. position = -1;
  5788. for (i = list.length - 1; i >= 0; i--) {
  5789. if (list[i] === listener || list[i].listener === listener) {
  5790. originalListener = list[i].listener;
  5791. position = i;
  5792. break;
  5793. }
  5794. }
  5795. if (position < 0)
  5796. return this;
  5797. if (position === 0)
  5798. list.shift();
  5799. else
  5800. spliceOne(list, position);
  5801. if (list.length === 1)
  5802. events[type] = list[0];
  5803. if (events.removeListener)
  5804. this.emit('removeListener', type, originalListener || listener);
  5805. }
  5806. return this;
  5807. };
  5808. EventEmitter.prototype.removeAllListeners =
  5809. function removeAllListeners(type) {
  5810. var listeners, events, i;
  5811. events = this._events;
  5812. if (!events)
  5813. return this;
  5814. // not listening for removeListener, no need to emit
  5815. if (!events.removeListener) {
  5816. if (arguments.length === 0) {
  5817. this._events = objectCreate(null);
  5818. this._eventsCount = 0;
  5819. } else if (events[type]) {
  5820. if (--this._eventsCount === 0)
  5821. this._events = objectCreate(null);
  5822. else
  5823. delete events[type];
  5824. }
  5825. return this;
  5826. }
  5827. // emit removeListener for all listeners on all events
  5828. if (arguments.length === 0) {
  5829. var keys = objectKeys(events);
  5830. var key;
  5831. for (i = 0; i < keys.length; ++i) {
  5832. key = keys[i];
  5833. if (key === 'removeListener') continue;
  5834. this.removeAllListeners(key);
  5835. }
  5836. this.removeAllListeners('removeListener');
  5837. this._events = objectCreate(null);
  5838. this._eventsCount = 0;
  5839. return this;
  5840. }
  5841. listeners = events[type];
  5842. if (typeof listeners === 'function') {
  5843. this.removeListener(type, listeners);
  5844. } else if (listeners) {
  5845. // LIFO order
  5846. for (i = listeners.length - 1; i >= 0; i--) {
  5847. this.removeListener(type, listeners[i]);
  5848. }
  5849. }
  5850. return this;
  5851. };
  5852. function _listeners(target, type, unwrap) {
  5853. var events = target._events;
  5854. if (!events)
  5855. return [];
  5856. var evlistener = events[type];
  5857. if (!evlistener)
  5858. return [];
  5859. if (typeof evlistener === 'function')
  5860. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  5861. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  5862. }
  5863. EventEmitter.prototype.listeners = function listeners(type) {
  5864. return _listeners(this, type, true);
  5865. };
  5866. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  5867. return _listeners(this, type, false);
  5868. };
  5869. EventEmitter.listenerCount = function(emitter, type) {
  5870. if (typeof emitter.listenerCount === 'function') {
  5871. return emitter.listenerCount(type);
  5872. } else {
  5873. return listenerCount.call(emitter, type);
  5874. }
  5875. };
  5876. EventEmitter.prototype.listenerCount = listenerCount;
  5877. function listenerCount(type) {
  5878. var events = this._events;
  5879. if (events) {
  5880. var evlistener = events[type];
  5881. if (typeof evlistener === 'function') {
  5882. return 1;
  5883. } else if (evlistener) {
  5884. return evlistener.length;
  5885. }
  5886. }
  5887. return 0;
  5888. }
  5889. EventEmitter.prototype.eventNames = function eventNames() {
  5890. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  5891. };
  5892. // About 1.5x faster than the two-arg version of Array#splice().
  5893. function spliceOne(list, index) {
  5894. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  5895. list[i] = list[k];
  5896. list.pop();
  5897. }
  5898. function arrayClone(arr, n) {
  5899. var copy = new Array(n);
  5900. for (var i = 0; i < n; ++i)
  5901. copy[i] = arr[i];
  5902. return copy;
  5903. }
  5904. function unwrapListeners(arr) {
  5905. var ret = new Array(arr.length);
  5906. for (var i = 0; i < ret.length; ++i) {
  5907. ret[i] = arr[i].listener || arr[i];
  5908. }
  5909. return ret;
  5910. }
  5911. function objectCreatePolyfill(proto) {
  5912. var F = function() {};
  5913. F.prototype = proto;
  5914. return new F;
  5915. }
  5916. function objectKeysPolyfill(obj) {
  5917. var keys = [];
  5918. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  5919. keys.push(k);
  5920. }
  5921. return k;
  5922. }
  5923. function functionBindPolyfill(context) {
  5924. var fn = this;
  5925. return function () {
  5926. return fn.apply(context, arguments);
  5927. };
  5928. }
  5929. },{}],23:[function(require,module,exports){
  5930. /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  5931. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  5932. var e, m
  5933. var eLen = (nBytes * 8) - mLen - 1
  5934. var eMax = (1 << eLen) - 1
  5935. var eBias = eMax >> 1
  5936. var nBits = -7
  5937. var i = isLE ? (nBytes - 1) : 0
  5938. var d = isLE ? -1 : 1
  5939. var s = buffer[offset + i]
  5940. i += d
  5941. e = s & ((1 << (-nBits)) - 1)
  5942. s >>= (-nBits)
  5943. nBits += eLen
  5944. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5945. m = e & ((1 << (-nBits)) - 1)
  5946. e >>= (-nBits)
  5947. nBits += mLen
  5948. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  5949. if (e === 0) {
  5950. e = 1 - eBias
  5951. } else if (e === eMax) {
  5952. return m ? NaN : ((s ? -1 : 1) * Infinity)
  5953. } else {
  5954. m = m + Math.pow(2, mLen)
  5955. e = e - eBias
  5956. }
  5957. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  5958. }
  5959. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  5960. var e, m, c
  5961. var eLen = (nBytes * 8) - mLen - 1
  5962. var eMax = (1 << eLen) - 1
  5963. var eBias = eMax >> 1
  5964. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  5965. var i = isLE ? 0 : (nBytes - 1)
  5966. var d = isLE ? 1 : -1
  5967. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  5968. value = Math.abs(value)
  5969. if (isNaN(value) || value === Infinity) {
  5970. m = isNaN(value) ? 1 : 0
  5971. e = eMax
  5972. } else {
  5973. e = Math.floor(Math.log(value) / Math.LN2)
  5974. if (value * (c = Math.pow(2, -e)) < 1) {
  5975. e--
  5976. c *= 2
  5977. }
  5978. if (e + eBias >= 1) {
  5979. value += rt / c
  5980. } else {
  5981. value += rt * Math.pow(2, 1 - eBias)
  5982. }
  5983. if (value * c >= 2) {
  5984. e++
  5985. c /= 2
  5986. }
  5987. if (e + eBias >= eMax) {
  5988. m = 0
  5989. e = eMax
  5990. } else if (e + eBias >= 1) {
  5991. m = ((value * c) - 1) * Math.pow(2, mLen)
  5992. e = e + eBias
  5993. } else {
  5994. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  5995. e = 0
  5996. }
  5997. }
  5998. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  5999. e = (e << mLen) | m
  6000. eLen += mLen
  6001. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  6002. buffer[offset + i - d] |= s * 128
  6003. }
  6004. },{}],24:[function(require,module,exports){
  6005. if (typeof Object.create === 'function') {
  6006. // implementation from standard node.js 'util' module
  6007. module.exports = function inherits(ctor, superCtor) {
  6008. if (superCtor) {
  6009. ctor.super_ = superCtor
  6010. ctor.prototype = Object.create(superCtor.prototype, {
  6011. constructor: {
  6012. value: ctor,
  6013. enumerable: false,
  6014. writable: true,
  6015. configurable: true
  6016. }
  6017. })
  6018. }
  6019. };
  6020. } else {
  6021. // old school shim for old browsers
  6022. module.exports = function inherits(ctor, superCtor) {
  6023. if (superCtor) {
  6024. ctor.super_ = superCtor
  6025. var TempCtor = function () {}
  6026. TempCtor.prototype = superCtor.prototype
  6027. ctor.prototype = new TempCtor()
  6028. ctor.prototype.constructor = ctor
  6029. }
  6030. }
  6031. }
  6032. },{}],25:[function(require,module,exports){
  6033. "use strict";
  6034. Object.defineProperty(exports, "__esModule", { value: true });
  6035. var TreeNode = /** @class */ (function () {
  6036. function TreeNode(key, value) {
  6037. this.color = true;
  6038. this.key = undefined;
  6039. this.value = undefined;
  6040. this.parent = undefined;
  6041. this.brother = undefined;
  6042. this.leftChild = undefined;
  6043. this.rightChild = undefined;
  6044. this.key = key;
  6045. this.value = value;
  6046. }
  6047. TreeNode.prototype.rotateLeft = function () {
  6048. var PP = this.parent;
  6049. var PB = this.brother;
  6050. var F = this.leftChild;
  6051. var V = this.rightChild;
  6052. if (!V)
  6053. throw new Error("unknown error");
  6054. var R = V.leftChild;
  6055. var X = V.rightChild;
  6056. if (PP) {
  6057. if (PP.leftChild === this)
  6058. PP.leftChild = V;
  6059. else if (PP.rightChild === this)
  6060. PP.rightChild = V;
  6061. }
  6062. V.parent = PP;
  6063. V.brother = PB;
  6064. V.leftChild = this;
  6065. V.rightChild = X;
  6066. if (PB)
  6067. PB.brother = V;
  6068. this.parent = V;
  6069. this.brother = X;
  6070. this.leftChild = F;
  6071. this.rightChild = R;
  6072. if (X) {
  6073. X.parent = V;
  6074. X.brother = this;
  6075. }
  6076. if (F) {
  6077. F.parent = this;
  6078. F.brother = R;
  6079. }
  6080. if (R) {
  6081. R.parent = this;
  6082. R.brother = F;
  6083. }
  6084. return V;
  6085. };
  6086. TreeNode.prototype.rotateRight = function () {
  6087. var PP = this.parent;
  6088. var PB = this.brother;
  6089. var F = this.leftChild;
  6090. if (!F)
  6091. throw new Error("unknown error");
  6092. var V = this.rightChild;
  6093. var D = F.leftChild;
  6094. var K = F.rightChild;
  6095. if (PP) {
  6096. if (PP.leftChild === this)
  6097. PP.leftChild = F;
  6098. else if (PP.rightChild === this)
  6099. PP.rightChild = F;
  6100. }
  6101. F.parent = PP;
  6102. F.brother = PB;
  6103. F.leftChild = D;
  6104. F.rightChild = this;
  6105. if (PB)
  6106. PB.brother = F;
  6107. if (D) {
  6108. D.parent = F;
  6109. D.brother = this;
  6110. }
  6111. this.parent = F;
  6112. this.brother = D;
  6113. this.leftChild = K;
  6114. this.rightChild = V;
  6115. if (K) {
  6116. K.parent = this;
  6117. K.brother = V;
  6118. }
  6119. if (V) {
  6120. V.parent = this;
  6121. V.brother = K;
  6122. }
  6123. return F;
  6124. };
  6125. TreeNode.prototype.remove = function () {
  6126. if (this.leftChild || this.rightChild)
  6127. throw new Error("can only remove leaf node");
  6128. if (this.parent) {
  6129. if (this === this.parent.leftChild)
  6130. this.parent.leftChild = undefined;
  6131. else if (this === this.parent.rightChild)
  6132. this.parent.rightChild = undefined;
  6133. }
  6134. if (this.brother)
  6135. this.brother.brother = undefined;
  6136. this.key = undefined;
  6137. this.value = undefined;
  6138. this.parent = undefined;
  6139. this.brother = undefined;
  6140. };
  6141. TreeNode.TreeNodeColorType = {
  6142. red: true,
  6143. black: false
  6144. };
  6145. return TreeNode;
  6146. }());
  6147. Object.freeze(TreeNode);
  6148. exports.default = TreeNode;
  6149. },{}],26:[function(require,module,exports){
  6150. "use strict";
  6151. var __generator = (this && this.__generator) || function (thisArg, body) {
  6152. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  6153. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  6154. function verb(n) { return function (v) { return step([n, v]); }; }
  6155. function step(op) {
  6156. if (f) throw new TypeError("Generator is already executing.");
  6157. while (_) try {
  6158. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  6159. if (y = 0, t) op = [op[0] & 2, t.value];
  6160. switch (op[0]) {
  6161. case 0: case 1: t = op; break;
  6162. case 4: _.label++; return { value: op[1], done: false };
  6163. case 5: _.label++; y = op[1]; op = [0]; continue;
  6164. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  6165. default:
  6166. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  6167. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  6168. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  6169. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  6170. if (t[2]) _.ops.pop();
  6171. _.trys.pop(); continue;
  6172. }
  6173. op = body.call(thisArg, _);
  6174. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  6175. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  6176. }
  6177. };
  6178. Object.defineProperty(exports, "__esModule", { value: true });
  6179. Deque.sigma = 3; // growth factor
  6180. Deque.bucketSize = 5000;
  6181. function Deque(container) {
  6182. var _this = this;
  6183. if (container === void 0) { container = []; }
  6184. var map = [];
  6185. var first = 0;
  6186. var curFirst = 0;
  6187. var last = 0;
  6188. var curLast = 0;
  6189. var bucketNum = 0;
  6190. var len = 0;
  6191. this.size = function () {
  6192. return len;
  6193. };
  6194. this.empty = function () {
  6195. return len === 0;
  6196. };
  6197. this.clear = function () {
  6198. first = last = curFirst = curLast = bucketNum = len = 0;
  6199. reAllocate.call(this, Deque.bucketSize);
  6200. len = 0;
  6201. };
  6202. this.front = function () {
  6203. return map[first][curFirst];
  6204. };
  6205. this.back = function () {
  6206. return map[last][curLast];
  6207. };
  6208. this.forEach = function (callback) {
  6209. if (this.empty())
  6210. return;
  6211. var index = 0;
  6212. if (first === last) {
  6213. for (var i = curFirst; i <= curLast; ++i) {
  6214. callback(map[first][i], index++);
  6215. }
  6216. return;
  6217. }
  6218. for (var i = curFirst; i < Deque.bucketSize; ++i) {
  6219. callback(map[first][i], index++);
  6220. }
  6221. for (var i = first + 1; i < last; ++i) {
  6222. for (var j = 0; j < Deque.bucketSize; ++j) {
  6223. callback(map[i][j], index++);
  6224. }
  6225. }
  6226. for (var i = 0; i <= curLast; ++i) {
  6227. callback(map[last][i], index++);
  6228. }
  6229. };
  6230. var getElementIndex = function (pos) {
  6231. var curFirstIndex = first * Deque.bucketSize + curFirst;
  6232. var curNodeIndex = curFirstIndex + pos;
  6233. var curLastIndex = last * Deque.bucketSize + curLast;
  6234. if (curNodeIndex < curFirstIndex || curNodeIndex > curLastIndex)
  6235. throw new Error("pos should more than 0 and less than queue's size");
  6236. var curNodeBucketIndex = Math.floor(curNodeIndex / Deque.bucketSize);
  6237. var curNodePointerIndex = curNodeIndex % Deque.bucketSize;
  6238. return { curNodeBucketIndex: curNodeBucketIndex, curNodePointerIndex: curNodePointerIndex };
  6239. };
  6240. /**
  6241. * @param pos index from 0 to size - 1
  6242. */
  6243. this.getElementByPos = function (pos) {
  6244. var _a = getElementIndex(pos), curNodeBucketIndex = _a.curNodeBucketIndex, curNodePointerIndex = _a.curNodePointerIndex;
  6245. return map[curNodeBucketIndex][curNodePointerIndex];
  6246. };
  6247. this.eraseElementByPos = function (pos) {
  6248. var _this = this;
  6249. if (pos < 0 || pos > len)
  6250. throw new Error("pos should more than 0 and less than queue's size");
  6251. if (pos === 0)
  6252. this.popFront();
  6253. else if (pos === this.size())
  6254. this.popBack();
  6255. else {
  6256. var arr = [];
  6257. for (var i = pos + 1; i < len; ++i) {
  6258. arr.push(this.getElementByPos(i));
  6259. }
  6260. this.cut(pos);
  6261. this.popBack();
  6262. arr.forEach(function (element) { return _this.pushBack(element); });
  6263. }
  6264. };
  6265. this.eraseElementByValue = function (value) {
  6266. if (this.empty())
  6267. return;
  6268. var arr = [];
  6269. this.forEach(function (element) {
  6270. if (element !== value) {
  6271. arr.push(element);
  6272. }
  6273. });
  6274. var _len = arr.length;
  6275. for (var i = 0; i < _len; ++i)
  6276. this.setElementByPos(i, arr[i]);
  6277. this.cut(_len - 1);
  6278. };
  6279. var reAllocate = function (originalSize) {
  6280. var newMap = [];
  6281. var needSize = originalSize * Deque.sigma;
  6282. var newBucketNum = Math.max(Math.ceil(needSize / Deque.bucketSize), 2);
  6283. for (var i = 0; i < newBucketNum; ++i) {
  6284. newMap.push(new Array(Deque.bucketSize));
  6285. }
  6286. var needBucketNum = Math.ceil(originalSize / Deque.bucketSize);
  6287. var newFirst = Math.floor(newBucketNum / 2) - Math.floor(needBucketNum / 2);
  6288. var newLast = newFirst, newCurLast = 0;
  6289. if (this.size()) {
  6290. for (var i = 0; i < needBucketNum; ++i) {
  6291. for (var j = 0; j < Deque.bucketSize; ++j) {
  6292. newMap[newFirst + i][j] = this.front();
  6293. this.popFront();
  6294. if (this.empty()) {
  6295. newLast = newFirst + i;
  6296. newCurLast = j;
  6297. break;
  6298. }
  6299. }
  6300. if (this.empty())
  6301. break;
  6302. }
  6303. }
  6304. map = newMap;
  6305. first = newFirst;
  6306. curFirst = 0;
  6307. last = newLast;
  6308. curLast = newCurLast;
  6309. bucketNum = newBucketNum;
  6310. len = originalSize;
  6311. };
  6312. this.pushBack = function (element) {
  6313. if (!this.empty()) {
  6314. if (last === bucketNum - 1 && curLast === Deque.bucketSize - 1) {
  6315. reAllocate.call(this, this.size());
  6316. }
  6317. if (curLast < Deque.bucketSize - 1) {
  6318. ++curLast;
  6319. }
  6320. else if (last < bucketNum - 1) {
  6321. ++last;
  6322. curLast = 0;
  6323. }
  6324. }
  6325. ++len;
  6326. map[last][curLast] = element;
  6327. };
  6328. this.popBack = function () {
  6329. if (this.empty())
  6330. return;
  6331. if (this.size() !== 1) {
  6332. if (curLast > 0) {
  6333. --curLast;
  6334. }
  6335. else if (first < last) {
  6336. --last;
  6337. curLast = Deque.bucketSize - 1;
  6338. }
  6339. }
  6340. if (len > 0)
  6341. --len;
  6342. };
  6343. this.setElementByPos = function (pos, element) {
  6344. var _a = getElementIndex(pos), curNodeBucketIndex = _a.curNodeBucketIndex, curNodePointerIndex = _a.curNodePointerIndex;
  6345. map[curNodeBucketIndex][curNodePointerIndex] = element;
  6346. };
  6347. /**
  6348. * @param {number} pos insert element before pos, should in [0, queue.size]
  6349. * @param {any} element the element you want to insert
  6350. * @param {number} [num = 1] the nums you want to insert
  6351. */
  6352. this.insert = function (pos, element, num) {
  6353. var _this = this;
  6354. if (num === void 0) { num = 1; }
  6355. if (pos === 0) {
  6356. while (num--)
  6357. this.pushFront(element);
  6358. }
  6359. else if (pos === this.size()) {
  6360. while (num--)
  6361. this.pushBack(element);
  6362. }
  6363. else {
  6364. var arr = [];
  6365. for (var i = pos; i < len; ++i) {
  6366. arr.push(this.getElementByPos(i));
  6367. }
  6368. this.cut(pos - 1);
  6369. for (var i = 0; i < num; ++i)
  6370. this.pushBack(element);
  6371. arr.forEach(function (element) { return _this.pushBack(element); });
  6372. }
  6373. };
  6374. this.find = function (element) {
  6375. if (first === last) {
  6376. for (var i = curFirst; i <= curLast; ++i) {
  6377. if (map[first][i] === element)
  6378. return true;
  6379. }
  6380. return false;
  6381. }
  6382. for (var i = curFirst; i < Deque.bucketSize; ++i) {
  6383. if (map[first][i] === element)
  6384. return true;
  6385. }
  6386. for (var i = first + 1; i < last; ++i) {
  6387. for (var j = 0; j < Deque.bucketSize; ++j) {
  6388. if (map[i][j] === element)
  6389. return true;
  6390. }
  6391. }
  6392. for (var i = 0; i <= curLast; ++i) {
  6393. if (map[last][i] === element)
  6394. return true;
  6395. }
  6396. return false;
  6397. };
  6398. this.reverse = function () {
  6399. var l = 0, r = len - 1;
  6400. while (l < r) {
  6401. var tmp = this.getElementByPos(l);
  6402. this.setElementByPos(l, this.getElementByPos(r));
  6403. this.setElementByPos(r, tmp);
  6404. ++l;
  6405. --r;
  6406. }
  6407. };
  6408. this.unique = function () {
  6409. if (this.empty())
  6410. return;
  6411. var arr = [];
  6412. var pre = this.front();
  6413. this.forEach(function (element, index) {
  6414. if (index === 0 || element !== pre) {
  6415. arr.push(element);
  6416. pre = element;
  6417. }
  6418. });
  6419. for (var i = 0; i < len; ++i) {
  6420. this.setElementByPos(i, arr[i]);
  6421. }
  6422. this.cut(arr.length - 1);
  6423. };
  6424. this.sort = function (cmp) {
  6425. var arr = [];
  6426. this.forEach(function (element) {
  6427. arr.push(element);
  6428. });
  6429. arr.sort(cmp);
  6430. for (var i = 0; i < len; ++i)
  6431. this.setElementByPos(i, arr[i]);
  6432. };
  6433. this.pushFront = function (element) {
  6434. if (!this.empty()) {
  6435. if (first === 0 && curFirst === 0) {
  6436. reAllocate.call(this, this.size());
  6437. }
  6438. if (curFirst > 0) {
  6439. --curFirst;
  6440. }
  6441. else if (first > 0) {
  6442. --first;
  6443. curFirst = Deque.bucketSize - 1;
  6444. }
  6445. }
  6446. ++len;
  6447. map[first][curFirst] = element;
  6448. };
  6449. this.popFront = function () {
  6450. if (this.empty())
  6451. return;
  6452. if (this.size() !== 1) {
  6453. if (curFirst < Deque.bucketSize - 1) {
  6454. ++curFirst;
  6455. }
  6456. else if (first < last) {
  6457. ++first;
  6458. curFirst = 0;
  6459. }
  6460. }
  6461. if (len > 0)
  6462. --len;
  6463. };
  6464. /**
  6465. * reduces memory usage by freeing unused memory
  6466. */
  6467. this.shrinkToFit = function () {
  6468. var _this = this;
  6469. var arr = [];
  6470. this.forEach(function (element) {
  6471. arr.push(element);
  6472. });
  6473. var _len = arr.length;
  6474. map = [];
  6475. var bucketNum = Math.ceil(_len / Deque.bucketSize);
  6476. for (var i = 0; i < bucketNum; ++i) {
  6477. map.push(new Array(Deque.bucketSize));
  6478. }
  6479. this.clear();
  6480. arr.forEach(function (element) { return _this.pushBack(element); });
  6481. };
  6482. /**
  6483. * @param pos cut elements after pos
  6484. */
  6485. this.cut = function (pos) {
  6486. if (pos < 0) {
  6487. this.clear();
  6488. return;
  6489. }
  6490. var _a = getElementIndex(pos), curNodeBucketIndex = _a.curNodeBucketIndex, curNodePointerIndex = _a.curNodePointerIndex;
  6491. last = curNodeBucketIndex;
  6492. curLast = curNodePointerIndex;
  6493. len = pos + 1;
  6494. };
  6495. this[Symbol.iterator] = function () {
  6496. return (function () {
  6497. var i, i, i, j, i;
  6498. return __generator(this, function (_a) {
  6499. switch (_a.label) {
  6500. case 0:
  6501. if (len === 0)
  6502. return [2 /*return*/];
  6503. if (!(first === last)) return [3 /*break*/, 5];
  6504. i = curFirst;
  6505. _a.label = 1;
  6506. case 1:
  6507. if (!(i <= curLast)) return [3 /*break*/, 4];
  6508. return [4 /*yield*/, map[first][i]];
  6509. case 2:
  6510. _a.sent();
  6511. _a.label = 3;
  6512. case 3:
  6513. ++i;
  6514. return [3 /*break*/, 1];
  6515. case 4: return [2 /*return*/];
  6516. case 5:
  6517. i = curFirst;
  6518. _a.label = 6;
  6519. case 6:
  6520. if (!(i < Deque.bucketSize)) return [3 /*break*/, 9];
  6521. return [4 /*yield*/, map[first][i]];
  6522. case 7:
  6523. _a.sent();
  6524. _a.label = 8;
  6525. case 8:
  6526. ++i;
  6527. return [3 /*break*/, 6];
  6528. case 9:
  6529. i = first + 1;
  6530. _a.label = 10;
  6531. case 10:
  6532. if (!(i < last)) return [3 /*break*/, 15];
  6533. j = 0;
  6534. _a.label = 11;
  6535. case 11:
  6536. if (!(j < Deque.bucketSize)) return [3 /*break*/, 14];
  6537. return [4 /*yield*/, map[i][j]];
  6538. case 12:
  6539. _a.sent();
  6540. _a.label = 13;
  6541. case 13:
  6542. ++j;
  6543. return [3 /*break*/, 11];
  6544. case 14:
  6545. ++i;
  6546. return [3 /*break*/, 10];
  6547. case 15:
  6548. i = 0;
  6549. _a.label = 16;
  6550. case 16:
  6551. if (!(i <= curLast)) return [3 /*break*/, 19];
  6552. return [4 /*yield*/, map[last][i]];
  6553. case 17:
  6554. _a.sent();
  6555. _a.label = 18;
  6556. case 18:
  6557. ++i;
  6558. return [3 /*break*/, 16];
  6559. case 19: return [2 /*return*/];
  6560. }
  6561. });
  6562. })();
  6563. };
  6564. (function () {
  6565. var _len = Deque.bucketSize;
  6566. if (container.size) {
  6567. _len = container.size();
  6568. }
  6569. else if (container.length) {
  6570. _len = container.length;
  6571. }
  6572. var needSize = _len * Deque.sigma;
  6573. bucketNum = Math.ceil(needSize / Deque.bucketSize);
  6574. bucketNum = Math.max(bucketNum, 3);
  6575. for (var i = 0; i < bucketNum; ++i) {
  6576. map.push(new Array(Deque.bucketSize));
  6577. }
  6578. var needBucketNum = Math.ceil(_len / Deque.bucketSize);
  6579. first = Math.floor(bucketNum / 2) - Math.floor(needBucketNum / 2);
  6580. last = first;
  6581. container.forEach(function (element) { return _this.pushBack(element); });
  6582. })();
  6583. Object.freeze(this);
  6584. }
  6585. Object.freeze(Deque);
  6586. exports.default = Deque;
  6587. },{}],27:[function(require,module,exports){
  6588. "use strict";
  6589. var __generator = (this && this.__generator) || function (thisArg, body) {
  6590. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  6591. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  6592. function verb(n) { return function (v) { return step([n, v]); }; }
  6593. function step(op) {
  6594. if (f) throw new TypeError("Generator is already executing.");
  6595. while (_) try {
  6596. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  6597. if (y = 0, t) op = [op[0] & 2, t.value];
  6598. switch (op[0]) {
  6599. case 0: case 1: t = op; break;
  6600. case 4: _.label++; return { value: op[1], done: false };
  6601. case 5: _.label++; y = op[1]; op = [0]; continue;
  6602. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  6603. default:
  6604. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  6605. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  6606. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  6607. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  6608. if (t[2]) _.ops.pop();
  6609. _.trys.pop(); continue;
  6610. }
  6611. op = body.call(thisArg, _);
  6612. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  6613. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  6614. }
  6615. };
  6616. var __values = (this && this.__values) || function(o) {
  6617. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  6618. if (m) return m.call(o);
  6619. if (o && typeof o.length === "number") return {
  6620. next: function () {
  6621. if (o && i >= o.length) o = void 0;
  6622. return { value: o && o[i++], done: !o };
  6623. }
  6624. };
  6625. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  6626. };
  6627. Object.defineProperty(exports, "__esModule", { value: true });
  6628. var LinkList_1 = require("../LinkList/LinkList");
  6629. var Map_1 = require("../Map/Map");
  6630. HashMap.initSize = (1 << 4);
  6631. HashMap.maxSize = (1 << 30);
  6632. HashMap.sigma = 0.75; // default load factor
  6633. HashMap.treeifyThreshold = 8;
  6634. HashMap.untreeifyThreshold = 6;
  6635. HashMap.minTreeifySize = 64;
  6636. /**
  6637. * Note that resize is a time-consuming operation, please try to determine the number of buckets before use.
  6638. * @param container Initialize the container
  6639. * @param initBucketNum Initialize the bucket num, must be 2 to the power of n
  6640. * @param hashFunc Function to map elements to numbers
  6641. * @constructor
  6642. */
  6643. function HashMap(container, initBucketNum, hashFunc) {
  6644. var _this = this;
  6645. if (container === void 0) { container = []; }
  6646. if (initBucketNum === void 0) { initBucketNum = HashMap.initSize; }
  6647. hashFunc = hashFunc || (function (x) {
  6648. var e_1, _a;
  6649. var hashCode = 0;
  6650. var str = '';
  6651. if (typeof x === "number") {
  6652. hashCode = Math.floor(x);
  6653. hashCode = ((hashCode << 5) - hashCode);
  6654. hashCode = hashCode & hashCode;
  6655. }
  6656. else {
  6657. if (typeof x !== "string") {
  6658. str = JSON.stringify(x);
  6659. }
  6660. else
  6661. str = x;
  6662. try {
  6663. for (var str_1 = __values(str), str_1_1 = str_1.next(); !str_1_1.done; str_1_1 = str_1.next()) {
  6664. var ch = str_1_1.value;
  6665. var character = ch.charCodeAt(0);
  6666. hashCode = ((hashCode << 5) - hashCode) + character;
  6667. hashCode = hashCode & hashCode;
  6668. }
  6669. }
  6670. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  6671. finally {
  6672. try {
  6673. if (str_1_1 && !str_1_1.done && (_a = str_1.return)) _a.call(str_1);
  6674. }
  6675. finally { if (e_1) throw e_1.error; }
  6676. }
  6677. }
  6678. hashCode ^= (hashCode >>> 16);
  6679. return hashCode;
  6680. });
  6681. if ((initBucketNum & (initBucketNum - 1)) !== 0) {
  6682. throw new Error("initBucketNum must be 2 to the power of n");
  6683. }
  6684. var len = 0;
  6685. var hashTable = [];
  6686. var bucketNum = Math.max(HashMap.initSize, Math.min(HashMap.maxSize, initBucketNum));
  6687. this.size = function () {
  6688. return len;
  6689. };
  6690. this.empty = function () {
  6691. return len === 0;
  6692. };
  6693. this.clear = function () {
  6694. len = 0;
  6695. bucketNum = initBucketNum;
  6696. hashTable = [];
  6697. };
  6698. this.forEach = function (callback) {
  6699. var index = 0;
  6700. hashTable.forEach(function (container) {
  6701. container.forEach(function (element) {
  6702. callback(element, index++);
  6703. });
  6704. });
  6705. };
  6706. var reAllocate = function (originalBucketNum) {
  6707. if (originalBucketNum >= HashMap.maxSize)
  6708. return;
  6709. bucketNum = originalBucketNum * 2;
  6710. var newHashTable = [];
  6711. hashTable.forEach(function (container, index) {
  6712. if (container.empty())
  6713. return;
  6714. if (container instanceof LinkList_1.default && container.size() === 1) {
  6715. var _a = container.front(), key = _a.key, value = _a.value;
  6716. newHashTable[hashFunc(key) & (bucketNum - 1)] = new LinkList_1.default([{
  6717. key: key,
  6718. value: value
  6719. }]);
  6720. }
  6721. else if (container instanceof Map_1.default) {
  6722. var lowList_1 = new LinkList_1.default();
  6723. var highList_1 = new LinkList_1.default();
  6724. container.forEach(function (pair) {
  6725. var hashCode = hashFunc(pair.key);
  6726. if ((hashCode & originalBucketNum) === 0) {
  6727. lowList_1.pushBack(pair);
  6728. }
  6729. else
  6730. highList_1.pushBack(pair);
  6731. });
  6732. if (lowList_1.size() > HashMap.untreeifyThreshold)
  6733. newHashTable[index] = new Map_1.default(lowList_1);
  6734. else if (lowList_1.size())
  6735. newHashTable[index] = lowList_1;
  6736. if (highList_1.size() > HashMap.untreeifyThreshold)
  6737. newHashTable[index + originalBucketNum] = new Map_1.default(highList_1);
  6738. else if (highList_1.size())
  6739. newHashTable[index + originalBucketNum] = highList_1;
  6740. }
  6741. else {
  6742. var lowList_2 = new LinkList_1.default();
  6743. var highList_2 = new LinkList_1.default();
  6744. container.forEach(function (pair) {
  6745. var hashCode = hashFunc(pair.key);
  6746. if ((hashCode & originalBucketNum) === 0) {
  6747. lowList_2.pushBack(pair);
  6748. }
  6749. else
  6750. highList_2.pushBack(pair);
  6751. });
  6752. if (lowList_2.size())
  6753. newHashTable[index] = lowList_2;
  6754. if (highList_2.size())
  6755. newHashTable[index + originalBucketNum] = highList_2;
  6756. }
  6757. hashTable[index].clear();
  6758. });
  6759. hashTable = newHashTable;
  6760. };
  6761. this.setElement = function (key, value) {
  6762. var e_2, _a;
  6763. if (key === null || key === undefined) {
  6764. throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
  6765. }
  6766. if (value === null || value === undefined) {
  6767. this.eraseElementByKey(key);
  6768. return;
  6769. }
  6770. var index = hashFunc(key) & (bucketNum - 1);
  6771. if (!hashTable[index]) {
  6772. ++len;
  6773. hashTable[index] = new LinkList_1.default([{ key: key, value: value }]);
  6774. }
  6775. else {
  6776. var preSize = hashTable[index].size();
  6777. if (hashTable[index] instanceof LinkList_1.default) {
  6778. try {
  6779. for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {
  6780. var pair = _c.value;
  6781. if (pair.key === key) {
  6782. pair.value = value;
  6783. return;
  6784. }
  6785. }
  6786. }
  6787. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  6788. finally {
  6789. try {
  6790. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  6791. }
  6792. finally { if (e_2) throw e_2.error; }
  6793. }
  6794. hashTable[index].pushBack({
  6795. key: key,
  6796. value: value,
  6797. });
  6798. if (hashTable[index].size() >= HashMap.treeifyThreshold) {
  6799. hashTable[index] = new Map_1.default(hashTable[index]);
  6800. }
  6801. }
  6802. else
  6803. hashTable[index].setElement(key, value);
  6804. var curSize = hashTable[index].size();
  6805. len += curSize - preSize;
  6806. }
  6807. if (len > bucketNum * HashMap.sigma) {
  6808. reAllocate.call(this, bucketNum);
  6809. }
  6810. };
  6811. this.getElementByKey = function (key) {
  6812. var e_3, _a;
  6813. var index = hashFunc(key) & (bucketNum - 1);
  6814. if (!hashTable[index])
  6815. return undefined;
  6816. if (hashTable[index] instanceof Map_1.default)
  6817. return hashTable[index].getElementByKey(key);
  6818. else {
  6819. try {
  6820. for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {
  6821. var pair = _c.value;
  6822. if (pair.key === key)
  6823. return pair.value;
  6824. }
  6825. }
  6826. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  6827. finally {
  6828. try {
  6829. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  6830. }
  6831. finally { if (e_3) throw e_3.error; }
  6832. }
  6833. return undefined;
  6834. }
  6835. };
  6836. this.eraseElementByKey = function (key) {
  6837. var e_4, _a;
  6838. var index = hashFunc(key) & (bucketNum - 1);
  6839. if (!hashTable[index])
  6840. return;
  6841. var preSize = hashTable[index].size();
  6842. if (hashTable[index] instanceof Map_1.default) {
  6843. hashTable[index].eraseElementByKey(key);
  6844. if (hashTable[index].size() <= HashMap.untreeifyThreshold) {
  6845. hashTable[index] = new LinkList_1.default(hashTable[index]);
  6846. }
  6847. }
  6848. else {
  6849. var pos = -1;
  6850. try {
  6851. for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {
  6852. var pair = _c.value;
  6853. ++pos;
  6854. if (pair.key === key) {
  6855. hashTable[index].eraseElementByPos(pos);
  6856. break;
  6857. }
  6858. }
  6859. }
  6860. catch (e_4_1) { e_4 = { error: e_4_1 }; }
  6861. finally {
  6862. try {
  6863. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  6864. }
  6865. finally { if (e_4) throw e_4.error; }
  6866. }
  6867. }
  6868. var curSize = hashTable[index].size();
  6869. len += curSize - preSize;
  6870. };
  6871. this.find = function (key) {
  6872. var e_5, _a;
  6873. var index = hashFunc(key) & (bucketNum - 1);
  6874. if (!hashTable[index])
  6875. return false;
  6876. if (hashTable[index] instanceof Map_1.default)
  6877. return hashTable[index].find(key);
  6878. try {
  6879. for (var _b = __values(hashTable[index]), _c = _b.next(); !_c.done; _c = _b.next()) {
  6880. var pair = _c.value;
  6881. if (pair.key === key)
  6882. return true;
  6883. }
  6884. }
  6885. catch (e_5_1) { e_5 = { error: e_5_1 }; }
  6886. finally {
  6887. try {
  6888. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  6889. }
  6890. finally { if (e_5) throw e_5.error; }
  6891. }
  6892. return false;
  6893. };
  6894. this[Symbol.iterator] = function () {
  6895. return (function () {
  6896. var index, _a, _b, pair, e_6_1;
  6897. var e_6, _c;
  6898. return __generator(this, function (_d) {
  6899. switch (_d.label) {
  6900. case 0:
  6901. index = 0;
  6902. _d.label = 1;
  6903. case 1:
  6904. if (!(index < bucketNum)) return [3 /*break*/, 10];
  6905. while (index < bucketNum && !hashTable[index])
  6906. ++index;
  6907. if (index >= bucketNum)
  6908. return [3 /*break*/, 10];
  6909. _d.label = 2;
  6910. case 2:
  6911. _d.trys.push([2, 7, 8, 9]);
  6912. _a = (e_6 = void 0, __values(hashTable[index])), _b = _a.next();
  6913. _d.label = 3;
  6914. case 3:
  6915. if (!!_b.done) return [3 /*break*/, 6];
  6916. pair = _b.value;
  6917. return [4 /*yield*/, pair];
  6918. case 4:
  6919. _d.sent();
  6920. _d.label = 5;
  6921. case 5:
  6922. _b = _a.next();
  6923. return [3 /*break*/, 3];
  6924. case 6: return [3 /*break*/, 9];
  6925. case 7:
  6926. e_6_1 = _d.sent();
  6927. e_6 = { error: e_6_1 };
  6928. return [3 /*break*/, 9];
  6929. case 8:
  6930. try {
  6931. if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
  6932. }
  6933. finally { if (e_6) throw e_6.error; }
  6934. return [7 /*endfinally*/];
  6935. case 9:
  6936. ++index;
  6937. return [3 /*break*/, 1];
  6938. case 10: return [2 /*return*/];
  6939. }
  6940. });
  6941. })();
  6942. };
  6943. container.forEach(function (_a) {
  6944. var key = _a.key, value = _a.value;
  6945. return _this.setElement(key, value);
  6946. });
  6947. Object.freeze(this);
  6948. }
  6949. Object.freeze(HashMap);
  6950. exports.default = HashMap;
  6951. },{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(require,module,exports){
  6952. "use strict";
  6953. var __generator = (this && this.__generator) || function (thisArg, body) {
  6954. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  6955. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  6956. function verb(n) { return function (v) { return step([n, v]); }; }
  6957. function step(op) {
  6958. if (f) throw new TypeError("Generator is already executing.");
  6959. while (_) try {
  6960. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  6961. if (y = 0, t) op = [op[0] & 2, t.value];
  6962. switch (op[0]) {
  6963. case 0: case 1: t = op; break;
  6964. case 4: _.label++; return { value: op[1], done: false };
  6965. case 5: _.label++; y = op[1]; op = [0]; continue;
  6966. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  6967. default:
  6968. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  6969. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  6970. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  6971. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  6972. if (t[2]) _.ops.pop();
  6973. _.trys.pop(); continue;
  6974. }
  6975. op = body.call(thisArg, _);
  6976. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  6977. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  6978. }
  6979. };
  6980. var __values = (this && this.__values) || function(o) {
  6981. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  6982. if (m) return m.call(o);
  6983. if (o && typeof o.length === "number") return {
  6984. next: function () {
  6985. if (o && i >= o.length) o = void 0;
  6986. return { value: o && o[i++], done: !o };
  6987. }
  6988. };
  6989. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  6990. };
  6991. Object.defineProperty(exports, "__esModule", { value: true });
  6992. var Set_1 = require("../Set/Set");
  6993. var LinkList_1 = require("../LinkList/LinkList");
  6994. HashSet.initSize = (1 << 4);
  6995. HashSet.maxSize = (1 << 30);
  6996. HashSet.sigma = 0.75; // default load factor
  6997. HashSet.treeifyThreshold = 8;
  6998. HashSet.untreeifyThreshold = 6;
  6999. HashSet.minTreeifySize = 64;
  7000. /**
  7001. * Note that resize is a time-consuming operation, please try to determine the number of buckets before use.
  7002. * @param container Initialize the container
  7003. * @param initBucketNum Initialize the bucket num
  7004. * @param hashFunc Function to map elements to numbers
  7005. * @constructor
  7006. */
  7007. function HashSet(container, initBucketNum, hashFunc) {
  7008. var _this = this;
  7009. if (container === void 0) { container = []; }
  7010. if (initBucketNum === void 0) { initBucketNum = HashSet.initSize; }
  7011. hashFunc = hashFunc || (function (x) {
  7012. var hashCode = 0;
  7013. var str = '';
  7014. if (typeof x === "number") {
  7015. hashCode = Math.floor(x);
  7016. hashCode = ((hashCode << 5) - hashCode);
  7017. hashCode = hashCode & hashCode;
  7018. }
  7019. else {
  7020. if (typeof x !== "string") {
  7021. str = JSON.stringify(x);
  7022. }
  7023. else
  7024. str = x;
  7025. for (var i = 0; i < str.length; i++) {
  7026. var character = str.charCodeAt(i);
  7027. hashCode = ((hashCode << 5) - hashCode) + character;
  7028. hashCode = hashCode & hashCode;
  7029. }
  7030. }
  7031. hashCode ^= (hashCode >>> 16);
  7032. return hashCode;
  7033. });
  7034. if ((initBucketNum & (initBucketNum - 1)) !== 0) {
  7035. throw new Error("initBucketNum must be 2 to the power of n");
  7036. }
  7037. var len = 0;
  7038. var hashTable = [];
  7039. var bucketNum = Math.max(HashSet.initSize, Math.min(HashSet.maxSize, initBucketNum));
  7040. this.size = function () {
  7041. return len;
  7042. };
  7043. this.empty = function () {
  7044. return len === 0;
  7045. };
  7046. this.clear = function () {
  7047. len = 0;
  7048. bucketNum = initBucketNum;
  7049. hashTable = [];
  7050. };
  7051. this.forEach = function (callback) {
  7052. var index = 0;
  7053. hashTable.forEach(function (container) {
  7054. container.forEach(function (element) {
  7055. callback(element, index++);
  7056. });
  7057. });
  7058. };
  7059. var reAllocate = function (originalBucketNum) {
  7060. if (originalBucketNum >= HashSet.maxSize)
  7061. return;
  7062. bucketNum = originalBucketNum * 2;
  7063. var newHashTable = [];
  7064. hashTable.forEach(function (container, index) {
  7065. if (container.empty())
  7066. return;
  7067. if (container instanceof LinkList_1.default && container.size() === 1) {
  7068. var element = container.front();
  7069. if (element === undefined)
  7070. throw new Error("unknown error");
  7071. newHashTable[hashFunc(element) & (bucketNum - 1)] = new LinkList_1.default([element]);
  7072. }
  7073. else if (container instanceof Set_1.default) {
  7074. var lowList_1 = new LinkList_1.default();
  7075. var highList_1 = new LinkList_1.default();
  7076. container.forEach(function (element) {
  7077. var hashCode = hashFunc(element);
  7078. if ((hashCode & originalBucketNum) === 0) {
  7079. lowList_1.pushBack(element);
  7080. }
  7081. else
  7082. highList_1.pushBack(element);
  7083. });
  7084. if (lowList_1.size() > HashSet.untreeifyThreshold)
  7085. newHashTable[index] = new Set_1.default(lowList_1);
  7086. else if (lowList_1.size())
  7087. newHashTable[index] = lowList_1;
  7088. if (highList_1.size() > HashSet.untreeifyThreshold)
  7089. newHashTable[index + originalBucketNum] = new Set_1.default(highList_1);
  7090. else if (highList_1.size())
  7091. newHashTable[index + originalBucketNum] = highList_1;
  7092. }
  7093. else {
  7094. var lowList_2 = new LinkList_1.default();
  7095. var highList_2 = new LinkList_1.default();
  7096. container.forEach(function (element) {
  7097. var hashCode = hashFunc(element);
  7098. if ((hashCode & originalBucketNum) === 0) {
  7099. lowList_2.pushBack(element);
  7100. }
  7101. else
  7102. highList_2.pushBack(element);
  7103. });
  7104. if (lowList_2.size())
  7105. newHashTable[index] = lowList_2;
  7106. if (highList_2.size())
  7107. newHashTable[index + originalBucketNum] = highList_2;
  7108. }
  7109. hashTable[index].clear();
  7110. });
  7111. hashTable = newHashTable;
  7112. };
  7113. this.insert = function (element) {
  7114. if (element === null || element === undefined) {
  7115. throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
  7116. }
  7117. var index = hashFunc(element) & (bucketNum - 1);
  7118. if (!hashTable[index]) {
  7119. hashTable[index] = new LinkList_1.default([element]);
  7120. ++len;
  7121. }
  7122. else {
  7123. var preSize = hashTable[index].size();
  7124. if (hashTable[index] instanceof LinkList_1.default) {
  7125. if (hashTable[index].find(element))
  7126. return;
  7127. hashTable[index].pushBack(element);
  7128. if (hashTable[index].size() >= HashSet.treeifyThreshold) {
  7129. hashTable[index] = new Set_1.default(hashTable[index]);
  7130. }
  7131. }
  7132. else
  7133. hashTable[index].insert(element);
  7134. var curSize = hashTable[index].size();
  7135. len += curSize - preSize;
  7136. }
  7137. if (len > bucketNum * HashSet.sigma) {
  7138. reAllocate.call(this, bucketNum);
  7139. }
  7140. };
  7141. this.eraseElementByValue = function (element) {
  7142. var index = hashFunc(element) & (bucketNum - 1);
  7143. if (!hashTable[index])
  7144. return;
  7145. var preSize = hashTable[index].size();
  7146. hashTable[index].eraseElementByValue(element);
  7147. if (hashTable[index] instanceof Set_1.default) {
  7148. if (hashTable[index].size() <= HashSet.untreeifyThreshold) {
  7149. hashTable[index] = new LinkList_1.default(hashTable[index]);
  7150. }
  7151. }
  7152. var curSize = hashTable[index].size();
  7153. len += curSize - preSize;
  7154. };
  7155. this.find = function (element) {
  7156. var index = hashFunc(element) & (bucketNum - 1);
  7157. if (!hashTable[index])
  7158. return false;
  7159. return hashTable[index].find(element);
  7160. };
  7161. this[Symbol.iterator] = function () {
  7162. return (function () {
  7163. var index, _a, _b, element, e_1_1;
  7164. var e_1, _c;
  7165. return __generator(this, function (_d) {
  7166. switch (_d.label) {
  7167. case 0:
  7168. index = 0;
  7169. _d.label = 1;
  7170. case 1:
  7171. if (!(index < bucketNum)) return [3 /*break*/, 10];
  7172. while (index < bucketNum && !hashTable[index])
  7173. ++index;
  7174. if (index >= bucketNum)
  7175. return [3 /*break*/, 10];
  7176. _d.label = 2;
  7177. case 2:
  7178. _d.trys.push([2, 7, 8, 9]);
  7179. _a = (e_1 = void 0, __values(hashTable[index])), _b = _a.next();
  7180. _d.label = 3;
  7181. case 3:
  7182. if (!!_b.done) return [3 /*break*/, 6];
  7183. element = _b.value;
  7184. return [4 /*yield*/, element];
  7185. case 4:
  7186. _d.sent();
  7187. _d.label = 5;
  7188. case 5:
  7189. _b = _a.next();
  7190. return [3 /*break*/, 3];
  7191. case 6: return [3 /*break*/, 9];
  7192. case 7:
  7193. e_1_1 = _d.sent();
  7194. e_1 = { error: e_1_1 };
  7195. return [3 /*break*/, 9];
  7196. case 8:
  7197. try {
  7198. if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
  7199. }
  7200. finally { if (e_1) throw e_1.error; }
  7201. return [7 /*endfinally*/];
  7202. case 9:
  7203. ++index;
  7204. return [3 /*break*/, 1];
  7205. case 10: return [2 /*return*/];
  7206. }
  7207. });
  7208. })();
  7209. };
  7210. container.forEach(function (element) { return _this.insert(element); });
  7211. Object.freeze(this);
  7212. }
  7213. Object.freeze(HashSet);
  7214. exports.default = HashSet;
  7215. },{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(require,module,exports){
  7216. "use strict";
  7217. var __generator = (this && this.__generator) || function (thisArg, body) {
  7218. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  7219. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  7220. function verb(n) { return function (v) { return step([n, v]); }; }
  7221. function step(op) {
  7222. if (f) throw new TypeError("Generator is already executing.");
  7223. while (_) try {
  7224. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  7225. if (y = 0, t) op = [op[0] & 2, t.value];
  7226. switch (op[0]) {
  7227. case 0: case 1: t = op; break;
  7228. case 4: _.label++; return { value: op[1], done: false };
  7229. case 5: _.label++; y = op[1]; op = [0]; continue;
  7230. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  7231. default:
  7232. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  7233. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  7234. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  7235. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  7236. if (t[2]) _.ops.pop();
  7237. _.trys.pop(); continue;
  7238. }
  7239. op = body.call(thisArg, _);
  7240. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  7241. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  7242. }
  7243. };
  7244. Object.defineProperty(exports, "__esModule", { value: true });
  7245. var LinkNode = /** @class */ (function () {
  7246. function LinkNode(element) {
  7247. this.value = undefined;
  7248. this.pre = undefined;
  7249. this.next = undefined;
  7250. this.value = element;
  7251. }
  7252. return LinkNode;
  7253. }());
  7254. function LinkList(container) {
  7255. var _this = this;
  7256. if (container === void 0) { container = []; }
  7257. var len = 0;
  7258. var head = undefined;
  7259. var tail = undefined;
  7260. this.size = function () {
  7261. return len;
  7262. };
  7263. this.empty = function () {
  7264. return len === 0;
  7265. };
  7266. this.clear = function () {
  7267. head = tail = undefined;
  7268. len = 0;
  7269. };
  7270. this.front = function () {
  7271. return head === null || head === void 0 ? void 0 : head.value;
  7272. };
  7273. this.back = function () {
  7274. return tail === null || tail === void 0 ? void 0 : tail.value;
  7275. };
  7276. this.forEach = function (callback) {
  7277. var curNode = head;
  7278. var index = 0;
  7279. while (curNode) {
  7280. if (curNode.value === undefined)
  7281. throw new Error("unknown error");
  7282. callback(curNode.value, index++);
  7283. curNode = curNode.next;
  7284. }
  7285. };
  7286. this.getElementByPos = function (pos) {
  7287. if (pos < 0 || pos >= len)
  7288. throw new Error("pos must more then 0 and less then the list length");
  7289. var curNode = head;
  7290. while (pos--) {
  7291. if (!curNode)
  7292. break;
  7293. curNode = curNode.next;
  7294. }
  7295. if (!curNode || curNode.value === undefined)
  7296. throw new Error("unknown error");
  7297. return curNode.value;
  7298. };
  7299. this.eraseElementByPos = function (pos) {
  7300. if (pos < 0 || pos >= len)
  7301. throw new Error("erase pos must more then 0 and less then the list length");
  7302. if (pos === 0)
  7303. this.popFront();
  7304. else if (pos === len - 1)
  7305. this.popBack();
  7306. else {
  7307. var curNode = head;
  7308. while (pos--) {
  7309. if (!(curNode === null || curNode === void 0 ? void 0 : curNode.next))
  7310. throw new Error("unknown error");
  7311. curNode = curNode.next;
  7312. }
  7313. if (!curNode || !curNode.pre || !curNode.next) {
  7314. throw new Error("unknown error");
  7315. }
  7316. var pre = curNode.pre;
  7317. var next = curNode.next;
  7318. next.pre = pre;
  7319. pre.next = next;
  7320. if (len > 0)
  7321. --len;
  7322. }
  7323. };
  7324. this.eraseElementByValue = function (value) {
  7325. while (head && head.value === value)
  7326. this.popFront();
  7327. while (tail && tail.value === value)
  7328. this.popBack();
  7329. if (!head)
  7330. return;
  7331. var curNode = head;
  7332. while (curNode) {
  7333. if (curNode.value === value) {
  7334. var pre = curNode.pre;
  7335. var next = curNode.next;
  7336. if (next)
  7337. next.pre = pre;
  7338. if (pre)
  7339. pre.next = next;
  7340. if (len > 0)
  7341. --len;
  7342. }
  7343. curNode = curNode.next;
  7344. }
  7345. };
  7346. this.pushBack = function (element) {
  7347. if (element === null || element === undefined) {
  7348. throw new Error("you can't push null or undefined here");
  7349. }
  7350. ++len;
  7351. var newTail = new LinkNode(element);
  7352. if (!tail) {
  7353. head = tail = newTail;
  7354. }
  7355. else {
  7356. tail.next = newTail;
  7357. newTail.pre = tail;
  7358. tail = newTail;
  7359. }
  7360. };
  7361. this.popBack = function () {
  7362. if (!tail)
  7363. return;
  7364. if (len > 0)
  7365. --len;
  7366. if (!tail)
  7367. return;
  7368. if (head === tail) {
  7369. head = tail = undefined;
  7370. }
  7371. else {
  7372. tail = tail.pre;
  7373. if (tail)
  7374. tail.next = undefined;
  7375. }
  7376. };
  7377. this.setElementByPos = function (pos, element) {
  7378. if (element === null || element === undefined) {
  7379. throw new Error("you can't set null or undefined here");
  7380. }
  7381. if (pos < 0 || pos >= len)
  7382. throw new Error("pos must more then 0 and less then the list length");
  7383. var curNode = head;
  7384. while (pos--) {
  7385. if (!curNode)
  7386. throw new Error("unknown error");
  7387. curNode = curNode.next;
  7388. }
  7389. if (curNode)
  7390. curNode.value = element;
  7391. };
  7392. /**
  7393. * @param {number} pos insert element before pos, should in [0, list.size]
  7394. * @param {any} element the element you want to insert
  7395. * @param {number} [num = 1] the nums you want to insert
  7396. */
  7397. this.insert = function (pos, element, num) {
  7398. if (num === void 0) { num = 1; }
  7399. if (element === null || element === undefined) {
  7400. throw new Error("you can't insert null or undefined here");
  7401. }
  7402. if (pos < 0 || pos > len)
  7403. throw new Error("insert pos must more then 0 and less then or equal to the list length");
  7404. if (num < 0)
  7405. throw new Error("insert size must more than 0");
  7406. if (pos === 0) {
  7407. while (num--)
  7408. this.pushFront(element);
  7409. }
  7410. else if (pos === len) {
  7411. while (num--)
  7412. this.pushBack(element);
  7413. }
  7414. else {
  7415. var curNode = head;
  7416. for (var i = 1; i < pos; ++i) {
  7417. if (!(curNode === null || curNode === void 0 ? void 0 : curNode.next))
  7418. throw new Error("unknown error");
  7419. curNode = curNode === null || curNode === void 0 ? void 0 : curNode.next;
  7420. }
  7421. if (!curNode) {
  7422. throw new Error("unknown error");
  7423. }
  7424. var next = curNode.next;
  7425. len += num;
  7426. while (num--) {
  7427. curNode.next = new LinkNode(element);
  7428. curNode.next.pre = curNode;
  7429. curNode = curNode.next;
  7430. }
  7431. curNode.next = next;
  7432. if (next)
  7433. next.pre = curNode;
  7434. }
  7435. };
  7436. this.find = function (element) {
  7437. var curNode = head;
  7438. while (curNode) {
  7439. if (curNode.value === element)
  7440. return true;
  7441. curNode = curNode.next;
  7442. }
  7443. return false;
  7444. };
  7445. this.reverse = function () {
  7446. var pHead = head;
  7447. var pTail = tail;
  7448. var cnt = 0;
  7449. while (pHead && pTail && cnt * 2 < len) {
  7450. var tmp = pHead.value;
  7451. pHead.value = pTail.value;
  7452. pTail.value = tmp;
  7453. pHead = pHead.next;
  7454. pTail = pTail.pre;
  7455. ++cnt;
  7456. }
  7457. };
  7458. this.unique = function () {
  7459. var curNode = head;
  7460. while (curNode) {
  7461. var tmpNode = curNode;
  7462. while (tmpNode && tmpNode.next && tmpNode.value === tmpNode.next.value) {
  7463. tmpNode = tmpNode.next;
  7464. if (len > 0)
  7465. --len;
  7466. }
  7467. curNode.next = tmpNode.next;
  7468. if (curNode.next)
  7469. curNode.next.pre = curNode;
  7470. curNode = curNode.next;
  7471. }
  7472. };
  7473. this.sort = function (cmp) {
  7474. var arr = [];
  7475. this.forEach(function (element) {
  7476. arr.push(element);
  7477. });
  7478. arr.sort(cmp);
  7479. var curNode = head;
  7480. arr.forEach(function (element) {
  7481. if (curNode) {
  7482. curNode.value = element;
  7483. curNode = curNode.next;
  7484. }
  7485. });
  7486. };
  7487. this.pushFront = function (element) {
  7488. if (element === null || element === undefined) {
  7489. throw new Error("you can't push null or undefined here");
  7490. }
  7491. ++len;
  7492. var newHead = new LinkNode(element);
  7493. if (!head) {
  7494. head = tail = newHead;
  7495. }
  7496. else {
  7497. newHead.next = head;
  7498. head.pre = newHead;
  7499. head = newHead;
  7500. }
  7501. };
  7502. this.popFront = function () {
  7503. if (!head)
  7504. return;
  7505. if (len > 0)
  7506. --len;
  7507. if (!head)
  7508. return;
  7509. if (head === tail) {
  7510. head = tail = undefined;
  7511. }
  7512. else {
  7513. head = head.next;
  7514. if (head)
  7515. head.pre = undefined;
  7516. }
  7517. };
  7518. /**
  7519. * merge two sorted lists
  7520. * @param list other list
  7521. */
  7522. this.merge = function (list) {
  7523. var _this = this;
  7524. var curNode = head;
  7525. list.forEach(function (element) {
  7526. while (curNode && curNode.value !== undefined && curNode.value <= element) {
  7527. curNode = curNode.next;
  7528. }
  7529. if (curNode === undefined) {
  7530. _this.pushBack(element);
  7531. curNode = tail;
  7532. }
  7533. else if (curNode === head) {
  7534. _this.pushFront(element);
  7535. curNode = head;
  7536. }
  7537. else {
  7538. ++len;
  7539. var pre = curNode.pre;
  7540. if (pre) {
  7541. pre.next = new LinkNode(element);
  7542. pre.next.pre = pre;
  7543. pre.next.next = curNode;
  7544. if (curNode)
  7545. curNode.pre = pre.next;
  7546. }
  7547. }
  7548. });
  7549. };
  7550. this[Symbol.iterator] = function () {
  7551. return (function () {
  7552. var curNode;
  7553. return __generator(this, function (_a) {
  7554. switch (_a.label) {
  7555. case 0:
  7556. curNode = head;
  7557. _a.label = 1;
  7558. case 1:
  7559. if (!(curNode !== undefined)) return [3 /*break*/, 3];
  7560. if (!curNode.value)
  7561. throw new Error("unknown error");
  7562. return [4 /*yield*/, curNode.value];
  7563. case 2:
  7564. _a.sent();
  7565. curNode = curNode.next;
  7566. return [3 /*break*/, 1];
  7567. case 3: return [2 /*return*/];
  7568. }
  7569. });
  7570. })();
  7571. };
  7572. container.forEach(function (element) { return _this.pushBack(element); });
  7573. Object.freeze(this);
  7574. }
  7575. Object.freeze(LinkList);
  7576. exports.default = LinkList;
  7577. },{}],30:[function(require,module,exports){
  7578. "use strict";
  7579. var __generator = (this && this.__generator) || function (thisArg, body) {
  7580. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  7581. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  7582. function verb(n) { return function (v) { return step([n, v]); }; }
  7583. function step(op) {
  7584. if (f) throw new TypeError("Generator is already executing.");
  7585. while (_) try {
  7586. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  7587. if (y = 0, t) op = [op[0] & 2, t.value];
  7588. switch (op[0]) {
  7589. case 0: case 1: t = op; break;
  7590. case 4: _.label++; return { value: op[1], done: false };
  7591. case 5: _.label++; y = op[1]; op = [0]; continue;
  7592. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  7593. default:
  7594. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  7595. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  7596. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  7597. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  7598. if (t[2]) _.ops.pop();
  7599. _.trys.pop(); continue;
  7600. }
  7601. op = body.call(thisArg, _);
  7602. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  7603. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  7604. }
  7605. };
  7606. var __values = (this && this.__values) || function(o) {
  7607. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  7608. if (m) return m.call(o);
  7609. if (o && typeof o.length === "number") return {
  7610. next: function () {
  7611. if (o && i >= o.length) o = void 0;
  7612. return { value: o && o[i++], done: !o };
  7613. }
  7614. };
  7615. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  7616. };
  7617. Object.defineProperty(exports, "__esModule", { value: true });
  7618. var TreeNode_1 = require("../Base/TreeNode");
  7619. function Map(container, cmp) {
  7620. var _this = this;
  7621. if (container === void 0) { container = []; }
  7622. cmp = cmp || (function (x, y) {
  7623. if (x < y)
  7624. return -1;
  7625. if (x > y)
  7626. return 1;
  7627. return 0;
  7628. });
  7629. var len = 0;
  7630. var root = new TreeNode_1.default();
  7631. root.color = TreeNode_1.default.TreeNodeColorType.black;
  7632. this.size = function () {
  7633. return len;
  7634. };
  7635. this.empty = function () {
  7636. return len === 0;
  7637. };
  7638. this.clear = function () {
  7639. len = 0;
  7640. root.key = root.value = undefined;
  7641. root.leftChild = root.rightChild = root.brother = undefined;
  7642. };
  7643. var findSubTreeMinNode = function (curNode) {
  7644. if (!curNode || curNode.key === undefined)
  7645. throw new Error("unknown error");
  7646. return curNode.leftChild ? findSubTreeMinNode(curNode.leftChild) : curNode;
  7647. };
  7648. var findSubTreeMaxNode = function (curNode) {
  7649. if (!curNode || curNode.key === undefined)
  7650. throw new Error("unknown error");
  7651. return curNode.rightChild ? findSubTreeMaxNode(curNode.rightChild) : curNode;
  7652. };
  7653. this.front = function () {
  7654. if (this.empty())
  7655. return undefined;
  7656. var minNode = findSubTreeMinNode(root);
  7657. if (minNode.key === undefined || minNode.value === undefined)
  7658. throw new Error("unknown error");
  7659. return {
  7660. key: minNode.key,
  7661. value: minNode.value
  7662. };
  7663. };
  7664. this.back = function () {
  7665. if (this.empty())
  7666. return undefined;
  7667. var maxNode = findSubTreeMaxNode(root);
  7668. if (maxNode.key === undefined || maxNode.value === undefined)
  7669. throw new Error("unknown error");
  7670. return {
  7671. key: maxNode.key,
  7672. value: maxNode.value
  7673. };
  7674. };
  7675. this.forEach = function (callback) {
  7676. var e_1, _a;
  7677. var index = 0;
  7678. try {
  7679. for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {
  7680. var pair = _c.value;
  7681. callback(pair, index++);
  7682. }
  7683. }
  7684. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  7685. finally {
  7686. try {
  7687. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  7688. }
  7689. finally { if (e_1) throw e_1.error; }
  7690. }
  7691. };
  7692. this.getElementByPos = function (pos) {
  7693. var e_2, _a;
  7694. if (pos < 0 || pos >= this.size())
  7695. throw new Error("pos must more than 0 and less than set's size");
  7696. var index = 0;
  7697. try {
  7698. for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {
  7699. var pair = _c.value;
  7700. if (index === pos)
  7701. return pair;
  7702. ++index;
  7703. }
  7704. }
  7705. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  7706. finally {
  7707. try {
  7708. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  7709. }
  7710. finally { if (e_2) throw e_2.error; }
  7711. }
  7712. throw new Error("unknown Error");
  7713. };
  7714. var _lowerBound = function (curNode, key) {
  7715. if (!curNode || curNode.key === undefined || curNode.value === undefined)
  7716. return undefined;
  7717. var cmpResult = cmp(curNode.key, key);
  7718. if (cmpResult === 0)
  7719. return { key: curNode.key, value: curNode.value };
  7720. if (cmpResult < 0)
  7721. return _lowerBound(curNode.rightChild, key);
  7722. return _lowerBound(curNode.leftChild, key) || {
  7723. key: curNode.key,
  7724. value: curNode.value
  7725. };
  7726. };
  7727. this.lowerBound = function (key) {
  7728. return _lowerBound(root, key);
  7729. };
  7730. var _upperBound = function (curNode, key) {
  7731. if (!curNode || curNode.key === undefined || curNode.value === undefined)
  7732. return undefined;
  7733. var cmpResult = cmp(curNode.key, key);
  7734. if (cmpResult <= 0)
  7735. return _upperBound(curNode.rightChild, key);
  7736. return _upperBound(curNode.leftChild, key) || {
  7737. key: curNode.key,
  7738. value: curNode.value
  7739. };
  7740. };
  7741. this.upperBound = function (key) {
  7742. return _upperBound(root, key);
  7743. };
  7744. var _reverseLowerBound = function (curNode, key) {
  7745. if (!curNode || curNode.key === undefined || curNode.value === undefined)
  7746. return undefined;
  7747. var cmpResult = cmp(curNode.key, key);
  7748. if (cmpResult === 0)
  7749. return { key: curNode.key, value: curNode.value };
  7750. if (cmpResult > 0)
  7751. return _reverseLowerBound(curNode.leftChild, key);
  7752. return _reverseLowerBound(curNode.rightChild, key) || {
  7753. key: curNode.key,
  7754. value: curNode.value
  7755. };
  7756. };
  7757. this.reverseLowerBound = function (key) {
  7758. return _reverseLowerBound(root, key);
  7759. };
  7760. var _reverseUpperBound = function (curNode, key) {
  7761. if (!curNode || curNode.key === undefined || curNode.value === undefined)
  7762. return undefined;
  7763. var cmpResult = cmp(curNode.key, key);
  7764. if (cmpResult >= 0)
  7765. return _reverseUpperBound(curNode.leftChild, key);
  7766. return _reverseUpperBound(curNode.rightChild, key) || {
  7767. key: curNode.key,
  7768. value: curNode.value
  7769. };
  7770. };
  7771. this.reverseUpperBound = function (key) {
  7772. return _reverseUpperBound(root, key);
  7773. };
  7774. var eraseNodeSelfBalance = function (curNode) {
  7775. var parentNode = curNode.parent;
  7776. if (!parentNode) {
  7777. if (curNode === root)
  7778. return;
  7779. throw new Error("unknown error");
  7780. }
  7781. if (curNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  7782. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7783. return;
  7784. }
  7785. var brotherNode = curNode.brother;
  7786. if (!brotherNode)
  7787. throw new Error("unknown error");
  7788. if (curNode === parentNode.leftChild) {
  7789. if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  7790. brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7791. parentNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7792. var newRoot = parentNode.rotateLeft();
  7793. if (root === parentNode)
  7794. root = newRoot;
  7795. eraseNodeSelfBalance(curNode);
  7796. }
  7797. else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  7798. if (brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  7799. brotherNode.color = parentNode.color;
  7800. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7801. if (brotherNode.rightChild)
  7802. brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;
  7803. var newRoot = parentNode.rotateLeft();
  7804. if (root === parentNode)
  7805. root = newRoot;
  7806. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7807. }
  7808. else if ((!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  7809. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7810. if (brotherNode.leftChild)
  7811. brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;
  7812. var newRoot = brotherNode.rotateRight();
  7813. if (root === brotherNode)
  7814. root = newRoot;
  7815. eraseNodeSelfBalance(curNode);
  7816. }
  7817. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {
  7818. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7819. eraseNodeSelfBalance(parentNode);
  7820. }
  7821. }
  7822. }
  7823. else if (curNode === parentNode.rightChild) {
  7824. if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  7825. brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7826. parentNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7827. var newRoot = parentNode.rotateRight();
  7828. if (root === parentNode)
  7829. root = newRoot;
  7830. eraseNodeSelfBalance(curNode);
  7831. }
  7832. else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  7833. if (brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  7834. brotherNode.color = parentNode.color;
  7835. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7836. if (brotherNode.leftChild)
  7837. brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;
  7838. var newRoot = parentNode.rotateRight();
  7839. if (root === parentNode)
  7840. root = newRoot;
  7841. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7842. }
  7843. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  7844. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7845. if (brotherNode.rightChild)
  7846. brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;
  7847. var newRoot = brotherNode.rotateLeft();
  7848. if (root === brotherNode)
  7849. root = newRoot;
  7850. eraseNodeSelfBalance(curNode);
  7851. }
  7852. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {
  7853. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  7854. eraseNodeSelfBalance(parentNode);
  7855. }
  7856. }
  7857. }
  7858. };
  7859. var eraseNode = function (curNode) {
  7860. var swapNode = curNode;
  7861. while (swapNode.leftChild || swapNode.rightChild) {
  7862. if (swapNode.rightChild) {
  7863. swapNode = findSubTreeMinNode(swapNode.rightChild);
  7864. var tmpKey = curNode.key;
  7865. curNode.key = swapNode.key;
  7866. swapNode.key = tmpKey;
  7867. var tmpValue = curNode.value;
  7868. curNode.value = swapNode.value;
  7869. swapNode.value = tmpValue;
  7870. curNode = swapNode;
  7871. }
  7872. if (swapNode.leftChild) {
  7873. swapNode = findSubTreeMaxNode(swapNode.leftChild);
  7874. var tmpKey = curNode.key;
  7875. curNode.key = swapNode.key;
  7876. swapNode.key = tmpKey;
  7877. var tmpValue = curNode.value;
  7878. curNode.value = swapNode.value;
  7879. swapNode.value = tmpValue;
  7880. curNode = swapNode;
  7881. }
  7882. }
  7883. eraseNodeSelfBalance(swapNode);
  7884. if (swapNode)
  7885. swapNode.remove();
  7886. --len;
  7887. root.color = TreeNode_1.default.TreeNodeColorType.black;
  7888. };
  7889. var inOrderTraversal = function (curNode, callback) {
  7890. if (!curNode || curNode.key === undefined)
  7891. return false;
  7892. var ifReturn = inOrderTraversal(curNode.leftChild, callback);
  7893. if (ifReturn)
  7894. return true;
  7895. if (callback(curNode))
  7896. return true;
  7897. return inOrderTraversal(curNode.rightChild, callback);
  7898. };
  7899. this.eraseElementByPos = function (pos) {
  7900. if (pos < 0 || pos >= len)
  7901. throw new Error("pos must more than 0 and less than set's size");
  7902. var index = 0;
  7903. inOrderTraversal(root, function (curNode) {
  7904. if (pos === index) {
  7905. eraseNode(curNode);
  7906. return true;
  7907. }
  7908. ++index;
  7909. return false;
  7910. });
  7911. };
  7912. this.eraseElementByKey = function (key) {
  7913. if (this.empty())
  7914. return;
  7915. var curNode = findElementPos(root, key);
  7916. if (curNode === undefined || curNode.key === undefined || cmp(curNode.key, key) !== 0)
  7917. return;
  7918. eraseNode(curNode);
  7919. };
  7920. var findInsertPos = function (curNode, element) {
  7921. if (!curNode || curNode.key === undefined)
  7922. throw new Error("unknown error");
  7923. var cmpResult = cmp(element, curNode.key);
  7924. if (cmpResult < 0) {
  7925. if (!curNode.leftChild) {
  7926. curNode.leftChild = new TreeNode_1.default();
  7927. curNode.leftChild.parent = curNode;
  7928. curNode.leftChild.brother = curNode.rightChild;
  7929. if (curNode.rightChild)
  7930. curNode.rightChild.brother = curNode.leftChild;
  7931. return curNode.leftChild;
  7932. }
  7933. return findInsertPos(curNode.leftChild, element);
  7934. }
  7935. else if (cmpResult > 0) {
  7936. if (!curNode.rightChild) {
  7937. curNode.rightChild = new TreeNode_1.default();
  7938. curNode.rightChild.parent = curNode;
  7939. curNode.rightChild.brother = curNode.leftChild;
  7940. if (curNode.leftChild)
  7941. curNode.leftChild.brother = curNode.rightChild;
  7942. return curNode.rightChild;
  7943. }
  7944. return findInsertPos(curNode.rightChild, element);
  7945. }
  7946. return curNode;
  7947. };
  7948. var insertNodeSelfBalance = function (curNode) {
  7949. var parentNode = curNode.parent;
  7950. if (!parentNode) {
  7951. if (curNode === root)
  7952. return;
  7953. throw new Error("unknown error");
  7954. }
  7955. if (parentNode.color === TreeNode_1.default.TreeNodeColorType.black)
  7956. return;
  7957. if (parentNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  7958. var uncleNode = parentNode.brother;
  7959. var grandParent = parentNode.parent;
  7960. if (!grandParent)
  7961. throw new Error("unknown error");
  7962. if (uncleNode && uncleNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  7963. uncleNode.color = parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7964. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  7965. insertNodeSelfBalance(grandParent);
  7966. }
  7967. else if (!uncleNode || uncleNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  7968. if (parentNode === grandParent.leftChild) {
  7969. if (curNode === parentNode.leftChild) {
  7970. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7971. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  7972. var newRoot = grandParent.rotateRight();
  7973. if (grandParent === root)
  7974. root = newRoot;
  7975. }
  7976. else if (curNode === parentNode.rightChild) {
  7977. var newRoot = parentNode.rotateLeft();
  7978. if (grandParent === root)
  7979. root = newRoot;
  7980. insertNodeSelfBalance(parentNode);
  7981. }
  7982. }
  7983. else if (parentNode === grandParent.rightChild) {
  7984. if (curNode === parentNode.leftChild) {
  7985. var newRoot = parentNode.rotateRight();
  7986. if (grandParent === root)
  7987. root = newRoot;
  7988. insertNodeSelfBalance(parentNode);
  7989. }
  7990. else if (curNode === parentNode.rightChild) {
  7991. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  7992. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  7993. var newRoot = grandParent.rotateLeft();
  7994. if (grandParent === root)
  7995. root = newRoot;
  7996. }
  7997. }
  7998. }
  7999. }
  8000. };
  8001. this.setElement = function (key, value) {
  8002. if (key === null || key === undefined) {
  8003. throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
  8004. }
  8005. if (value === null || value === undefined) {
  8006. this.eraseElementByKey(key);
  8007. return;
  8008. }
  8009. if (this.empty()) {
  8010. ++len;
  8011. root.key = key;
  8012. root.value = value;
  8013. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8014. return;
  8015. }
  8016. var curNode = findInsertPos(root, key);
  8017. if (curNode.key !== undefined && cmp(curNode.key, key) === 0) {
  8018. curNode.value = value;
  8019. return;
  8020. }
  8021. ++len;
  8022. curNode.key = key;
  8023. curNode.value = value;
  8024. insertNodeSelfBalance(curNode);
  8025. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8026. };
  8027. var findElementPos = function (curNode, element) {
  8028. if (!curNode || curNode.key === undefined)
  8029. return undefined;
  8030. var cmpResult = cmp(element, curNode.key);
  8031. if (cmpResult < 0)
  8032. return findElementPos(curNode.leftChild, element);
  8033. else if (cmpResult > 0)
  8034. return findElementPos(curNode.rightChild, element);
  8035. return curNode;
  8036. };
  8037. this.find = function (element) {
  8038. return !!findElementPos(root, element);
  8039. };
  8040. this.getElementByKey = function (element) {
  8041. var curNode = findElementPos(root, element);
  8042. if ((curNode === null || curNode === void 0 ? void 0 : curNode.key) === undefined || (curNode === null || curNode === void 0 ? void 0 : curNode.value) === undefined)
  8043. throw new Error("unknown error");
  8044. return curNode.value;
  8045. };
  8046. // waiting for optimization, this is O(mlog(n+m)) algorithm now, but we expect it to be O(mlog(n/m+1)).
  8047. // (https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Set_operations_and_bulk_operations)
  8048. this.union = function (other) {
  8049. var _this = this;
  8050. other.forEach(function (_a) {
  8051. var key = _a.key, value = _a.value;
  8052. return _this.setElement(key, value);
  8053. });
  8054. };
  8055. this.getHeight = function () {
  8056. if (this.empty())
  8057. return 0;
  8058. var traversal = function (curNode) {
  8059. if (!curNode)
  8060. return 1;
  8061. return Math.max(traversal(curNode.leftChild), traversal(curNode.rightChild)) + 1;
  8062. };
  8063. return traversal(root);
  8064. };
  8065. var iterationFunc = function (curNode) {
  8066. return __generator(this, function (_a) {
  8067. switch (_a.label) {
  8068. case 0:
  8069. if (!curNode || curNode.key === undefined || curNode.value === undefined)
  8070. return [2 /*return*/];
  8071. return [5 /*yield**/, __values(iterationFunc(curNode.leftChild))];
  8072. case 1:
  8073. _a.sent();
  8074. return [4 /*yield*/, { key: curNode.key, value: curNode.value }];
  8075. case 2:
  8076. _a.sent();
  8077. return [5 /*yield**/, __values(iterationFunc(curNode.rightChild))];
  8078. case 3:
  8079. _a.sent();
  8080. return [2 /*return*/];
  8081. }
  8082. });
  8083. };
  8084. this[Symbol.iterator] = function () {
  8085. return iterationFunc(root);
  8086. };
  8087. container.forEach(function (_a) {
  8088. var key = _a.key, value = _a.value;
  8089. return _this.setElement(key, value);
  8090. });
  8091. Object.freeze(this);
  8092. }
  8093. Object.freeze(Map);
  8094. exports.default = Map;
  8095. },{"../Base/TreeNode":25}],31:[function(require,module,exports){
  8096. "use strict";
  8097. Object.defineProperty(exports, "__esModule", { value: true });
  8098. /**
  8099. * @param container
  8100. * @param cmp default cmp will generate a max heap
  8101. * @constructor
  8102. */
  8103. function PriorityQueue(container, cmp) {
  8104. if (container === void 0) { container = []; }
  8105. cmp = cmp || (function (x, y) {
  8106. if (x > y)
  8107. return -1;
  8108. if (x < y)
  8109. return 1;
  8110. return 0;
  8111. });
  8112. var priorityQueue = [];
  8113. container.forEach(function (element) { return priorityQueue.push(element); });
  8114. var len = priorityQueue.length;
  8115. var swap = function (x, y) {
  8116. if (x < 0 || x >= len)
  8117. throw new Error("unknown error");
  8118. if (y < 0 || y >= len)
  8119. throw new Error("unknown error");
  8120. var tmp = priorityQueue[x];
  8121. priorityQueue[x] = priorityQueue[y];
  8122. priorityQueue[y] = tmp;
  8123. };
  8124. var adjust = function (parent) {
  8125. if (parent < 0 || parent >= len)
  8126. throw new Error("unknown error");
  8127. var leftChild = parent * 2 + 1;
  8128. var rightChild = parent * 2 + 2;
  8129. if (leftChild < len && cmp(priorityQueue[parent], priorityQueue[leftChild]) > 0)
  8130. swap(parent, leftChild);
  8131. if (rightChild < len && cmp(priorityQueue[parent], priorityQueue[rightChild]) > 0)
  8132. swap(parent, rightChild);
  8133. };
  8134. (function () {
  8135. for (var parent_1 = Math.floor((len - 1) / 2); parent_1 >= 0; --parent_1) {
  8136. var curParent = parent_1;
  8137. var curChild = curParent * 2 + 1;
  8138. while (curChild < len) {
  8139. var leftChild = curChild;
  8140. var rightChild = leftChild + 1;
  8141. var minChild = leftChild;
  8142. if (rightChild < len && cmp(priorityQueue[leftChild], priorityQueue[rightChild]) > 0)
  8143. minChild = rightChild;
  8144. if (cmp(priorityQueue[curParent], priorityQueue[minChild]) <= 0)
  8145. break;
  8146. swap(curParent, minChild);
  8147. curParent = minChild;
  8148. curChild = curParent * 2 + 1;
  8149. }
  8150. }
  8151. })();
  8152. this.size = function () {
  8153. return len;
  8154. };
  8155. this.empty = function () {
  8156. return len === 0;
  8157. };
  8158. this.clear = function () {
  8159. len = 0;
  8160. priorityQueue.length = 0;
  8161. };
  8162. this.push = function (element) {
  8163. priorityQueue.push(element);
  8164. ++len;
  8165. if (len === 1)
  8166. return;
  8167. var curNode = len - 1;
  8168. while (curNode > 0) {
  8169. var parent_2 = Math.floor((curNode - 1) / 2);
  8170. if (cmp(priorityQueue[parent_2], element) <= 0)
  8171. break;
  8172. adjust(parent_2);
  8173. curNode = parent_2;
  8174. }
  8175. };
  8176. this.pop = function () {
  8177. if (this.empty())
  8178. return;
  8179. if (this.size() === 1) {
  8180. --len;
  8181. return;
  8182. }
  8183. var last = priorityQueue[len - 1];
  8184. --len;
  8185. var parent = 0;
  8186. while (parent < this.size()) {
  8187. var leftChild = parent * 2 + 1;
  8188. var rightChild = parent * 2 + 2;
  8189. if (leftChild >= this.size())
  8190. break;
  8191. var minChild = leftChild;
  8192. if (rightChild < this.size() && cmp(priorityQueue[leftChild], priorityQueue[rightChild]) > 0)
  8193. minChild = rightChild;
  8194. if (cmp(priorityQueue[minChild], last) >= 0)
  8195. break;
  8196. priorityQueue[parent] = priorityQueue[minChild];
  8197. parent = minChild;
  8198. }
  8199. priorityQueue[parent] = last;
  8200. };
  8201. this.top = function () {
  8202. return priorityQueue[0];
  8203. };
  8204. Object.freeze(this);
  8205. }
  8206. Object.freeze(PriorityQueue);
  8207. exports.default = PriorityQueue;
  8208. },{}],32:[function(require,module,exports){
  8209. "use strict";
  8210. Object.defineProperty(exports, "__esModule", { value: true });
  8211. var LinkList_1 = require("../LinkList/LinkList");
  8212. function Queue(container) {
  8213. if (container === void 0) { container = []; }
  8214. var queue = new LinkList_1.default(container);
  8215. this.size = function () {
  8216. return queue.size();
  8217. };
  8218. this.empty = function () {
  8219. return queue.empty();
  8220. };
  8221. this.clear = function () {
  8222. queue.clear();
  8223. };
  8224. this.push = function (element) {
  8225. queue.pushBack(element);
  8226. };
  8227. this.pop = function () {
  8228. queue.popFront();
  8229. };
  8230. this.front = function () {
  8231. return queue.front();
  8232. };
  8233. Object.freeze(this);
  8234. }
  8235. Object.freeze(Queue);
  8236. exports.default = Queue;
  8237. },{"../LinkList/LinkList":29}],33:[function(require,module,exports){
  8238. "use strict";
  8239. var __generator = (this && this.__generator) || function (thisArg, body) {
  8240. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  8241. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  8242. function verb(n) { return function (v) { return step([n, v]); }; }
  8243. function step(op) {
  8244. if (f) throw new TypeError("Generator is already executing.");
  8245. while (_) try {
  8246. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  8247. if (y = 0, t) op = [op[0] & 2, t.value];
  8248. switch (op[0]) {
  8249. case 0: case 1: t = op; break;
  8250. case 4: _.label++; return { value: op[1], done: false };
  8251. case 5: _.label++; y = op[1]; op = [0]; continue;
  8252. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  8253. default:
  8254. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  8255. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  8256. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  8257. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  8258. if (t[2]) _.ops.pop();
  8259. _.trys.pop(); continue;
  8260. }
  8261. op = body.call(thisArg, _);
  8262. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  8263. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  8264. }
  8265. };
  8266. var __values = (this && this.__values) || function(o) {
  8267. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  8268. if (m) return m.call(o);
  8269. if (o && typeof o.length === "number") return {
  8270. next: function () {
  8271. if (o && i >= o.length) o = void 0;
  8272. return { value: o && o[i++], done: !o };
  8273. }
  8274. };
  8275. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  8276. };
  8277. Object.defineProperty(exports, "__esModule", { value: true });
  8278. var TreeNode_1 = require("../Base/TreeNode");
  8279. function Set(container, cmp) {
  8280. var _this = this;
  8281. if (container === void 0) { container = []; }
  8282. cmp = cmp || (function (x, y) {
  8283. if (x < y)
  8284. return -1;
  8285. if (x > y)
  8286. return 1;
  8287. return 0;
  8288. });
  8289. var len = 0;
  8290. var root = new TreeNode_1.default();
  8291. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8292. this.size = function () {
  8293. return len;
  8294. };
  8295. this.empty = function () {
  8296. return len === 0;
  8297. };
  8298. this.clear = function () {
  8299. len = 0;
  8300. root.key = undefined;
  8301. root.leftChild = root.rightChild = root.brother = root.parent = undefined;
  8302. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8303. };
  8304. var findSubTreeMinNode = function (curNode) {
  8305. if (!curNode || curNode.key === undefined)
  8306. throw new Error("unknown error");
  8307. return curNode.leftChild ? findSubTreeMinNode(curNode.leftChild) : curNode;
  8308. };
  8309. var findSubTreeMaxNode = function (curNode) {
  8310. if (!curNode || curNode.key === undefined)
  8311. throw new Error("unknown error");
  8312. return curNode.rightChild ? findSubTreeMaxNode(curNode.rightChild) : curNode;
  8313. };
  8314. this.front = function () {
  8315. if (this.empty())
  8316. return undefined;
  8317. var minNode = findSubTreeMinNode(root);
  8318. return minNode.key;
  8319. };
  8320. this.back = function () {
  8321. if (this.empty())
  8322. return undefined;
  8323. var maxNode = findSubTreeMaxNode(root);
  8324. return maxNode.key;
  8325. };
  8326. this.forEach = function (callback) {
  8327. var e_1, _a;
  8328. var index = 0;
  8329. try {
  8330. for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {
  8331. var element = _c.value;
  8332. callback(element, index++);
  8333. }
  8334. }
  8335. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  8336. finally {
  8337. try {
  8338. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  8339. }
  8340. finally { if (e_1) throw e_1.error; }
  8341. }
  8342. };
  8343. this.getElementByPos = function (pos) {
  8344. var e_2, _a;
  8345. if (pos < 0 || pos >= this.size())
  8346. throw new Error("pos must more than 0 and less than set's size");
  8347. var index = 0;
  8348. try {
  8349. for (var _b = __values(this), _c = _b.next(); !_c.done; _c = _b.next()) {
  8350. var element = _c.value;
  8351. if (index === pos)
  8352. return element;
  8353. ++index;
  8354. }
  8355. }
  8356. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  8357. finally {
  8358. try {
  8359. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  8360. }
  8361. finally { if (e_2) throw e_2.error; }
  8362. }
  8363. throw new Error("unknown error");
  8364. };
  8365. var eraseNodeSelfBalance = function (curNode) {
  8366. var parentNode = curNode.parent;
  8367. if (!parentNode) {
  8368. if (curNode === root)
  8369. return;
  8370. throw new Error("unknown error");
  8371. }
  8372. if (curNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  8373. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8374. return;
  8375. }
  8376. var brotherNode = curNode.brother;
  8377. if (!brotherNode)
  8378. throw new Error("unknown error");
  8379. if (curNode === parentNode.leftChild) {
  8380. if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  8381. brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8382. parentNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8383. var newRoot = parentNode.rotateLeft();
  8384. if (root === parentNode)
  8385. root = newRoot;
  8386. eraseNodeSelfBalance(curNode);
  8387. }
  8388. else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  8389. if (brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  8390. brotherNode.color = parentNode.color;
  8391. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8392. if (brotherNode.rightChild)
  8393. brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;
  8394. var newRoot = parentNode.rotateLeft();
  8395. if (root === parentNode)
  8396. root = newRoot;
  8397. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8398. }
  8399. else if ((!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  8400. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8401. if (brotherNode.leftChild)
  8402. brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;
  8403. var newRoot = brotherNode.rotateRight();
  8404. if (root === brotherNode)
  8405. root = newRoot;
  8406. eraseNodeSelfBalance(curNode);
  8407. }
  8408. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {
  8409. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8410. eraseNodeSelfBalance(parentNode);
  8411. }
  8412. }
  8413. }
  8414. else if (curNode === parentNode.rightChild) {
  8415. if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  8416. brotherNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8417. parentNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8418. var newRoot = parentNode.rotateRight();
  8419. if (root === parentNode)
  8420. root = newRoot;
  8421. eraseNodeSelfBalance(curNode);
  8422. }
  8423. else if (brotherNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  8424. if (brotherNode.leftChild && brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  8425. brotherNode.color = parentNode.color;
  8426. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8427. if (brotherNode.leftChild)
  8428. brotherNode.leftChild.color = TreeNode_1.default.TreeNodeColorType.black;
  8429. var newRoot = parentNode.rotateRight();
  8430. if (root === parentNode)
  8431. root = newRoot;
  8432. curNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8433. }
  8434. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && brotherNode.rightChild && brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.red) {
  8435. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8436. if (brotherNode.rightChild)
  8437. brotherNode.rightChild.color = TreeNode_1.default.TreeNodeColorType.black;
  8438. var newRoot = brotherNode.rotateLeft();
  8439. if (root === brotherNode)
  8440. root = newRoot;
  8441. eraseNodeSelfBalance(curNode);
  8442. }
  8443. else if ((!brotherNode.leftChild || brotherNode.leftChild.color === TreeNode_1.default.TreeNodeColorType.black) && (!brotherNode.rightChild || brotherNode.rightChild.color === TreeNode_1.default.TreeNodeColorType.black)) {
  8444. brotherNode.color = TreeNode_1.default.TreeNodeColorType.red;
  8445. eraseNodeSelfBalance(parentNode);
  8446. }
  8447. }
  8448. }
  8449. };
  8450. var eraseNode = function (curNode) {
  8451. var swapNode = curNode;
  8452. while (swapNode.leftChild || swapNode.rightChild) {
  8453. if (swapNode.rightChild) {
  8454. swapNode = findSubTreeMinNode(swapNode.rightChild);
  8455. var tmpKey = curNode.key;
  8456. curNode.key = swapNode.key;
  8457. swapNode.key = tmpKey;
  8458. curNode = swapNode;
  8459. }
  8460. if (swapNode.leftChild) {
  8461. swapNode = findSubTreeMaxNode(swapNode.leftChild);
  8462. var tmpKey = curNode.key;
  8463. curNode.key = swapNode.key;
  8464. swapNode.key = tmpKey;
  8465. curNode = swapNode;
  8466. }
  8467. }
  8468. eraseNodeSelfBalance(swapNode);
  8469. if (swapNode)
  8470. swapNode.remove();
  8471. --len;
  8472. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8473. };
  8474. var inOrderTraversal = function (curNode, callback) {
  8475. if (!curNode || curNode.key === undefined)
  8476. return false;
  8477. var ifReturn = inOrderTraversal(curNode.leftChild, callback);
  8478. if (ifReturn)
  8479. return true;
  8480. if (callback(curNode))
  8481. return true;
  8482. return inOrderTraversal(curNode.rightChild, callback);
  8483. };
  8484. this.eraseElementByPos = function (pos) {
  8485. if (pos < 0 || pos >= len)
  8486. throw new Error("pos must more than 0 and less than set's size");
  8487. var index = 0;
  8488. inOrderTraversal(root, function (curNode) {
  8489. if (pos === index) {
  8490. eraseNode(curNode);
  8491. return true;
  8492. }
  8493. ++index;
  8494. return false;
  8495. });
  8496. };
  8497. this.eraseElementByValue = function (value) {
  8498. if (this.empty())
  8499. return;
  8500. var curNode = findElementPos(root, value);
  8501. if (curNode === undefined || curNode.key === undefined || cmp(curNode.key, value) !== 0)
  8502. return;
  8503. eraseNode(curNode);
  8504. };
  8505. var findInsertPos = function (curNode, element) {
  8506. if (!curNode || curNode.key === undefined)
  8507. throw new Error("unknown error");
  8508. var cmpResult = cmp(element, curNode.key);
  8509. if (cmpResult < 0) {
  8510. if (!curNode.leftChild) {
  8511. curNode.leftChild = new TreeNode_1.default();
  8512. curNode.leftChild.parent = curNode;
  8513. curNode.leftChild.brother = curNode.rightChild;
  8514. if (curNode.rightChild)
  8515. curNode.rightChild.brother = curNode.leftChild;
  8516. return curNode.leftChild;
  8517. }
  8518. return findInsertPos(curNode.leftChild, element);
  8519. }
  8520. else if (cmpResult > 0) {
  8521. if (!curNode.rightChild) {
  8522. curNode.rightChild = new TreeNode_1.default();
  8523. curNode.rightChild.parent = curNode;
  8524. curNode.rightChild.brother = curNode.leftChild;
  8525. if (curNode.leftChild)
  8526. curNode.leftChild.brother = curNode.rightChild;
  8527. return curNode.rightChild;
  8528. }
  8529. return findInsertPos(curNode.rightChild, element);
  8530. }
  8531. return curNode;
  8532. };
  8533. var insertNodeSelfBalance = function (curNode) {
  8534. var parentNode = curNode.parent;
  8535. if (!parentNode) {
  8536. if (curNode === root)
  8537. return;
  8538. throw new Error("unknown error");
  8539. }
  8540. if (parentNode.color === TreeNode_1.default.TreeNodeColorType.black)
  8541. return;
  8542. if (parentNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  8543. var uncleNode = parentNode.brother;
  8544. var grandParent = parentNode.parent;
  8545. if (!grandParent)
  8546. throw new Error("unknown error");
  8547. if (uncleNode && uncleNode.color === TreeNode_1.default.TreeNodeColorType.red) {
  8548. uncleNode.color = parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8549. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  8550. insertNodeSelfBalance(grandParent);
  8551. }
  8552. else if (!uncleNode || uncleNode.color === TreeNode_1.default.TreeNodeColorType.black) {
  8553. if (parentNode === grandParent.leftChild) {
  8554. if (curNode === parentNode.leftChild) {
  8555. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8556. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  8557. var newRoot = grandParent.rotateRight();
  8558. if (grandParent === root)
  8559. root = newRoot;
  8560. }
  8561. else if (curNode === parentNode.rightChild) {
  8562. var newRoot = parentNode.rotateLeft();
  8563. if (grandParent === root)
  8564. root = newRoot;
  8565. insertNodeSelfBalance(parentNode);
  8566. }
  8567. }
  8568. else if (parentNode === grandParent.rightChild) {
  8569. if (curNode === parentNode.leftChild) {
  8570. var newRoot = parentNode.rotateRight();
  8571. if (grandParent === root)
  8572. root = newRoot;
  8573. insertNodeSelfBalance(parentNode);
  8574. }
  8575. else if (curNode === parentNode.rightChild) {
  8576. parentNode.color = TreeNode_1.default.TreeNodeColorType.black;
  8577. grandParent.color = TreeNode_1.default.TreeNodeColorType.red;
  8578. var newRoot = grandParent.rotateLeft();
  8579. if (grandParent === root)
  8580. root = newRoot;
  8581. }
  8582. }
  8583. }
  8584. }
  8585. };
  8586. this.insert = function (element) {
  8587. if (element === null || element === undefined) {
  8588. throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");
  8589. }
  8590. if (this.empty()) {
  8591. ++len;
  8592. root.key = element;
  8593. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8594. return;
  8595. }
  8596. var curNode = findInsertPos(root, element);
  8597. if (curNode.key !== undefined && cmp(curNode.key, element) === 0)
  8598. return;
  8599. ++len;
  8600. curNode.key = element;
  8601. insertNodeSelfBalance(curNode);
  8602. root.color = TreeNode_1.default.TreeNodeColorType.black;
  8603. };
  8604. var findElementPos = function (curNode, element) {
  8605. if (!curNode || curNode.key === undefined)
  8606. return undefined;
  8607. var cmpResult = cmp(element, curNode.key);
  8608. if (cmpResult < 0)
  8609. return findElementPos(curNode.leftChild, element);
  8610. else if (cmpResult > 0)
  8611. return findElementPos(curNode.rightChild, element);
  8612. return curNode;
  8613. };
  8614. this.find = function (element) {
  8615. var curNode = findElementPos(root, element);
  8616. return curNode !== undefined && curNode.key !== undefined && cmp(curNode.key, element) === 0;
  8617. };
  8618. var _lowerBound = function (curNode, key) {
  8619. if (!curNode || curNode.key === undefined)
  8620. return undefined;
  8621. var cmpResult = cmp(curNode.key, key);
  8622. if (cmpResult === 0)
  8623. return curNode.key;
  8624. if (cmpResult < 0)
  8625. return _lowerBound(curNode.rightChild, key);
  8626. var res = _lowerBound(curNode.leftChild, key);
  8627. if (res !== undefined)
  8628. return res;
  8629. return curNode.key;
  8630. };
  8631. this.lowerBound = function (key) {
  8632. return _lowerBound(root, key);
  8633. };
  8634. var _upperBound = function (curNode, key) {
  8635. if (!curNode || curNode.key === undefined)
  8636. return undefined;
  8637. var cmpResult = cmp(curNode.key, key);
  8638. if (cmpResult <= 0)
  8639. return _upperBound(curNode.rightChild, key);
  8640. var res = _upperBound(curNode.leftChild, key);
  8641. if (res !== undefined)
  8642. return res;
  8643. return curNode.key;
  8644. };
  8645. this.upperBound = function (key) {
  8646. return _upperBound(root, key);
  8647. };
  8648. var _reverseLowerBound = function (curNode, key) {
  8649. if (!curNode || curNode.key === undefined)
  8650. return undefined;
  8651. var cmpResult = cmp(curNode.key, key);
  8652. if (cmpResult === 0)
  8653. return curNode.key;
  8654. if (cmpResult > 0)
  8655. return _reverseLowerBound(curNode.leftChild, key);
  8656. var res = _reverseLowerBound(curNode.rightChild, key);
  8657. if (res !== undefined)
  8658. return res;
  8659. return curNode.key;
  8660. };
  8661. this.reverseLowerBound = function (key) {
  8662. return _reverseLowerBound(root, key);
  8663. };
  8664. var _reverseUpperBound = function (curNode, key) {
  8665. if (!curNode || curNode.key === undefined)
  8666. return undefined;
  8667. var cmpResult = cmp(curNode.key, key);
  8668. if (cmpResult >= 0)
  8669. return _reverseUpperBound(curNode.leftChild, key);
  8670. var res = _reverseUpperBound(curNode.rightChild, key);
  8671. if (res !== undefined)
  8672. return res;
  8673. return curNode.key;
  8674. };
  8675. this.reverseUpperBound = function (key) {
  8676. return _reverseUpperBound(root, key);
  8677. };
  8678. // waiting for optimization, this is O(mlog(n+m)) algorithm now, but we expect it to be O(mlog(n/m+1)).
  8679. // (https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Set_operations_and_bulk_operations)
  8680. this.union = function (other) {
  8681. var _this = this;
  8682. other.forEach(function (element) { return _this.insert(element); });
  8683. };
  8684. this.getHeight = function () {
  8685. if (this.empty())
  8686. return 0;
  8687. var traversal = function (curNode) {
  8688. if (!curNode)
  8689. return 1;
  8690. return Math.max(traversal(curNode.leftChild), traversal(curNode.rightChild)) + 1;
  8691. };
  8692. return traversal(root);
  8693. };
  8694. var iterationFunc = function (curNode) {
  8695. return __generator(this, function (_a) {
  8696. switch (_a.label) {
  8697. case 0:
  8698. if (!curNode || curNode.key === undefined)
  8699. return [2 /*return*/];
  8700. return [5 /*yield**/, __values(iterationFunc(curNode.leftChild))];
  8701. case 1:
  8702. _a.sent();
  8703. return [4 /*yield*/, curNode.key];
  8704. case 2:
  8705. _a.sent();
  8706. return [5 /*yield**/, __values(iterationFunc(curNode.rightChild))];
  8707. case 3:
  8708. _a.sent();
  8709. return [2 /*return*/];
  8710. }
  8711. });
  8712. };
  8713. this[Symbol.iterator] = function () {
  8714. return iterationFunc(root);
  8715. };
  8716. container.forEach(function (element) { return _this.insert(element); });
  8717. Object.freeze(this);
  8718. }
  8719. Object.freeze(Set);
  8720. exports.default = Set;
  8721. },{"../Base/TreeNode":25}],34:[function(require,module,exports){
  8722. "use strict";
  8723. Object.defineProperty(exports, "__esModule", { value: true });
  8724. function Stack(container) {
  8725. var _this = this;
  8726. if (container === void 0) { container = []; }
  8727. var len = 0;
  8728. var stack = [];
  8729. this.size = function () {
  8730. return len;
  8731. };
  8732. this.empty = function () {
  8733. return len === 0;
  8734. };
  8735. this.clear = function () {
  8736. len = 0;
  8737. stack.length = 0;
  8738. };
  8739. this.push = function (element) {
  8740. stack.push(element);
  8741. ++len;
  8742. };
  8743. this.pop = function () {
  8744. stack.pop();
  8745. if (len > 0)
  8746. --len;
  8747. };
  8748. this.top = function () {
  8749. return stack[len - 1];
  8750. };
  8751. container.forEach(function (element) { return _this.push(element); });
  8752. Object.freeze(this);
  8753. }
  8754. Object.freeze(Stack);
  8755. exports.default = Stack;
  8756. },{}],35:[function(require,module,exports){
  8757. "use strict";
  8758. var __generator = (this && this.__generator) || function (thisArg, body) {
  8759. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  8760. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  8761. function verb(n) { return function (v) { return step([n, v]); }; }
  8762. function step(op) {
  8763. if (f) throw new TypeError("Generator is already executing.");
  8764. while (_) try {
  8765. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
  8766. if (y = 0, t) op = [op[0] & 2, t.value];
  8767. switch (op[0]) {
  8768. case 0: case 1: t = op; break;
  8769. case 4: _.label++; return { value: op[1], done: false };
  8770. case 5: _.label++; y = op[1]; op = [0]; continue;
  8771. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  8772. default:
  8773. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  8774. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  8775. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  8776. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  8777. if (t[2]) _.ops.pop();
  8778. _.trys.pop(); continue;
  8779. }
  8780. op = body.call(thisArg, _);
  8781. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  8782. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  8783. }
  8784. };
  8785. var __read = (this && this.__read) || function (o, n) {
  8786. var m = typeof Symbol === "function" && o[Symbol.iterator];
  8787. if (!m) return o;
  8788. var i = m.call(o), r, ar = [], e;
  8789. try {
  8790. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  8791. }
  8792. catch (error) { e = { error: error }; }
  8793. finally {
  8794. try {
  8795. if (r && !r.done && (m = i["return"])) m.call(i);
  8796. }
  8797. finally { if (e) throw e.error; }
  8798. }
  8799. return ar;
  8800. };
  8801. var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
  8802. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  8803. if (ar || !(i in from)) {
  8804. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  8805. ar[i] = from[i];
  8806. }
  8807. }
  8808. return to.concat(ar || Array.prototype.slice.call(from));
  8809. };
  8810. var __values = (this && this.__values) || function(o) {
  8811. var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  8812. if (m) return m.call(o);
  8813. if (o && typeof o.length === "number") return {
  8814. next: function () {
  8815. if (o && i >= o.length) o = void 0;
  8816. return { value: o && o[i++], done: !o };
  8817. }
  8818. };
  8819. throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
  8820. };
  8821. Object.defineProperty(exports, "__esModule", { value: true });
  8822. function Vector(container) {
  8823. var _this = this;
  8824. if (container === void 0) { container = []; }
  8825. var len = 0;
  8826. var vector = [];
  8827. this.size = function () {
  8828. return len;
  8829. };
  8830. this.empty = function () {
  8831. return len === 0;
  8832. };
  8833. this.clear = function () {
  8834. len = 0;
  8835. vector.length = 0;
  8836. };
  8837. this.front = function () {
  8838. if (this.empty())
  8839. return undefined;
  8840. return vector[0];
  8841. };
  8842. this.back = function () {
  8843. if (this.empty())
  8844. return undefined;
  8845. return vector[len - 1];
  8846. };
  8847. this.forEach = function (callback) {
  8848. vector.forEach(callback);
  8849. };
  8850. this.getElementByPos = function (pos) {
  8851. if (pos < 0 || pos >= len)
  8852. throw new Error("pos must more than 0 and less than vector's size");
  8853. return vector[pos];
  8854. };
  8855. this.eraseElementByPos = function (pos) {
  8856. if (pos < 0 || pos >= len)
  8857. throw new Error("pos must more than 0 and less than vector's size");
  8858. for (var i = pos; i < len - 1; ++i)
  8859. vector[i] = vector[i + 1];
  8860. this.popBack();
  8861. };
  8862. this.eraseElementByValue = function (value) {
  8863. var newArr = [];
  8864. this.forEach(function (element) {
  8865. if (element !== value)
  8866. newArr.push(element);
  8867. });
  8868. newArr.forEach(function (element, index) {
  8869. vector[index] = element;
  8870. });
  8871. var newLen = newArr.length;
  8872. while (len > newLen)
  8873. this.popBack();
  8874. };
  8875. this.pushBack = function (element) {
  8876. vector.push(element);
  8877. ++len;
  8878. };
  8879. this.popBack = function () {
  8880. vector.pop();
  8881. if (len > 0)
  8882. --len;
  8883. };
  8884. this.setElementByPos = function (pos, element) {
  8885. if (pos < 0 || pos >= len)
  8886. throw new Error("pos must more than 0 and less than vector's size");
  8887. vector[pos] = element;
  8888. };
  8889. this.insert = function (pos, element, num) {
  8890. if (num === void 0) { num = 1; }
  8891. if (pos < 0 || pos > len)
  8892. throw new Error("pos must more than 0 and less than or equal to vector's size");
  8893. vector.splice.apply(vector, __spreadArray([pos, 0], __read(new Array(num).fill(element)), false));
  8894. len += num;
  8895. };
  8896. this.find = function (element) {
  8897. return vector.includes(element);
  8898. };
  8899. this.reverse = function () {
  8900. vector.reverse();
  8901. };
  8902. this.unique = function () {
  8903. var pre;
  8904. var newArr = [];
  8905. this.forEach(function (element, index) {
  8906. if (index === 0 || element !== pre) {
  8907. newArr.push(element);
  8908. pre = element;
  8909. }
  8910. });
  8911. newArr.forEach(function (element, index) {
  8912. vector[index] = element;
  8913. });
  8914. var newLen = newArr.length;
  8915. while (len > newLen)
  8916. this.popBack();
  8917. };
  8918. this.sort = function (cmp) {
  8919. vector.sort(cmp);
  8920. };
  8921. this[Symbol.iterator] = function () {
  8922. return (function () {
  8923. return __generator(this, function (_a) {
  8924. switch (_a.label) {
  8925. case 0: return [5 /*yield**/, __values(vector)];
  8926. case 1: return [2 /*return*/, _a.sent()];
  8927. }
  8928. });
  8929. })();
  8930. };
  8931. container.forEach(function (element) { return _this.pushBack(element); });
  8932. Object.freeze(this);
  8933. }
  8934. Object.freeze(Vector);
  8935. exports.default = Vector;
  8936. },{}],36:[function(require,module,exports){
  8937. "use strict";
  8938. Object.defineProperty(exports, "__esModule", { value: true });
  8939. exports.HashMap = exports.HashSet = exports.Map = exports.Set = exports.PriorityQueue = exports.Deque = exports.LinkList = exports.Queue = exports.Stack = exports.Vector = void 0;
  8940. var Vector_1 = require("./Vector/Vector");
  8941. exports.Vector = Vector_1.default;
  8942. var Stack_1 = require("./Stack/Stack");
  8943. exports.Stack = Stack_1.default;
  8944. var Queue_1 = require("./Queue/Queue");
  8945. exports.Queue = Queue_1.default;
  8946. var LinkList_1 = require("./LinkList/LinkList");
  8947. exports.LinkList = LinkList_1.default;
  8948. var Deque_1 = require("./Deque/Deque");
  8949. exports.Deque = Deque_1.default;
  8950. var PriorityQueue_1 = require("./PriorityQueue/PriorityQueue");
  8951. exports.PriorityQueue = PriorityQueue_1.default;
  8952. var Set_1 = require("./Set/Set");
  8953. exports.Set = Set_1.default;
  8954. var Map_1 = require("./Map/Map");
  8955. exports.Map = Map_1.default;
  8956. var HashSet_1 = require("./HashSet/HashSet");
  8957. exports.HashSet = HashSet_1.default;
  8958. var HashMap_1 = require("./HashMap/HashMap");
  8959. exports.HashMap = HashMap_1.default;
  8960. },{"./Deque/Deque":26,"./HashMap/HashMap":27,"./HashSet/HashSet":28,"./LinkList/LinkList":29,"./Map/Map":30,"./PriorityQueue/PriorityQueue":31,"./Queue/Queue":32,"./Set/Set":33,"./Stack/Stack":34,"./Vector/Vector":35}],37:[function(require,module,exports){
  8961. 'use strict'
  8962. // A linked list to keep track of recently-used-ness
  8963. const Yallist = require('yallist')
  8964. const MAX = Symbol('max')
  8965. const LENGTH = Symbol('length')
  8966. const LENGTH_CALCULATOR = Symbol('lengthCalculator')
  8967. const ALLOW_STALE = Symbol('allowStale')
  8968. const MAX_AGE = Symbol('maxAge')
  8969. const DISPOSE = Symbol('dispose')
  8970. const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')
  8971. const LRU_LIST = Symbol('lruList')
  8972. const CACHE = Symbol('cache')
  8973. const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')
  8974. const naiveLength = () => 1
  8975. // lruList is a yallist where the head is the youngest
  8976. // item, and the tail is the oldest. the list contains the Hit
  8977. // objects as the entries.
  8978. // Each Hit object has a reference to its Yallist.Node. This
  8979. // never changes.
  8980. //
  8981. // cache is a Map (or PseudoMap) that matches the keys to
  8982. // the Yallist.Node object.
  8983. class LRUCache {
  8984. constructor (options) {
  8985. if (typeof options === 'number')
  8986. options = { max: options }
  8987. if (!options)
  8988. options = {}
  8989. if (options.max && (typeof options.max !== 'number' || options.max < 0))
  8990. throw new TypeError('max must be a non-negative number')
  8991. // Kind of weird to have a default max of Infinity, but oh well.
  8992. const max = this[MAX] = options.max || Infinity
  8993. const lc = options.length || naiveLength
  8994. this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc
  8995. this[ALLOW_STALE] = options.stale || false
  8996. if (options.maxAge && typeof options.maxAge !== 'number')
  8997. throw new TypeError('maxAge must be a number')
  8998. this[MAX_AGE] = options.maxAge || 0
  8999. this[DISPOSE] = options.dispose
  9000. this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false
  9001. this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false
  9002. this.reset()
  9003. }
  9004. // resize the cache when the max changes.
  9005. set max (mL) {
  9006. if (typeof mL !== 'number' || mL < 0)
  9007. throw new TypeError('max must be a non-negative number')
  9008. this[MAX] = mL || Infinity
  9009. trim(this)
  9010. }
  9011. get max () {
  9012. return this[MAX]
  9013. }
  9014. set allowStale (allowStale) {
  9015. this[ALLOW_STALE] = !!allowStale
  9016. }
  9017. get allowStale () {
  9018. return this[ALLOW_STALE]
  9019. }
  9020. set maxAge (mA) {
  9021. if (typeof mA !== 'number')
  9022. throw new TypeError('maxAge must be a non-negative number')
  9023. this[MAX_AGE] = mA
  9024. trim(this)
  9025. }
  9026. get maxAge () {
  9027. return this[MAX_AGE]
  9028. }
  9029. // resize the cache when the lengthCalculator changes.
  9030. set lengthCalculator (lC) {
  9031. if (typeof lC !== 'function')
  9032. lC = naiveLength
  9033. if (lC !== this[LENGTH_CALCULATOR]) {
  9034. this[LENGTH_CALCULATOR] = lC
  9035. this[LENGTH] = 0
  9036. this[LRU_LIST].forEach(hit => {
  9037. hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)
  9038. this[LENGTH] += hit.length
  9039. })
  9040. }
  9041. trim(this)
  9042. }
  9043. get lengthCalculator () { return this[LENGTH_CALCULATOR] }
  9044. get length () { return this[LENGTH] }
  9045. get itemCount () { return this[LRU_LIST].length }
  9046. rforEach (fn, thisp) {
  9047. thisp = thisp || this
  9048. for (let walker = this[LRU_LIST].tail; walker !== null;) {
  9049. const prev = walker.prev
  9050. forEachStep(this, fn, walker, thisp)
  9051. walker = prev
  9052. }
  9053. }
  9054. forEach (fn, thisp) {
  9055. thisp = thisp || this
  9056. for (let walker = this[LRU_LIST].head; walker !== null;) {
  9057. const next = walker.next
  9058. forEachStep(this, fn, walker, thisp)
  9059. walker = next
  9060. }
  9061. }
  9062. keys () {
  9063. return this[LRU_LIST].toArray().map(k => k.key)
  9064. }
  9065. values () {
  9066. return this[LRU_LIST].toArray().map(k => k.value)
  9067. }
  9068. reset () {
  9069. if (this[DISPOSE] &&
  9070. this[LRU_LIST] &&
  9071. this[LRU_LIST].length) {
  9072. this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))
  9073. }
  9074. this[CACHE] = new Map() // hash of items by key
  9075. this[LRU_LIST] = new Yallist() // list of items in order of use recency
  9076. this[LENGTH] = 0 // length of items in the list
  9077. }
  9078. dump () {
  9079. return this[LRU_LIST].map(hit =>
  9080. isStale(this, hit) ? false : {
  9081. k: hit.key,
  9082. v: hit.value,
  9083. e: hit.now + (hit.maxAge || 0)
  9084. }).toArray().filter(h => h)
  9085. }
  9086. dumpLru () {
  9087. return this[LRU_LIST]
  9088. }
  9089. set (key, value, maxAge) {
  9090. maxAge = maxAge || this[MAX_AGE]
  9091. if (maxAge && typeof maxAge !== 'number')
  9092. throw new TypeError('maxAge must be a number')
  9093. const now = maxAge ? Date.now() : 0
  9094. const len = this[LENGTH_CALCULATOR](value, key)
  9095. if (this[CACHE].has(key)) {
  9096. if (len > this[MAX]) {
  9097. del(this, this[CACHE].get(key))
  9098. return false
  9099. }
  9100. const node = this[CACHE].get(key)
  9101. const item = node.value
  9102. // dispose of the old one before overwriting
  9103. // split out into 2 ifs for better coverage tracking
  9104. if (this[DISPOSE]) {
  9105. if (!this[NO_DISPOSE_ON_SET])
  9106. this[DISPOSE](key, item.value)
  9107. }
  9108. item.now = now
  9109. item.maxAge = maxAge
  9110. item.value = value
  9111. this[LENGTH] += len - item.length
  9112. item.length = len
  9113. this.get(key)
  9114. trim(this)
  9115. return true
  9116. }
  9117. const hit = new Entry(key, value, len, now, maxAge)
  9118. // oversized objects fall out of cache automatically.
  9119. if (hit.length > this[MAX]) {
  9120. if (this[DISPOSE])
  9121. this[DISPOSE](key, value)
  9122. return false
  9123. }
  9124. this[LENGTH] += hit.length
  9125. this[LRU_LIST].unshift(hit)
  9126. this[CACHE].set(key, this[LRU_LIST].head)
  9127. trim(this)
  9128. return true
  9129. }
  9130. has (key) {
  9131. if (!this[CACHE].has(key)) return false
  9132. const hit = this[CACHE].get(key).value
  9133. return !isStale(this, hit)
  9134. }
  9135. get (key) {
  9136. return get(this, key, true)
  9137. }
  9138. peek (key) {
  9139. return get(this, key, false)
  9140. }
  9141. pop () {
  9142. const node = this[LRU_LIST].tail
  9143. if (!node)
  9144. return null
  9145. del(this, node)
  9146. return node.value
  9147. }
  9148. del (key) {
  9149. del(this, this[CACHE].get(key))
  9150. }
  9151. load (arr) {
  9152. // reset the cache
  9153. this.reset()
  9154. const now = Date.now()
  9155. // A previous serialized cache has the most recent items first
  9156. for (let l = arr.length - 1; l >= 0; l--) {
  9157. const hit = arr[l]
  9158. const expiresAt = hit.e || 0
  9159. if (expiresAt === 0)
  9160. // the item was created without expiration in a non aged cache
  9161. this.set(hit.k, hit.v)
  9162. else {
  9163. const maxAge = expiresAt - now
  9164. // dont add already expired items
  9165. if (maxAge > 0) {
  9166. this.set(hit.k, hit.v, maxAge)
  9167. }
  9168. }
  9169. }
  9170. }
  9171. prune () {
  9172. this[CACHE].forEach((value, key) => get(this, key, false))
  9173. }
  9174. }
  9175. const get = (self, key, doUse) => {
  9176. const node = self[CACHE].get(key)
  9177. if (node) {
  9178. const hit = node.value
  9179. if (isStale(self, hit)) {
  9180. del(self, node)
  9181. if (!self[ALLOW_STALE])
  9182. return undefined
  9183. } else {
  9184. if (doUse) {
  9185. if (self[UPDATE_AGE_ON_GET])
  9186. node.value.now = Date.now()
  9187. self[LRU_LIST].unshiftNode(node)
  9188. }
  9189. }
  9190. return hit.value
  9191. }
  9192. }
  9193. const isStale = (self, hit) => {
  9194. if (!hit || (!hit.maxAge && !self[MAX_AGE]))
  9195. return false
  9196. const diff = Date.now() - hit.now
  9197. return hit.maxAge ? diff > hit.maxAge
  9198. : self[MAX_AGE] && (diff > self[MAX_AGE])
  9199. }
  9200. const trim = self => {
  9201. if (self[LENGTH] > self[MAX]) {
  9202. for (let walker = self[LRU_LIST].tail;
  9203. self[LENGTH] > self[MAX] && walker !== null;) {
  9204. // We know that we're about to delete this one, and also
  9205. // what the next least recently used key will be, so just
  9206. // go ahead and set it now.
  9207. const prev = walker.prev
  9208. del(self, walker)
  9209. walker = prev
  9210. }
  9211. }
  9212. }
  9213. const del = (self, node) => {
  9214. if (node) {
  9215. const hit = node.value
  9216. if (self[DISPOSE])
  9217. self[DISPOSE](hit.key, hit.value)
  9218. self[LENGTH] -= hit.length
  9219. self[CACHE].delete(hit.key)
  9220. self[LRU_LIST].removeNode(node)
  9221. }
  9222. }
  9223. class Entry {
  9224. constructor (key, value, length, now, maxAge) {
  9225. this.key = key
  9226. this.value = value
  9227. this.length = length
  9228. this.now = now
  9229. this.maxAge = maxAge || 0
  9230. }
  9231. }
  9232. const forEachStep = (self, fn, node, thisp) => {
  9233. let hit = node.value
  9234. if (isStale(self, hit)) {
  9235. del(self, node)
  9236. if (!self[ALLOW_STALE])
  9237. hit = undefined
  9238. }
  9239. if (hit)
  9240. fn.call(thisp, hit.value, hit.key, self)
  9241. }
  9242. module.exports = LRUCache
  9243. },{"yallist":83}],38:[function(require,module,exports){
  9244. (function (Buffer){(function (){
  9245. /* Protocol - protocol constants */
  9246. const protocol = module.exports
  9247. /* Command code => mnemonic */
  9248. protocol.types = {
  9249. 0: 'reserved',
  9250. 1: 'connect',
  9251. 2: 'connack',
  9252. 3: 'publish',
  9253. 4: 'puback',
  9254. 5: 'pubrec',
  9255. 6: 'pubrel',
  9256. 7: 'pubcomp',
  9257. 8: 'subscribe',
  9258. 9: 'suback',
  9259. 10: 'unsubscribe',
  9260. 11: 'unsuback',
  9261. 12: 'pingreq',
  9262. 13: 'pingresp',
  9263. 14: 'disconnect',
  9264. 15: 'auth'
  9265. }
  9266. /* Mnemonic => Command code */
  9267. protocol.codes = {}
  9268. for (const k in protocol.types) {
  9269. const v = protocol.types[k]
  9270. protocol.codes[v] = k
  9271. }
  9272. /* Header */
  9273. protocol.CMD_SHIFT = 4
  9274. protocol.CMD_MASK = 0xF0
  9275. protocol.DUP_MASK = 0x08
  9276. protocol.QOS_MASK = 0x03
  9277. protocol.QOS_SHIFT = 1
  9278. protocol.RETAIN_MASK = 0x01
  9279. /* Length */
  9280. protocol.VARBYTEINT_MASK = 0x7F
  9281. protocol.VARBYTEINT_FIN_MASK = 0x80
  9282. protocol.VARBYTEINT_MAX = 268435455
  9283. /* Connack */
  9284. protocol.SESSIONPRESENT_MASK = 0x01
  9285. protocol.SESSIONPRESENT_HEADER = Buffer.from([protocol.SESSIONPRESENT_MASK])
  9286. protocol.CONNACK_HEADER = Buffer.from([protocol.codes.connack << protocol.CMD_SHIFT])
  9287. /* Connect */
  9288. protocol.USERNAME_MASK = 0x80
  9289. protocol.PASSWORD_MASK = 0x40
  9290. protocol.WILL_RETAIN_MASK = 0x20
  9291. protocol.WILL_QOS_MASK = 0x18
  9292. protocol.WILL_QOS_SHIFT = 3
  9293. protocol.WILL_FLAG_MASK = 0x04
  9294. protocol.CLEAN_SESSION_MASK = 0x02
  9295. protocol.CONNECT_HEADER = Buffer.from([protocol.codes.connect << protocol.CMD_SHIFT])
  9296. /* Properties */
  9297. protocol.properties = {
  9298. sessionExpiryInterval: 17,
  9299. willDelayInterval: 24,
  9300. receiveMaximum: 33,
  9301. maximumPacketSize: 39,
  9302. topicAliasMaximum: 34,
  9303. requestResponseInformation: 25,
  9304. requestProblemInformation: 23,
  9305. userProperties: 38,
  9306. authenticationMethod: 21,
  9307. authenticationData: 22,
  9308. payloadFormatIndicator: 1,
  9309. messageExpiryInterval: 2,
  9310. contentType: 3,
  9311. responseTopic: 8,
  9312. correlationData: 9,
  9313. maximumQoS: 36,
  9314. retainAvailable: 37,
  9315. assignedClientIdentifier: 18,
  9316. reasonString: 31,
  9317. wildcardSubscriptionAvailable: 40,
  9318. subscriptionIdentifiersAvailable: 41,
  9319. sharedSubscriptionAvailable: 42,
  9320. serverKeepAlive: 19,
  9321. responseInformation: 26,
  9322. serverReference: 28,
  9323. topicAlias: 35,
  9324. subscriptionIdentifier: 11
  9325. }
  9326. protocol.propertiesCodes = {}
  9327. for (const prop in protocol.properties) {
  9328. const id = protocol.properties[prop]
  9329. protocol.propertiesCodes[id] = prop
  9330. }
  9331. protocol.propertiesTypes = {
  9332. sessionExpiryInterval: 'int32',
  9333. willDelayInterval: 'int32',
  9334. receiveMaximum: 'int16',
  9335. maximumPacketSize: 'int32',
  9336. topicAliasMaximum: 'int16',
  9337. requestResponseInformation: 'byte',
  9338. requestProblemInformation: 'byte',
  9339. userProperties: 'pair',
  9340. authenticationMethod: 'string',
  9341. authenticationData: 'binary',
  9342. payloadFormatIndicator: 'byte',
  9343. messageExpiryInterval: 'int32',
  9344. contentType: 'string',
  9345. responseTopic: 'string',
  9346. correlationData: 'binary',
  9347. maximumQoS: 'int8',
  9348. retainAvailable: 'byte',
  9349. assignedClientIdentifier: 'string',
  9350. reasonString: 'string',
  9351. wildcardSubscriptionAvailable: 'byte',
  9352. subscriptionIdentifiersAvailable: 'byte',
  9353. sharedSubscriptionAvailable: 'byte',
  9354. serverKeepAlive: 'int16',
  9355. responseInformation: 'string',
  9356. serverReference: 'string',
  9357. topicAlias: 'int16',
  9358. subscriptionIdentifier: 'var'
  9359. }
  9360. function genHeader (type) {
  9361. return [0, 1, 2].map(qos => {
  9362. return [0, 1].map(dup => {
  9363. return [0, 1].map(retain => {
  9364. const buf = Buffer.alloc(1)
  9365. buf.writeUInt8(
  9366. protocol.codes[type] << protocol.CMD_SHIFT |
  9367. (dup ? protocol.DUP_MASK : 0) |
  9368. qos << protocol.QOS_SHIFT | retain, 0, true)
  9369. return buf
  9370. })
  9371. })
  9372. })
  9373. }
  9374. /* Publish */
  9375. protocol.PUBLISH_HEADER = genHeader('publish')
  9376. /* Subscribe */
  9377. protocol.SUBSCRIBE_HEADER = genHeader('subscribe')
  9378. protocol.SUBSCRIBE_OPTIONS_QOS_MASK = 0x03
  9379. protocol.SUBSCRIBE_OPTIONS_NL_MASK = 0x01
  9380. protocol.SUBSCRIBE_OPTIONS_NL_SHIFT = 2
  9381. protocol.SUBSCRIBE_OPTIONS_RAP_MASK = 0x01
  9382. protocol.SUBSCRIBE_OPTIONS_RAP_SHIFT = 3
  9383. protocol.SUBSCRIBE_OPTIONS_RH_MASK = 0x03
  9384. protocol.SUBSCRIBE_OPTIONS_RH_SHIFT = 4
  9385. protocol.SUBSCRIBE_OPTIONS_RH = [0x00, 0x10, 0x20]
  9386. protocol.SUBSCRIBE_OPTIONS_NL = 0x04
  9387. protocol.SUBSCRIBE_OPTIONS_RAP = 0x08
  9388. protocol.SUBSCRIBE_OPTIONS_QOS = [0x00, 0x01, 0x02]
  9389. /* Unsubscribe */
  9390. protocol.UNSUBSCRIBE_HEADER = genHeader('unsubscribe')
  9391. /* Confirmations */
  9392. protocol.ACKS = {
  9393. unsuback: genHeader('unsuback'),
  9394. puback: genHeader('puback'),
  9395. pubcomp: genHeader('pubcomp'),
  9396. pubrel: genHeader('pubrel'),
  9397. pubrec: genHeader('pubrec')
  9398. }
  9399. protocol.SUBACK_HEADER = Buffer.from([protocol.codes.suback << protocol.CMD_SHIFT])
  9400. /* Protocol versions */
  9401. protocol.VERSION3 = Buffer.from([3])
  9402. protocol.VERSION4 = Buffer.from([4])
  9403. protocol.VERSION5 = Buffer.from([5])
  9404. protocol.VERSION131 = Buffer.from([131])
  9405. protocol.VERSION132 = Buffer.from([132])
  9406. /* QoS */
  9407. protocol.QOS = [0, 1, 2].map(qos => {
  9408. return Buffer.from([qos])
  9409. })
  9410. /* Empty packets */
  9411. protocol.EMPTY = {
  9412. pingreq: Buffer.from([protocol.codes.pingreq << 4, 0]),
  9413. pingresp: Buffer.from([protocol.codes.pingresp << 4, 0]),
  9414. disconnect: Buffer.from([protocol.codes.disconnect << 4, 0])
  9415. }
  9416. }).call(this)}).call(this,require("buffer").Buffer)
  9417. },{"buffer":17}],39:[function(require,module,exports){
  9418. (function (Buffer){(function (){
  9419. const writeToStream = require('./writeToStream')
  9420. const EventEmitter = require('events')
  9421. function generate (packet, opts) {
  9422. const stream = new Accumulator()
  9423. writeToStream(packet, stream, opts)
  9424. return stream.concat()
  9425. }
  9426. class Accumulator extends EventEmitter {
  9427. constructor () {
  9428. super()
  9429. this._array = new Array(20)
  9430. this._i = 0
  9431. }
  9432. write (chunk) {
  9433. this._array[this._i++] = chunk
  9434. return true
  9435. }
  9436. concat () {
  9437. let length = 0
  9438. const lengths = new Array(this._array.length)
  9439. const list = this._array
  9440. let pos = 0
  9441. let i
  9442. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  9443. if (typeof list[i] !== 'string') lengths[i] = list[i].length
  9444. else lengths[i] = Buffer.byteLength(list[i])
  9445. length += lengths[i]
  9446. }
  9447. const result = Buffer.allocUnsafe(length)
  9448. for (i = 0; i < list.length && list[i] !== undefined; i++) {
  9449. if (typeof list[i] !== 'string') {
  9450. list[i].copy(result, pos)
  9451. pos += lengths[i]
  9452. } else {
  9453. result.write(list[i], pos)
  9454. pos += lengths[i]
  9455. }
  9456. }
  9457. return result
  9458. }
  9459. }
  9460. module.exports = generate
  9461. }).call(this)}).call(this,require("buffer").Buffer)
  9462. },{"./writeToStream":44,"buffer":17,"events":22}],40:[function(require,module,exports){
  9463. exports.parser = require('./parser').parser
  9464. exports.generate = require('./generate')
  9465. exports.writeToStream = require('./writeToStream')
  9466. },{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(require,module,exports){
  9467. (function (Buffer){(function (){
  9468. const max = 65536
  9469. const cache = {}
  9470. // in node 6 Buffer.subarray returns a Uint8Array instead of a Buffer
  9471. // later versions return a Buffer
  9472. // alternative is Buffer.slice but that creates a new buffer
  9473. // creating new buffers takes time
  9474. // SubOk is only false on node < 8
  9475. const SubOk = Buffer.isBuffer(Buffer.from([1, 2]).subarray(0, 1))
  9476. function generateBuffer (i) {
  9477. const buffer = Buffer.allocUnsafe(2)
  9478. buffer.writeUInt8(i >> 8, 0)
  9479. buffer.writeUInt8(i & 0x00FF, 0 + 1)
  9480. return buffer
  9481. }
  9482. function generateCache () {
  9483. for (let i = 0; i < max; i++) {
  9484. cache[i] = generateBuffer(i)
  9485. }
  9486. }
  9487. function genBufVariableByteInt (num) {
  9488. const maxLength = 4 // max 4 bytes
  9489. let digit = 0
  9490. let pos = 0
  9491. const buffer = Buffer.allocUnsafe(maxLength)
  9492. do {
  9493. digit = num % 128 | 0
  9494. num = num / 128 | 0
  9495. if (num > 0) digit = digit | 0x80
  9496. buffer.writeUInt8(digit, pos++)
  9497. } while (num > 0 && pos < maxLength)
  9498. if (num > 0) {
  9499. pos = 0
  9500. }
  9501. return SubOk ? buffer.subarray(0, pos) : buffer.slice(0, pos)
  9502. }
  9503. function generate4ByteBuffer (num) {
  9504. const buffer = Buffer.allocUnsafe(4)
  9505. buffer.writeUInt32BE(num, 0)
  9506. return buffer
  9507. }
  9508. module.exports = {
  9509. cache,
  9510. generateCache,
  9511. generateNumber: generateBuffer,
  9512. genBufVariableByteInt,
  9513. generate4ByteBuffer
  9514. }
  9515. }).call(this)}).call(this,require("buffer").Buffer)
  9516. },{"buffer":17}],42:[function(require,module,exports){
  9517. class Packet {
  9518. constructor () {
  9519. this.cmd = null
  9520. this.retain = false
  9521. this.qos = 0
  9522. this.dup = false
  9523. this.length = -1
  9524. this.topic = null
  9525. this.payload = null
  9526. }
  9527. }
  9528. module.exports = Packet
  9529. },{}],43:[function(require,module,exports){
  9530. const bl = require('bl')
  9531. const EventEmitter = require('events')
  9532. const Packet = require('./packet')
  9533. const constants = require('./constants')
  9534. const debug = require('debug')('mqtt-packet:parser')
  9535. class Parser extends EventEmitter {
  9536. constructor () {
  9537. super()
  9538. this.parser = this.constructor.parser
  9539. }
  9540. static parser (opt) {
  9541. if (!(this instanceof Parser)) return (new Parser()).parser(opt)
  9542. this.settings = opt || {}
  9543. this._states = [
  9544. '_parseHeader',
  9545. '_parseLength',
  9546. '_parsePayload',
  9547. '_newPacket'
  9548. ]
  9549. this._resetState()
  9550. return this
  9551. }
  9552. _resetState () {
  9553. debug('_resetState: resetting packet, error, _list, and _stateCounter')
  9554. this.packet = new Packet()
  9555. this.error = null
  9556. this._list = bl()
  9557. this._stateCounter = 0
  9558. }
  9559. parse (buf) {
  9560. if (this.error) this._resetState()
  9561. this._list.append(buf)
  9562. debug('parse: current state: %s', this._states[this._stateCounter])
  9563. while ((this.packet.length !== -1 || this._list.length > 0) &&
  9564. this[this._states[this._stateCounter]]() &&
  9565. !this.error) {
  9566. this._stateCounter++
  9567. debug('parse: state complete. _stateCounter is now: %d', this._stateCounter)
  9568. debug('parse: packet.length: %d, buffer list length: %d', this.packet.length, this._list.length)
  9569. if (this._stateCounter >= this._states.length) this._stateCounter = 0
  9570. }
  9571. debug('parse: exited while loop. packet: %d, buffer list length: %d', this.packet.length, this._list.length)
  9572. return this._list.length
  9573. }
  9574. _parseHeader () {
  9575. // There is at least one byte in the buffer
  9576. const zero = this._list.readUInt8(0)
  9577. this.packet.cmd = constants.types[zero >> constants.CMD_SHIFT]
  9578. this.packet.retain = (zero & constants.RETAIN_MASK) !== 0
  9579. this.packet.qos = (zero >> constants.QOS_SHIFT) & constants.QOS_MASK
  9580. this.packet.dup = (zero & constants.DUP_MASK) !== 0
  9581. debug('_parseHeader: packet: %o', this.packet)
  9582. this._list.consume(1)
  9583. return true
  9584. }
  9585. _parseLength () {
  9586. // There is at least one byte in the list
  9587. const result = this._parseVarByteNum(true)
  9588. if (result) {
  9589. this.packet.length = result.value
  9590. this._list.consume(result.bytes)
  9591. }
  9592. debug('_parseLength %d', result.value)
  9593. return !!result
  9594. }
  9595. _parsePayload () {
  9596. debug('_parsePayload: payload %O', this._list)
  9597. let result = false
  9598. // Do we have a payload? Do we have enough data to complete the payload?
  9599. // PINGs have no payload
  9600. if (this.packet.length === 0 || this._list.length >= this.packet.length) {
  9601. this._pos = 0
  9602. switch (this.packet.cmd) {
  9603. case 'connect':
  9604. this._parseConnect()
  9605. break
  9606. case 'connack':
  9607. this._parseConnack()
  9608. break
  9609. case 'publish':
  9610. this._parsePublish()
  9611. break
  9612. case 'puback':
  9613. case 'pubrec':
  9614. case 'pubrel':
  9615. case 'pubcomp':
  9616. this._parseConfirmation()
  9617. break
  9618. case 'subscribe':
  9619. this._parseSubscribe()
  9620. break
  9621. case 'suback':
  9622. this._parseSuback()
  9623. break
  9624. case 'unsubscribe':
  9625. this._parseUnsubscribe()
  9626. break
  9627. case 'unsuback':
  9628. this._parseUnsuback()
  9629. break
  9630. case 'pingreq':
  9631. case 'pingresp':
  9632. // These are empty, nothing to do
  9633. break
  9634. case 'disconnect':
  9635. this._parseDisconnect()
  9636. break
  9637. case 'auth':
  9638. this._parseAuth()
  9639. break
  9640. default:
  9641. this._emitError(new Error('Not supported'))
  9642. }
  9643. result = true
  9644. }
  9645. debug('_parsePayload complete result: %s', result)
  9646. return result
  9647. }
  9648. _parseConnect () {
  9649. debug('_parseConnect')
  9650. let topic // Will topic
  9651. let payload // Will payload
  9652. let password // Password
  9653. let username // Username
  9654. const flags = {}
  9655. const packet = this.packet
  9656. // Parse protocolId
  9657. const protocolId = this._parseString()
  9658. if (protocolId === null) return this._emitError(new Error('Cannot parse protocolId'))
  9659. if (protocolId !== 'MQTT' && protocolId !== 'MQIsdp') {
  9660. return this._emitError(new Error('Invalid protocolId'))
  9661. }
  9662. packet.protocolId = protocolId
  9663. // Parse constants version number
  9664. if (this._pos >= this._list.length) return this._emitError(new Error('Packet too short'))
  9665. packet.protocolVersion = this._list.readUInt8(this._pos)
  9666. if (packet.protocolVersion >= 128) {
  9667. packet.bridgeMode = true
  9668. packet.protocolVersion = packet.protocolVersion - 128
  9669. }
  9670. if (packet.protocolVersion !== 3 && packet.protocolVersion !== 4 && packet.protocolVersion !== 5) {
  9671. return this._emitError(new Error('Invalid protocol version'))
  9672. }
  9673. this._pos++
  9674. if (this._pos >= this._list.length) {
  9675. return this._emitError(new Error('Packet too short'))
  9676. }
  9677. // Parse connect flags
  9678. flags.username = (this._list.readUInt8(this._pos) & constants.USERNAME_MASK)
  9679. flags.password = (this._list.readUInt8(this._pos) & constants.PASSWORD_MASK)
  9680. flags.will = (this._list.readUInt8(this._pos) & constants.WILL_FLAG_MASK)
  9681. if (flags.will) {
  9682. packet.will = {}
  9683. packet.will.retain = (this._list.readUInt8(this._pos) & constants.WILL_RETAIN_MASK) !== 0
  9684. packet.will.qos = (this._list.readUInt8(this._pos) &
  9685. constants.WILL_QOS_MASK) >> constants.WILL_QOS_SHIFT
  9686. }
  9687. packet.clean = (this._list.readUInt8(this._pos) & constants.CLEAN_SESSION_MASK) !== 0
  9688. this._pos++
  9689. // Parse keepalive
  9690. packet.keepalive = this._parseNum()
  9691. if (packet.keepalive === -1) return this._emitError(new Error('Packet too short'))
  9692. // parse properties
  9693. if (packet.protocolVersion === 5) {
  9694. const properties = this._parseProperties()
  9695. if (Object.getOwnPropertyNames(properties).length) {
  9696. packet.properties = properties
  9697. }
  9698. }
  9699. // Parse clientId
  9700. const clientId = this._parseString()
  9701. if (clientId === null) return this._emitError(new Error('Packet too short'))
  9702. packet.clientId = clientId
  9703. debug('_parseConnect: packet.clientId: %s', packet.clientId)
  9704. if (flags.will) {
  9705. if (packet.protocolVersion === 5) {
  9706. const willProperties = this._parseProperties()
  9707. if (Object.getOwnPropertyNames(willProperties).length) {
  9708. packet.will.properties = willProperties
  9709. }
  9710. }
  9711. // Parse will topic
  9712. topic = this._parseString()
  9713. if (topic === null) return this._emitError(new Error('Cannot parse will topic'))
  9714. packet.will.topic = topic
  9715. debug('_parseConnect: packet.will.topic: %s', packet.will.topic)
  9716. // Parse will payload
  9717. payload = this._parseBuffer()
  9718. if (payload === null) return this._emitError(new Error('Cannot parse will payload'))
  9719. packet.will.payload = payload
  9720. debug('_parseConnect: packet.will.paylaod: %s', packet.will.payload)
  9721. }
  9722. // Parse username
  9723. if (flags.username) {
  9724. username = this._parseString()
  9725. if (username === null) return this._emitError(new Error('Cannot parse username'))
  9726. packet.username = username
  9727. debug('_parseConnect: packet.username: %s', packet.username)
  9728. }
  9729. // Parse password
  9730. if (flags.password) {
  9731. password = this._parseBuffer()
  9732. if (password === null) return this._emitError(new Error('Cannot parse password'))
  9733. packet.password = password
  9734. }
  9735. // need for right parse auth packet and self set up
  9736. this.settings = packet
  9737. debug('_parseConnect: complete')
  9738. return packet
  9739. }
  9740. _parseConnack () {
  9741. debug('_parseConnack')
  9742. const packet = this.packet
  9743. if (this._list.length < 1) return null
  9744. packet.sessionPresent = !!(this._list.readUInt8(this._pos++) & constants.SESSIONPRESENT_MASK)
  9745. if (this.settings.protocolVersion === 5) {
  9746. if (this._list.length >= 2) {
  9747. packet.reasonCode = this._list.readUInt8(this._pos++)
  9748. } else {
  9749. packet.reasonCode = 0
  9750. }
  9751. } else {
  9752. if (this._list.length < 2) return null
  9753. packet.returnCode = this._list.readUInt8(this._pos++)
  9754. }
  9755. if (packet.returnCode === -1 || packet.reasonCode === -1) return this._emitError(new Error('Cannot parse return code'))
  9756. // mqtt 5 properties
  9757. if (this.settings.protocolVersion === 5) {
  9758. const properties = this._parseProperties()
  9759. if (Object.getOwnPropertyNames(properties).length) {
  9760. packet.properties = properties
  9761. }
  9762. }
  9763. debug('_parseConnack: complete')
  9764. }
  9765. _parsePublish () {
  9766. debug('_parsePublish')
  9767. const packet = this.packet
  9768. packet.topic = this._parseString()
  9769. if (packet.topic === null) return this._emitError(new Error('Cannot parse topic'))
  9770. // Parse messageId
  9771. if (packet.qos > 0) if (!this._parseMessageId()) { return }
  9772. // Properties mqtt 5
  9773. if (this.settings.protocolVersion === 5) {
  9774. const properties = this._parseProperties()
  9775. if (Object.getOwnPropertyNames(properties).length) {
  9776. packet.properties = properties
  9777. }
  9778. }
  9779. packet.payload = this._list.slice(this._pos, packet.length)
  9780. debug('_parsePublish: payload from buffer list: %o', packet.payload)
  9781. }
  9782. _parseSubscribe () {
  9783. debug('_parseSubscribe')
  9784. const packet = this.packet
  9785. let topic
  9786. let options
  9787. let qos
  9788. let rh
  9789. let rap
  9790. let nl
  9791. let subscription
  9792. if (packet.qos !== 1) {
  9793. return this._emitError(new Error('Wrong subscribe header'))
  9794. }
  9795. packet.subscriptions = []
  9796. if (!this._parseMessageId()) { return }
  9797. // Properties mqtt 5
  9798. if (this.settings.protocolVersion === 5) {
  9799. const properties = this._parseProperties()
  9800. if (Object.getOwnPropertyNames(properties).length) {
  9801. packet.properties = properties
  9802. }
  9803. }
  9804. while (this._pos < packet.length) {
  9805. // Parse topic
  9806. topic = this._parseString()
  9807. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  9808. if (this._pos >= packet.length) return this._emitError(new Error('Malformed Subscribe Payload'))
  9809. options = this._parseByte()
  9810. qos = options & constants.SUBSCRIBE_OPTIONS_QOS_MASK
  9811. nl = ((options >> constants.SUBSCRIBE_OPTIONS_NL_SHIFT) & constants.SUBSCRIBE_OPTIONS_NL_MASK) !== 0
  9812. rap = ((options >> constants.SUBSCRIBE_OPTIONS_RAP_SHIFT) & constants.SUBSCRIBE_OPTIONS_RAP_MASK) !== 0
  9813. rh = (options >> constants.SUBSCRIBE_OPTIONS_RH_SHIFT) & constants.SUBSCRIBE_OPTIONS_RH_MASK
  9814. subscription = { topic, qos }
  9815. // mqtt 5 options
  9816. if (this.settings.protocolVersion === 5) {
  9817. subscription.nl = nl
  9818. subscription.rap = rap
  9819. subscription.rh = rh
  9820. } else if (this.settings.bridgeMode) {
  9821. subscription.rh = 0
  9822. subscription.rap = true
  9823. subscription.nl = true
  9824. }
  9825. // Push pair to subscriptions
  9826. debug('_parseSubscribe: push subscription `%s` to subscription', subscription)
  9827. packet.subscriptions.push(subscription)
  9828. }
  9829. }
  9830. _parseSuback () {
  9831. debug('_parseSuback')
  9832. const packet = this.packet
  9833. this.packet.granted = []
  9834. if (!this._parseMessageId()) { return }
  9835. // Properties mqtt 5
  9836. if (this.settings.protocolVersion === 5) {
  9837. const properties = this._parseProperties()
  9838. if (Object.getOwnPropertyNames(properties).length) {
  9839. packet.properties = properties
  9840. }
  9841. }
  9842. // Parse granted QoSes
  9843. while (this._pos < this.packet.length) {
  9844. this.packet.granted.push(this._list.readUInt8(this._pos++))
  9845. }
  9846. }
  9847. _parseUnsubscribe () {
  9848. debug('_parseUnsubscribe')
  9849. const packet = this.packet
  9850. packet.unsubscriptions = []
  9851. // Parse messageId
  9852. if (!this._parseMessageId()) { return }
  9853. // Properties mqtt 5
  9854. if (this.settings.protocolVersion === 5) {
  9855. const properties = this._parseProperties()
  9856. if (Object.getOwnPropertyNames(properties).length) {
  9857. packet.properties = properties
  9858. }
  9859. }
  9860. while (this._pos < packet.length) {
  9861. // Parse topic
  9862. const topic = this._parseString()
  9863. if (topic === null) return this._emitError(new Error('Cannot parse topic'))
  9864. // Push topic to unsubscriptions
  9865. debug('_parseUnsubscribe: push topic `%s` to unsubscriptions', topic)
  9866. packet.unsubscriptions.push(topic)
  9867. }
  9868. }
  9869. _parseUnsuback () {
  9870. debug('_parseUnsuback')
  9871. const packet = this.packet
  9872. if (!this._parseMessageId()) return this._emitError(new Error('Cannot parse messageId'))
  9873. // Properties mqtt 5
  9874. if (this.settings.protocolVersion === 5) {
  9875. const properties = this._parseProperties()
  9876. if (Object.getOwnPropertyNames(properties).length) {
  9877. packet.properties = properties
  9878. }
  9879. // Parse granted QoSes
  9880. packet.granted = []
  9881. while (this._pos < this.packet.length) {
  9882. this.packet.granted.push(this._list.readUInt8(this._pos++))
  9883. }
  9884. }
  9885. }
  9886. // parse packets like puback, pubrec, pubrel, pubcomp
  9887. _parseConfirmation () {
  9888. debug('_parseConfirmation: packet.cmd: `%s`', this.packet.cmd)
  9889. const packet = this.packet
  9890. this._parseMessageId()
  9891. if (this.settings.protocolVersion === 5) {
  9892. if (packet.length > 2) {
  9893. // response code
  9894. packet.reasonCode = this._parseByte()
  9895. debug('_parseConfirmation: packet.reasonCode `%d`', packet.reasonCode)
  9896. } else {
  9897. packet.reasonCode = 0
  9898. }
  9899. if (packet.length > 3) {
  9900. // properies mqtt 5
  9901. const properties = this._parseProperties()
  9902. if (Object.getOwnPropertyNames(properties).length) {
  9903. packet.properties = properties
  9904. }
  9905. }
  9906. }
  9907. return true
  9908. }
  9909. // parse disconnect packet
  9910. _parseDisconnect () {
  9911. const packet = this.packet
  9912. debug('_parseDisconnect')
  9913. if (this.settings.protocolVersion === 5) {
  9914. // response code
  9915. if (this._list.length > 0) {
  9916. packet.reasonCode = this._parseByte()
  9917. } else {
  9918. packet.reasonCode = 0
  9919. }
  9920. // properies mqtt 5
  9921. const properties = this._parseProperties()
  9922. if (Object.getOwnPropertyNames(properties).length) {
  9923. packet.properties = properties
  9924. }
  9925. }
  9926. debug('_parseDisconnect result: true')
  9927. return true
  9928. }
  9929. // parse auth packet
  9930. _parseAuth () {
  9931. debug('_parseAuth')
  9932. const packet = this.packet
  9933. if (this.settings.protocolVersion !== 5) {
  9934. return this._emitError(new Error('Not supported auth packet for this version MQTT'))
  9935. }
  9936. // response code
  9937. packet.reasonCode = this._parseByte()
  9938. // properies mqtt 5
  9939. const properties = this._parseProperties()
  9940. if (Object.getOwnPropertyNames(properties).length) {
  9941. packet.properties = properties
  9942. }
  9943. debug('_parseAuth: result: true')
  9944. return true
  9945. }
  9946. _parseMessageId () {
  9947. const packet = this.packet
  9948. packet.messageId = this._parseNum()
  9949. if (packet.messageId === null) {
  9950. this._emitError(new Error('Cannot parse messageId'))
  9951. return false
  9952. }
  9953. debug('_parseMessageId: packet.messageId %d', packet.messageId)
  9954. return true
  9955. }
  9956. _parseString (maybeBuffer) {
  9957. const length = this._parseNum()
  9958. const end = length + this._pos
  9959. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  9960. const result = this._list.toString('utf8', this._pos, end)
  9961. this._pos += length
  9962. debug('_parseString: result: %s', result)
  9963. return result
  9964. }
  9965. _parseStringPair () {
  9966. debug('_parseStringPair')
  9967. return {
  9968. name: this._parseString(),
  9969. value: this._parseString()
  9970. }
  9971. }
  9972. _parseBuffer () {
  9973. const length = this._parseNum()
  9974. const end = length + this._pos
  9975. if (length === -1 || end > this._list.length || end > this.packet.length) return null
  9976. const result = this._list.slice(this._pos, end)
  9977. this._pos += length
  9978. debug('_parseBuffer: result: %o', result)
  9979. return result
  9980. }
  9981. _parseNum () {
  9982. if (this._list.length - this._pos < 2) return -1
  9983. const result = this._list.readUInt16BE(this._pos)
  9984. this._pos += 2
  9985. debug('_parseNum: result: %s', result)
  9986. return result
  9987. }
  9988. _parse4ByteNum () {
  9989. if (this._list.length - this._pos < 4) return -1
  9990. const result = this._list.readUInt32BE(this._pos)
  9991. this._pos += 4
  9992. debug('_parse4ByteNum: result: %s', result)
  9993. return result
  9994. }
  9995. _parseVarByteNum (fullInfoFlag) {
  9996. debug('_parseVarByteNum')
  9997. const maxBytes = 4
  9998. let bytes = 0
  9999. let mul = 1
  10000. let value = 0
  10001. let result = false
  10002. let current
  10003. const padding = this._pos ? this._pos : 0
  10004. while (bytes < maxBytes && (padding + bytes) < this._list.length) {
  10005. current = this._list.readUInt8(padding + bytes++)
  10006. value += mul * (current & constants.VARBYTEINT_MASK)
  10007. mul *= 0x80
  10008. if ((current & constants.VARBYTEINT_FIN_MASK) === 0) {
  10009. result = true
  10010. break
  10011. }
  10012. if (this._list.length <= bytes) {
  10013. break
  10014. }
  10015. }
  10016. if (!result && bytes === maxBytes && this._list.length >= bytes) {
  10017. this._emitError(new Error('Invalid variable byte integer'))
  10018. }
  10019. if (padding) {
  10020. this._pos += bytes
  10021. }
  10022. result = result
  10023. ? fullInfoFlag ? {
  10024. bytes,
  10025. value
  10026. } : value
  10027. : false
  10028. debug('_parseVarByteNum: result: %o', result)
  10029. return result
  10030. }
  10031. _parseByte () {
  10032. let result
  10033. if (this._pos < this._list.length) {
  10034. result = this._list.readUInt8(this._pos)
  10035. this._pos++
  10036. }
  10037. debug('_parseByte: result: %o', result)
  10038. return result
  10039. }
  10040. _parseByType (type) {
  10041. debug('_parseByType: type: %s', type)
  10042. switch (type) {
  10043. case 'byte': {
  10044. return this._parseByte() !== 0
  10045. }
  10046. case 'int8': {
  10047. return this._parseByte()
  10048. }
  10049. case 'int16': {
  10050. return this._parseNum()
  10051. }
  10052. case 'int32': {
  10053. return this._parse4ByteNum()
  10054. }
  10055. case 'var': {
  10056. return this._parseVarByteNum()
  10057. }
  10058. case 'string': {
  10059. return this._parseString()
  10060. }
  10061. case 'pair': {
  10062. return this._parseStringPair()
  10063. }
  10064. case 'binary': {
  10065. return this._parseBuffer()
  10066. }
  10067. }
  10068. }
  10069. _parseProperties () {
  10070. debug('_parseProperties')
  10071. const length = this._parseVarByteNum()
  10072. const start = this._pos
  10073. const end = start + length
  10074. const result = {}
  10075. while (this._pos < end) {
  10076. const type = this._parseByte()
  10077. if (!type) {
  10078. this._emitError(new Error('Cannot parse property code type'))
  10079. return false
  10080. }
  10081. const name = constants.propertiesCodes[type]
  10082. if (!name) {
  10083. this._emitError(new Error('Unknown property'))
  10084. return false
  10085. }
  10086. // user properties process
  10087. if (name === 'userProperties') {
  10088. if (!result[name]) {
  10089. result[name] = Object.create(null)
  10090. }
  10091. const currentUserProperty = this._parseByType(constants.propertiesTypes[name])
  10092. if (result[name][currentUserProperty.name]) {
  10093. if (Array.isArray(result[name][currentUserProperty.name])) {
  10094. result[name][currentUserProperty.name].push(currentUserProperty.value)
  10095. } else {
  10096. const currentValue = result[name][currentUserProperty.name]
  10097. result[name][currentUserProperty.name] = [currentValue]
  10098. result[name][currentUserProperty.name].push(currentUserProperty.value)
  10099. }
  10100. } else {
  10101. result[name][currentUserProperty.name] = currentUserProperty.value
  10102. }
  10103. continue
  10104. }
  10105. if (result[name]) {
  10106. if (Array.isArray(result[name])) {
  10107. result[name].push(this._parseByType(constants.propertiesTypes[name]))
  10108. } else {
  10109. result[name] = [result[name]]
  10110. result[name].push(this._parseByType(constants.propertiesTypes[name]))
  10111. }
  10112. } else {
  10113. result[name] = this._parseByType(constants.propertiesTypes[name])
  10114. }
  10115. }
  10116. return result
  10117. }
  10118. _newPacket () {
  10119. debug('_newPacket')
  10120. if (this.packet) {
  10121. this._list.consume(this.packet.length)
  10122. debug('_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d', this.packet.cmd, this.packet.payload, this.packet.length)
  10123. this.emit('packet', this.packet)
  10124. }
  10125. debug('_newPacket: new packet')
  10126. this.packet = new Packet()
  10127. this._pos = 0
  10128. return true
  10129. }
  10130. _emitError (err) {
  10131. debug('_emitError')
  10132. this.error = err
  10133. this.emit('error', err)
  10134. }
  10135. }
  10136. module.exports = Parser
  10137. },{"./constants":38,"./packet":42,"bl":15,"debug":18,"events":22}],44:[function(require,module,exports){
  10138. (function (Buffer){(function (){
  10139. const protocol = require('./constants')
  10140. const empty = Buffer.allocUnsafe(0)
  10141. const zeroBuf = Buffer.from([0])
  10142. const numbers = require('./numbers')
  10143. const nextTick = require('process-nextick-args').nextTick
  10144. const debug = require('debug')('mqtt-packet:writeToStream')
  10145. const numCache = numbers.cache
  10146. const generateNumber = numbers.generateNumber
  10147. const generateCache = numbers.generateCache
  10148. const genBufVariableByteInt = numbers.genBufVariableByteInt
  10149. const generate4ByteBuffer = numbers.generate4ByteBuffer
  10150. let writeNumber = writeNumberCached
  10151. let toGenerate = true
  10152. function generate (packet, stream, opts) {
  10153. debug('generate called')
  10154. if (stream.cork) {
  10155. stream.cork()
  10156. nextTick(uncork, stream)
  10157. }
  10158. if (toGenerate) {
  10159. toGenerate = false
  10160. generateCache()
  10161. }
  10162. debug('generate: packet.cmd: %s', packet.cmd)
  10163. switch (packet.cmd) {
  10164. case 'connect':
  10165. return connect(packet, stream, opts)
  10166. case 'connack':
  10167. return connack(packet, stream, opts)
  10168. case 'publish':
  10169. return publish(packet, stream, opts)
  10170. case 'puback':
  10171. case 'pubrec':
  10172. case 'pubrel':
  10173. case 'pubcomp':
  10174. return confirmation(packet, stream, opts)
  10175. case 'subscribe':
  10176. return subscribe(packet, stream, opts)
  10177. case 'suback':
  10178. return suback(packet, stream, opts)
  10179. case 'unsubscribe':
  10180. return unsubscribe(packet, stream, opts)
  10181. case 'unsuback':
  10182. return unsuback(packet, stream, opts)
  10183. case 'pingreq':
  10184. case 'pingresp':
  10185. return emptyPacket(packet, stream, opts)
  10186. case 'disconnect':
  10187. return disconnect(packet, stream, opts)
  10188. case 'auth':
  10189. return auth(packet, stream, opts)
  10190. default:
  10191. stream.emit('error', new Error('Unknown command'))
  10192. return false
  10193. }
  10194. }
  10195. /**
  10196. * Controls numbers cache.
  10197. * Set to "false" to allocate buffers on-the-flight instead of pre-generated cache
  10198. */
  10199. Object.defineProperty(generate, 'cacheNumbers', {
  10200. get () {
  10201. return writeNumber === writeNumberCached
  10202. },
  10203. set (value) {
  10204. if (value) {
  10205. if (!numCache || Object.keys(numCache).length === 0) toGenerate = true
  10206. writeNumber = writeNumberCached
  10207. } else {
  10208. toGenerate = false
  10209. writeNumber = writeNumberGenerated
  10210. }
  10211. }
  10212. })
  10213. function uncork (stream) {
  10214. stream.uncork()
  10215. }
  10216. function connect (packet, stream, opts) {
  10217. const settings = packet || {}
  10218. const protocolId = settings.protocolId || 'MQTT'
  10219. let protocolVersion = settings.protocolVersion || 4
  10220. const will = settings.will
  10221. let clean = settings.clean
  10222. const keepalive = settings.keepalive || 0
  10223. const clientId = settings.clientId || ''
  10224. const username = settings.username
  10225. const password = settings.password
  10226. /* mqtt5 new oprions */
  10227. const properties = settings.properties
  10228. if (clean === undefined) clean = true
  10229. let length = 0
  10230. // Must be a string and non-falsy
  10231. if (!protocolId ||
  10232. (typeof protocolId !== 'string' && !Buffer.isBuffer(protocolId))) {
  10233. stream.emit('error', new Error('Invalid protocolId'))
  10234. return false
  10235. } else length += protocolId.length + 2
  10236. // Must be 3 or 4 or 5
  10237. if (protocolVersion !== 3 && protocolVersion !== 4 && protocolVersion !== 5) {
  10238. stream.emit('error', new Error('Invalid protocol version'))
  10239. return false
  10240. } else length += 1
  10241. // ClientId might be omitted in 3.1.1 and 5, but only if cleanSession is set to 1
  10242. if ((typeof clientId === 'string' || Buffer.isBuffer(clientId)) &&
  10243. (clientId || protocolVersion >= 4) && (clientId || clean)) {
  10244. length += Buffer.byteLength(clientId) + 2
  10245. } else {
  10246. if (protocolVersion < 4) {
  10247. stream.emit('error', new Error('clientId must be supplied before 3.1.1'))
  10248. return false
  10249. }
  10250. if ((clean * 1) === 0) {
  10251. stream.emit('error', new Error('clientId must be given if cleanSession set to 0'))
  10252. return false
  10253. }
  10254. }
  10255. // Must be a two byte number
  10256. if (typeof keepalive !== 'number' ||
  10257. keepalive < 0 ||
  10258. keepalive > 65535 ||
  10259. keepalive % 1 !== 0) {
  10260. stream.emit('error', new Error('Invalid keepalive'))
  10261. return false
  10262. } else length += 2
  10263. // Connect flags
  10264. length += 1
  10265. // Properties
  10266. if (protocolVersion === 5) {
  10267. var propertiesData = getProperties(stream, properties)
  10268. if (!propertiesData) { return false }
  10269. length += propertiesData.length
  10270. }
  10271. // If will exists...
  10272. if (will) {
  10273. // It must be an object
  10274. if (typeof will !== 'object') {
  10275. stream.emit('error', new Error('Invalid will'))
  10276. return false
  10277. }
  10278. // It must have topic typeof string
  10279. if (!will.topic || typeof will.topic !== 'string') {
  10280. stream.emit('error', new Error('Invalid will topic'))
  10281. return false
  10282. } else {
  10283. length += Buffer.byteLength(will.topic) + 2
  10284. }
  10285. // Payload
  10286. length += 2 // payload length
  10287. if (will.payload) {
  10288. if (will.payload.length >= 0) {
  10289. if (typeof will.payload === 'string') {
  10290. length += Buffer.byteLength(will.payload)
  10291. } else {
  10292. length += will.payload.length
  10293. }
  10294. } else {
  10295. stream.emit('error', new Error('Invalid will payload'))
  10296. return false
  10297. }
  10298. }
  10299. // will properties
  10300. var willProperties = {}
  10301. if (protocolVersion === 5) {
  10302. willProperties = getProperties(stream, will.properties)
  10303. if (!willProperties) { return false }
  10304. length += willProperties.length
  10305. }
  10306. }
  10307. // Username
  10308. let providedUsername = false
  10309. if (username != null) {
  10310. if (isStringOrBuffer(username)) {
  10311. providedUsername = true
  10312. length += Buffer.byteLength(username) + 2
  10313. } else {
  10314. stream.emit('error', new Error('Invalid username'))
  10315. return false
  10316. }
  10317. }
  10318. // Password
  10319. if (password != null) {
  10320. if (!providedUsername) {
  10321. stream.emit('error', new Error('Username is required to use password'))
  10322. return false
  10323. }
  10324. if (isStringOrBuffer(password)) {
  10325. length += byteLength(password) + 2
  10326. } else {
  10327. stream.emit('error', new Error('Invalid password'))
  10328. return false
  10329. }
  10330. }
  10331. // Generate header
  10332. stream.write(protocol.CONNECT_HEADER)
  10333. // Generate length
  10334. writeVarByteInt(stream, length)
  10335. // Generate protocol ID
  10336. writeStringOrBuffer(stream, protocolId)
  10337. if (settings.bridgeMode) {
  10338. protocolVersion += 128
  10339. }
  10340. stream.write(
  10341. protocolVersion === 131
  10342. ? protocol.VERSION131
  10343. : protocolVersion === 132
  10344. ? protocol.VERSION132
  10345. : protocolVersion === 4
  10346. ? protocol.VERSION4
  10347. : protocolVersion === 5
  10348. ? protocol.VERSION5
  10349. : protocol.VERSION3
  10350. )
  10351. // Connect flags
  10352. let flags = 0
  10353. flags |= (username != null) ? protocol.USERNAME_MASK : 0
  10354. flags |= (password != null) ? protocol.PASSWORD_MASK : 0
  10355. flags |= (will && will.retain) ? protocol.WILL_RETAIN_MASK : 0
  10356. flags |= (will && will.qos) ? will.qos << protocol.WILL_QOS_SHIFT : 0
  10357. flags |= will ? protocol.WILL_FLAG_MASK : 0
  10358. flags |= clean ? protocol.CLEAN_SESSION_MASK : 0
  10359. stream.write(Buffer.from([flags]))
  10360. // Keepalive
  10361. writeNumber(stream, keepalive)
  10362. // Properties
  10363. if (protocolVersion === 5) {
  10364. propertiesData.write()
  10365. }
  10366. // Client ID
  10367. writeStringOrBuffer(stream, clientId)
  10368. // Will
  10369. if (will) {
  10370. if (protocolVersion === 5) {
  10371. willProperties.write()
  10372. }
  10373. writeString(stream, will.topic)
  10374. writeStringOrBuffer(stream, will.payload)
  10375. }
  10376. // Username and password
  10377. if (username != null) {
  10378. writeStringOrBuffer(stream, username)
  10379. }
  10380. if (password != null) {
  10381. writeStringOrBuffer(stream, password)
  10382. }
  10383. // This is a small packet that happens only once on a stream
  10384. // We assume the stream is always free to receive more data after this
  10385. return true
  10386. }
  10387. function connack (packet, stream, opts) {
  10388. const version = opts ? opts.protocolVersion : 4
  10389. const settings = packet || {}
  10390. const rc = version === 5 ? settings.reasonCode : settings.returnCode
  10391. const properties = settings.properties
  10392. let length = 2 // length of rc and sessionHeader
  10393. // Check return code
  10394. if (typeof rc !== 'number') {
  10395. stream.emit('error', new Error('Invalid return code'))
  10396. return false
  10397. }
  10398. // mqtt5 properties
  10399. let propertiesData = null
  10400. if (version === 5) {
  10401. propertiesData = getProperties(stream, properties)
  10402. if (!propertiesData) { return false }
  10403. length += propertiesData.length
  10404. }
  10405. stream.write(protocol.CONNACK_HEADER)
  10406. // length
  10407. writeVarByteInt(stream, length)
  10408. stream.write(settings.sessionPresent ? protocol.SESSIONPRESENT_HEADER : zeroBuf)
  10409. stream.write(Buffer.from([rc]))
  10410. if (propertiesData != null) {
  10411. propertiesData.write()
  10412. }
  10413. return true
  10414. }
  10415. function publish (packet, stream, opts) {
  10416. debug('publish: packet: %o', packet)
  10417. const version = opts ? opts.protocolVersion : 4
  10418. const settings = packet || {}
  10419. const qos = settings.qos || 0
  10420. const retain = settings.retain ? protocol.RETAIN_MASK : 0
  10421. const topic = settings.topic
  10422. const payload = settings.payload || empty
  10423. const id = settings.messageId
  10424. const properties = settings.properties
  10425. let length = 0
  10426. // Topic must be a non-empty string or Buffer
  10427. if (typeof topic === 'string') length += Buffer.byteLength(topic) + 2
  10428. else if (Buffer.isBuffer(topic)) length += topic.length + 2
  10429. else {
  10430. stream.emit('error', new Error('Invalid topic'))
  10431. return false
  10432. }
  10433. // Get the payload length
  10434. if (!Buffer.isBuffer(payload)) length += Buffer.byteLength(payload)
  10435. else length += payload.length
  10436. // Message ID must a number if qos > 0
  10437. if (qos && typeof id !== 'number') {
  10438. stream.emit('error', new Error('Invalid messageId'))
  10439. return false
  10440. } else if (qos) length += 2
  10441. // mqtt5 properties
  10442. let propertiesData = null
  10443. if (version === 5) {
  10444. propertiesData = getProperties(stream, properties)
  10445. if (!propertiesData) { return false }
  10446. length += propertiesData.length
  10447. }
  10448. // Header
  10449. stream.write(protocol.PUBLISH_HEADER[qos][settings.dup ? 1 : 0][retain ? 1 : 0])
  10450. // Remaining length
  10451. writeVarByteInt(stream, length)
  10452. // Topic
  10453. writeNumber(stream, byteLength(topic))
  10454. stream.write(topic)
  10455. // Message ID
  10456. if (qos > 0) writeNumber(stream, id)
  10457. // Properties
  10458. if (propertiesData != null) {
  10459. propertiesData.write()
  10460. }
  10461. // Payload
  10462. debug('publish: payload: %o', payload)
  10463. return stream.write(payload)
  10464. }
  10465. /* Puback, pubrec, pubrel and pubcomp */
  10466. function confirmation (packet, stream, opts) {
  10467. const version = opts ? opts.protocolVersion : 4
  10468. const settings = packet || {}
  10469. const type = settings.cmd || 'puback'
  10470. const id = settings.messageId
  10471. const dup = (settings.dup && type === 'pubrel') ? protocol.DUP_MASK : 0
  10472. let qos = 0
  10473. const reasonCode = settings.reasonCode
  10474. const properties = settings.properties
  10475. let length = version === 5 ? 3 : 2
  10476. if (type === 'pubrel') qos = 1
  10477. // Check message ID
  10478. if (typeof id !== 'number') {
  10479. stream.emit('error', new Error('Invalid messageId'))
  10480. return false
  10481. }
  10482. // properies mqtt 5
  10483. let propertiesData = null
  10484. if (version === 5) {
  10485. // Confirm should not add empty property length with no properties (rfc 3.4.2.2.1)
  10486. if (typeof properties === 'object') {
  10487. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  10488. if (!propertiesData) { return false }
  10489. length += propertiesData.length
  10490. }
  10491. }
  10492. // Header
  10493. stream.write(protocol.ACKS[type][qos][dup][0])
  10494. // Length
  10495. writeVarByteInt(stream, length)
  10496. // Message ID
  10497. writeNumber(stream, id)
  10498. // reason code in header
  10499. if (version === 5) {
  10500. stream.write(Buffer.from([reasonCode]))
  10501. }
  10502. // properies mqtt 5
  10503. if (propertiesData !== null) {
  10504. propertiesData.write()
  10505. }
  10506. return true
  10507. }
  10508. function subscribe (packet, stream, opts) {
  10509. debug('subscribe: packet: ')
  10510. const version = opts ? opts.protocolVersion : 4
  10511. const settings = packet || {}
  10512. const dup = settings.dup ? protocol.DUP_MASK : 0
  10513. const id = settings.messageId
  10514. const subs = settings.subscriptions
  10515. const properties = settings.properties
  10516. let length = 0
  10517. // Check message ID
  10518. if (typeof id !== 'number') {
  10519. stream.emit('error', new Error('Invalid messageId'))
  10520. return false
  10521. } else length += 2
  10522. // properies mqtt 5
  10523. let propertiesData = null
  10524. if (version === 5) {
  10525. propertiesData = getProperties(stream, properties)
  10526. if (!propertiesData) { return false }
  10527. length += propertiesData.length
  10528. }
  10529. // Check subscriptions
  10530. if (typeof subs === 'object' && subs.length) {
  10531. for (let i = 0; i < subs.length; i += 1) {
  10532. const itopic = subs[i].topic
  10533. const iqos = subs[i].qos
  10534. if (typeof itopic !== 'string') {
  10535. stream.emit('error', new Error('Invalid subscriptions - invalid topic'))
  10536. return false
  10537. }
  10538. if (typeof iqos !== 'number') {
  10539. stream.emit('error', new Error('Invalid subscriptions - invalid qos'))
  10540. return false
  10541. }
  10542. if (version === 5) {
  10543. const nl = subs[i].nl || false
  10544. if (typeof nl !== 'boolean') {
  10545. stream.emit('error', new Error('Invalid subscriptions - invalid No Local'))
  10546. return false
  10547. }
  10548. const rap = subs[i].rap || false
  10549. if (typeof rap !== 'boolean') {
  10550. stream.emit('error', new Error('Invalid subscriptions - invalid Retain as Published'))
  10551. return false
  10552. }
  10553. const rh = subs[i].rh || 0
  10554. if (typeof rh !== 'number' || rh > 2) {
  10555. stream.emit('error', new Error('Invalid subscriptions - invalid Retain Handling'))
  10556. return false
  10557. }
  10558. }
  10559. length += Buffer.byteLength(itopic) + 2 + 1
  10560. }
  10561. } else {
  10562. stream.emit('error', new Error('Invalid subscriptions'))
  10563. return false
  10564. }
  10565. // Generate header
  10566. debug('subscribe: writing to stream: %o', protocol.SUBSCRIBE_HEADER)
  10567. stream.write(protocol.SUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  10568. // Generate length
  10569. writeVarByteInt(stream, length)
  10570. // Generate message ID
  10571. writeNumber(stream, id)
  10572. // properies mqtt 5
  10573. if (propertiesData !== null) {
  10574. propertiesData.write()
  10575. }
  10576. let result = true
  10577. // Generate subs
  10578. for (const sub of subs) {
  10579. const jtopic = sub.topic
  10580. const jqos = sub.qos
  10581. const jnl = +sub.nl
  10582. const jrap = +sub.rap
  10583. const jrh = sub.rh
  10584. let joptions
  10585. // Write topic string
  10586. writeString(stream, jtopic)
  10587. // options process
  10588. joptions = protocol.SUBSCRIBE_OPTIONS_QOS[jqos]
  10589. if (version === 5) {
  10590. joptions |= jnl ? protocol.SUBSCRIBE_OPTIONS_NL : 0
  10591. joptions |= jrap ? protocol.SUBSCRIBE_OPTIONS_RAP : 0
  10592. joptions |= jrh ? protocol.SUBSCRIBE_OPTIONS_RH[jrh] : 0
  10593. }
  10594. // Write options
  10595. result = stream.write(Buffer.from([joptions]))
  10596. }
  10597. return result
  10598. }
  10599. function suback (packet, stream, opts) {
  10600. const version = opts ? opts.protocolVersion : 4
  10601. const settings = packet || {}
  10602. const id = settings.messageId
  10603. const granted = settings.granted
  10604. const properties = settings.properties
  10605. let length = 0
  10606. // Check message ID
  10607. if (typeof id !== 'number') {
  10608. stream.emit('error', new Error('Invalid messageId'))
  10609. return false
  10610. } else length += 2
  10611. // Check granted qos vector
  10612. if (typeof granted === 'object' && granted.length) {
  10613. for (let i = 0; i < granted.length; i += 1) {
  10614. if (typeof granted[i] !== 'number') {
  10615. stream.emit('error', new Error('Invalid qos vector'))
  10616. return false
  10617. }
  10618. length += 1
  10619. }
  10620. } else {
  10621. stream.emit('error', new Error('Invalid qos vector'))
  10622. return false
  10623. }
  10624. // properies mqtt 5
  10625. let propertiesData = null
  10626. if (version === 5) {
  10627. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  10628. if (!propertiesData) { return false }
  10629. length += propertiesData.length
  10630. }
  10631. // header
  10632. stream.write(protocol.SUBACK_HEADER)
  10633. // Length
  10634. writeVarByteInt(stream, length)
  10635. // Message ID
  10636. writeNumber(stream, id)
  10637. // properies mqtt 5
  10638. if (propertiesData !== null) {
  10639. propertiesData.write()
  10640. }
  10641. return stream.write(Buffer.from(granted))
  10642. }
  10643. function unsubscribe (packet, stream, opts) {
  10644. const version = opts ? opts.protocolVersion : 4
  10645. const settings = packet || {}
  10646. const id = settings.messageId
  10647. const dup = settings.dup ? protocol.DUP_MASK : 0
  10648. const unsubs = settings.unsubscriptions
  10649. const properties = settings.properties
  10650. let length = 0
  10651. // Check message ID
  10652. if (typeof id !== 'number') {
  10653. stream.emit('error', new Error('Invalid messageId'))
  10654. return false
  10655. } else {
  10656. length += 2
  10657. }
  10658. // Check unsubs
  10659. if (typeof unsubs === 'object' && unsubs.length) {
  10660. for (let i = 0; i < unsubs.length; i += 1) {
  10661. if (typeof unsubs[i] !== 'string') {
  10662. stream.emit('error', new Error('Invalid unsubscriptions'))
  10663. return false
  10664. }
  10665. length += Buffer.byteLength(unsubs[i]) + 2
  10666. }
  10667. } else {
  10668. stream.emit('error', new Error('Invalid unsubscriptions'))
  10669. return false
  10670. }
  10671. // properies mqtt 5
  10672. let propertiesData = null
  10673. if (version === 5) {
  10674. propertiesData = getProperties(stream, properties)
  10675. if (!propertiesData) { return false }
  10676. length += propertiesData.length
  10677. }
  10678. // Header
  10679. stream.write(protocol.UNSUBSCRIBE_HEADER[1][dup ? 1 : 0][0])
  10680. // Length
  10681. writeVarByteInt(stream, length)
  10682. // Message ID
  10683. writeNumber(stream, id)
  10684. // properies mqtt 5
  10685. if (propertiesData !== null) {
  10686. propertiesData.write()
  10687. }
  10688. // Unsubs
  10689. let result = true
  10690. for (let j = 0; j < unsubs.length; j++) {
  10691. result = writeString(stream, unsubs[j])
  10692. }
  10693. return result
  10694. }
  10695. function unsuback (packet, stream, opts) {
  10696. const version = opts ? opts.protocolVersion : 4
  10697. const settings = packet || {}
  10698. const id = settings.messageId
  10699. const dup = settings.dup ? protocol.DUP_MASK : 0
  10700. const granted = settings.granted
  10701. const properties = settings.properties
  10702. const type = settings.cmd
  10703. const qos = 0
  10704. let length = 2
  10705. // Check message ID
  10706. if (typeof id !== 'number') {
  10707. stream.emit('error', new Error('Invalid messageId'))
  10708. return false
  10709. }
  10710. // Check granted
  10711. if (version === 5) {
  10712. if (typeof granted === 'object' && granted.length) {
  10713. for (let i = 0; i < granted.length; i += 1) {
  10714. if (typeof granted[i] !== 'number') {
  10715. stream.emit('error', new Error('Invalid qos vector'))
  10716. return false
  10717. }
  10718. length += 1
  10719. }
  10720. } else {
  10721. stream.emit('error', new Error('Invalid qos vector'))
  10722. return false
  10723. }
  10724. }
  10725. // properies mqtt 5
  10726. let propertiesData = null
  10727. if (version === 5) {
  10728. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  10729. if (!propertiesData) { return false }
  10730. length += propertiesData.length
  10731. }
  10732. // Header
  10733. stream.write(protocol.ACKS[type][qos][dup][0])
  10734. // Length
  10735. writeVarByteInt(stream, length)
  10736. // Message ID
  10737. writeNumber(stream, id)
  10738. // properies mqtt 5
  10739. if (propertiesData !== null) {
  10740. propertiesData.write()
  10741. }
  10742. // payload
  10743. if (version === 5) {
  10744. stream.write(Buffer.from(granted))
  10745. }
  10746. return true
  10747. }
  10748. function emptyPacket (packet, stream, opts) {
  10749. return stream.write(protocol.EMPTY[packet.cmd])
  10750. }
  10751. function disconnect (packet, stream, opts) {
  10752. const version = opts ? opts.protocolVersion : 4
  10753. const settings = packet || {}
  10754. const reasonCode = settings.reasonCode
  10755. const properties = settings.properties
  10756. let length = version === 5 ? 1 : 0
  10757. // properies mqtt 5
  10758. let propertiesData = null
  10759. if (version === 5) {
  10760. propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  10761. if (!propertiesData) { return false }
  10762. length += propertiesData.length
  10763. }
  10764. // Header
  10765. stream.write(Buffer.from([protocol.codes.disconnect << 4]))
  10766. // Length
  10767. writeVarByteInt(stream, length)
  10768. // reason code in header
  10769. if (version === 5) {
  10770. stream.write(Buffer.from([reasonCode]))
  10771. }
  10772. // properies mqtt 5
  10773. if (propertiesData !== null) {
  10774. propertiesData.write()
  10775. }
  10776. return true
  10777. }
  10778. function auth (packet, stream, opts) {
  10779. const version = opts ? opts.protocolVersion : 4
  10780. const settings = packet || {}
  10781. const reasonCode = settings.reasonCode
  10782. const properties = settings.properties
  10783. let length = version === 5 ? 1 : 0
  10784. if (version !== 5) stream.emit('error', new Error('Invalid mqtt version for auth packet'))
  10785. // properies mqtt 5
  10786. const propertiesData = getPropertiesByMaximumPacketSize(stream, properties, opts, length)
  10787. if (!propertiesData) { return false }
  10788. length += propertiesData.length
  10789. // Header
  10790. stream.write(Buffer.from([protocol.codes.auth << 4]))
  10791. // Length
  10792. writeVarByteInt(stream, length)
  10793. // reason code in header
  10794. stream.write(Buffer.from([reasonCode]))
  10795. // properies mqtt 5
  10796. if (propertiesData !== null) {
  10797. propertiesData.write()
  10798. }
  10799. return true
  10800. }
  10801. /**
  10802. * writeVarByteInt - write an MQTT style variable byte integer to the buffer
  10803. *
  10804. * @param <Buffer> buffer - destination
  10805. * @param <Number> pos - offset
  10806. * @param <Number> length - length (>0)
  10807. * @returns <Number> number of bytes written
  10808. *
  10809. * @api private
  10810. */
  10811. const varByteIntCache = {}
  10812. function writeVarByteInt (stream, num) {
  10813. if (num > protocol.VARBYTEINT_MAX) {
  10814. stream.emit('error', new Error(`Invalid variable byte integer: ${num}`))
  10815. return false
  10816. }
  10817. let buffer = varByteIntCache[num]
  10818. if (!buffer) {
  10819. buffer = genBufVariableByteInt(num)
  10820. if (num < 16384) varByteIntCache[num] = buffer
  10821. }
  10822. debug('writeVarByteInt: writing to stream: %o', buffer)
  10823. return stream.write(buffer)
  10824. }
  10825. /**
  10826. * writeString - write a utf8 string to the buffer
  10827. *
  10828. * @param <Buffer> buffer - destination
  10829. * @param <Number> pos - offset
  10830. * @param <String> string - string to write
  10831. * @return <Number> number of bytes written
  10832. *
  10833. * @api private
  10834. */
  10835. function writeString (stream, string) {
  10836. const strlen = Buffer.byteLength(string)
  10837. writeNumber(stream, strlen)
  10838. debug('writeString: %s', string)
  10839. return stream.write(string, 'utf8')
  10840. }
  10841. /**
  10842. * writeStringPair - write a utf8 string pairs to the buffer
  10843. *
  10844. * @param <Buffer> buffer - destination
  10845. * @param <String> name - string name to write
  10846. * @param <String> value - string value to write
  10847. * @return <Number> number of bytes written
  10848. *
  10849. * @api private
  10850. */
  10851. function writeStringPair (stream, name, value) {
  10852. writeString(stream, name)
  10853. writeString(stream, value)
  10854. }
  10855. /**
  10856. * writeNumber - write a two byte number to the buffer
  10857. *
  10858. * @param <Buffer> buffer - destination
  10859. * @param <Number> pos - offset
  10860. * @param <String> number - number to write
  10861. * @return <Number> number of bytes written
  10862. *
  10863. * @api private
  10864. */
  10865. function writeNumberCached (stream, number) {
  10866. debug('writeNumberCached: number: %d', number)
  10867. debug('writeNumberCached: %o', numCache[number])
  10868. return stream.write(numCache[number])
  10869. }
  10870. function writeNumberGenerated (stream, number) {
  10871. const generatedNumber = generateNumber(number)
  10872. debug('writeNumberGenerated: %o', generatedNumber)
  10873. return stream.write(generatedNumber)
  10874. }
  10875. function write4ByteNumber (stream, number) {
  10876. const generated4ByteBuffer = generate4ByteBuffer(number)
  10877. debug('write4ByteNumber: %o', generated4ByteBuffer)
  10878. return stream.write(generated4ByteBuffer)
  10879. }
  10880. /**
  10881. * writeStringOrBuffer - write a String or Buffer with the its length prefix
  10882. *
  10883. * @param <Buffer> buffer - destination
  10884. * @param <Number> pos - offset
  10885. * @param <String> toWrite - String or Buffer
  10886. * @return <Number> number of bytes written
  10887. */
  10888. function writeStringOrBuffer (stream, toWrite) {
  10889. if (typeof toWrite === 'string') {
  10890. writeString(stream, toWrite)
  10891. } else if (toWrite) {
  10892. writeNumber(stream, toWrite.length)
  10893. stream.write(toWrite)
  10894. } else writeNumber(stream, 0)
  10895. }
  10896. function getProperties (stream, properties) {
  10897. /* connect properties */
  10898. if (typeof properties !== 'object' || properties.length != null) {
  10899. return {
  10900. length: 1,
  10901. write () {
  10902. writeProperties(stream, {}, 0)
  10903. }
  10904. }
  10905. }
  10906. let propertiesLength = 0
  10907. function getLengthProperty (name, value) {
  10908. const type = protocol.propertiesTypes[name]
  10909. let length = 0
  10910. switch (type) {
  10911. case 'byte': {
  10912. if (typeof value !== 'boolean') {
  10913. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10914. return false
  10915. }
  10916. length += 1 + 1
  10917. break
  10918. }
  10919. case 'int8': {
  10920. if (typeof value !== 'number' || value < 0 || value > 0xff) {
  10921. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10922. return false
  10923. }
  10924. length += 1 + 1
  10925. break
  10926. }
  10927. case 'binary': {
  10928. if (value && value === null) {
  10929. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10930. return false
  10931. }
  10932. length += 1 + Buffer.byteLength(value) + 2
  10933. break
  10934. }
  10935. case 'int16': {
  10936. if (typeof value !== 'number' || value < 0 || value > 0xffff) {
  10937. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10938. return false
  10939. }
  10940. length += 1 + 2
  10941. break
  10942. }
  10943. case 'int32': {
  10944. if (typeof value !== 'number' || value < 0 || value > 0xffffffff) {
  10945. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10946. return false
  10947. }
  10948. length += 1 + 4
  10949. break
  10950. }
  10951. case 'var': {
  10952. // var byte integer is max 24 bits packed in 32 bits
  10953. if (typeof value !== 'number' || value < 0 || value > 0x0fffffff) {
  10954. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10955. return false
  10956. }
  10957. length += 1 + Buffer.byteLength(genBufVariableByteInt(value))
  10958. break
  10959. }
  10960. case 'string': {
  10961. if (typeof value !== 'string') {
  10962. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10963. return false
  10964. }
  10965. length += 1 + 2 + Buffer.byteLength(value.toString())
  10966. break
  10967. }
  10968. case 'pair': {
  10969. if (typeof value !== 'object') {
  10970. stream.emit('error', new Error(`Invalid ${name}: ${value}`))
  10971. return false
  10972. }
  10973. length += Object.getOwnPropertyNames(value).reduce((result, name) => {
  10974. const currentValue = value[name]
  10975. if (Array.isArray(currentValue)) {
  10976. result += currentValue.reduce((currentLength, value) => {
  10977. currentLength += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value.toString())
  10978. return currentLength
  10979. }, 0)
  10980. } else {
  10981. result += 1 + 2 + Buffer.byteLength(name.toString()) + 2 + Buffer.byteLength(value[name].toString())
  10982. }
  10983. return result
  10984. }, 0)
  10985. break
  10986. }
  10987. default: {
  10988. stream.emit('error', new Error(`Invalid property ${name}: ${value}`))
  10989. return false
  10990. }
  10991. }
  10992. return length
  10993. }
  10994. if (properties) {
  10995. for (const propName in properties) {
  10996. let propLength = 0
  10997. let propValueLength = 0
  10998. const propValue = properties[propName]
  10999. if (Array.isArray(propValue)) {
  11000. for (let valueIndex = 0; valueIndex < propValue.length; valueIndex++) {
  11001. propValueLength = getLengthProperty(propName, propValue[valueIndex])
  11002. if (!propValueLength) { return false }
  11003. propLength += propValueLength
  11004. }
  11005. } else {
  11006. propValueLength = getLengthProperty(propName, propValue)
  11007. if (!propValueLength) { return false }
  11008. propLength = propValueLength
  11009. }
  11010. if (!propLength) return false
  11011. propertiesLength += propLength
  11012. }
  11013. }
  11014. const propertiesLengthLength = Buffer.byteLength(genBufVariableByteInt(propertiesLength))
  11015. return {
  11016. length: propertiesLengthLength + propertiesLength,
  11017. write () {
  11018. writeProperties(stream, properties, propertiesLength)
  11019. }
  11020. }
  11021. }
  11022. function getPropertiesByMaximumPacketSize (stream, properties, opts, length) {
  11023. const mayEmptyProps = ['reasonString', 'userProperties']
  11024. const maximumPacketSize = opts && opts.properties && opts.properties.maximumPacketSize ? opts.properties.maximumPacketSize : 0
  11025. let propertiesData = getProperties(stream, properties)
  11026. if (maximumPacketSize) {
  11027. while (length + propertiesData.length > maximumPacketSize) {
  11028. const currentMayEmptyProp = mayEmptyProps.shift()
  11029. if (currentMayEmptyProp && properties[currentMayEmptyProp]) {
  11030. delete properties[currentMayEmptyProp]
  11031. propertiesData = getProperties(stream, properties)
  11032. } else {
  11033. return false
  11034. }
  11035. }
  11036. }
  11037. return propertiesData
  11038. }
  11039. function writeProperty (stream, propName, value) {
  11040. const type = protocol.propertiesTypes[propName]
  11041. switch (type) {
  11042. case 'byte': {
  11043. stream.write(Buffer.from([protocol.properties[propName]]))
  11044. stream.write(Buffer.from([+value]))
  11045. break
  11046. }
  11047. case 'int8': {
  11048. stream.write(Buffer.from([protocol.properties[propName]]))
  11049. stream.write(Buffer.from([value]))
  11050. break
  11051. }
  11052. case 'binary': {
  11053. stream.write(Buffer.from([protocol.properties[propName]]))
  11054. writeStringOrBuffer(stream, value)
  11055. break
  11056. }
  11057. case 'int16': {
  11058. stream.write(Buffer.from([protocol.properties[propName]]))
  11059. writeNumber(stream, value)
  11060. break
  11061. }
  11062. case 'int32': {
  11063. stream.write(Buffer.from([protocol.properties[propName]]))
  11064. write4ByteNumber(stream, value)
  11065. break
  11066. }
  11067. case 'var': {
  11068. stream.write(Buffer.from([protocol.properties[propName]]))
  11069. writeVarByteInt(stream, value)
  11070. break
  11071. }
  11072. case 'string': {
  11073. stream.write(Buffer.from([protocol.properties[propName]]))
  11074. writeString(stream, value)
  11075. break
  11076. }
  11077. case 'pair': {
  11078. Object.getOwnPropertyNames(value).forEach(name => {
  11079. const currentValue = value[name]
  11080. if (Array.isArray(currentValue)) {
  11081. currentValue.forEach(value => {
  11082. stream.write(Buffer.from([protocol.properties[propName]]))
  11083. writeStringPair(stream, name.toString(), value.toString())
  11084. })
  11085. } else {
  11086. stream.write(Buffer.from([protocol.properties[propName]]))
  11087. writeStringPair(stream, name.toString(), currentValue.toString())
  11088. }
  11089. })
  11090. break
  11091. }
  11092. default: {
  11093. stream.emit('error', new Error(`Invalid property ${propName} value: ${value}`))
  11094. return false
  11095. }
  11096. }
  11097. }
  11098. function writeProperties (stream, properties, propertiesLength) {
  11099. /* write properties to stream */
  11100. writeVarByteInt(stream, propertiesLength)
  11101. for (const propName in properties) {
  11102. if (Object.prototype.hasOwnProperty.call(properties, propName) && properties[propName] !== null) {
  11103. const value = properties[propName]
  11104. if (Array.isArray(value)) {
  11105. for (let valueIndex = 0; valueIndex < value.length; valueIndex++) {
  11106. writeProperty(stream, propName, value[valueIndex])
  11107. }
  11108. } else {
  11109. writeProperty(stream, propName, value)
  11110. }
  11111. }
  11112. }
  11113. }
  11114. function byteLength (bufOrString) {
  11115. if (!bufOrString) return 0
  11116. else if (bufOrString instanceof Buffer) return bufOrString.length
  11117. else return Buffer.byteLength(bufOrString)
  11118. }
  11119. function isStringOrBuffer (field) {
  11120. return typeof field === 'string' || field instanceof Buffer
  11121. }
  11122. module.exports = generate
  11123. }).call(this)}).call(this,require("buffer").Buffer)
  11124. },{"./constants":38,"./numbers":41,"buffer":17,"debug":18,"process-nextick-args":49}],45:[function(require,module,exports){
  11125. /**
  11126. * Helpers.
  11127. */
  11128. var s = 1000;
  11129. var m = s * 60;
  11130. var h = m * 60;
  11131. var d = h * 24;
  11132. var w = d * 7;
  11133. var y = d * 365.25;
  11134. /**
  11135. * Parse or format the given `val`.
  11136. *
  11137. * Options:
  11138. *
  11139. * - `long` verbose formatting [false]
  11140. *
  11141. * @param {String|Number} val
  11142. * @param {Object} [options]
  11143. * @throws {Error} throw an error if val is not a non-empty string or a number
  11144. * @return {String|Number}
  11145. * @api public
  11146. */
  11147. module.exports = function(val, options) {
  11148. options = options || {};
  11149. var type = typeof val;
  11150. if (type === 'string' && val.length > 0) {
  11151. return parse(val);
  11152. } else if (type === 'number' && isFinite(val)) {
  11153. return options.long ? fmtLong(val) : fmtShort(val);
  11154. }
  11155. throw new Error(
  11156. 'val is not a non-empty string or a valid number. val=' +
  11157. JSON.stringify(val)
  11158. );
  11159. };
  11160. /**
  11161. * Parse the given `str` and return milliseconds.
  11162. *
  11163. * @param {String} str
  11164. * @return {Number}
  11165. * @api private
  11166. */
  11167. function parse(str) {
  11168. str = String(str);
  11169. if (str.length > 100) {
  11170. return;
  11171. }
  11172. var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  11173. str
  11174. );
  11175. if (!match) {
  11176. return;
  11177. }
  11178. var n = parseFloat(match[1]);
  11179. var type = (match[2] || 'ms').toLowerCase();
  11180. switch (type) {
  11181. case 'years':
  11182. case 'year':
  11183. case 'yrs':
  11184. case 'yr':
  11185. case 'y':
  11186. return n * y;
  11187. case 'weeks':
  11188. case 'week':
  11189. case 'w':
  11190. return n * w;
  11191. case 'days':
  11192. case 'day':
  11193. case 'd':
  11194. return n * d;
  11195. case 'hours':
  11196. case 'hour':
  11197. case 'hrs':
  11198. case 'hr':
  11199. case 'h':
  11200. return n * h;
  11201. case 'minutes':
  11202. case 'minute':
  11203. case 'mins':
  11204. case 'min':
  11205. case 'm':
  11206. return n * m;
  11207. case 'seconds':
  11208. case 'second':
  11209. case 'secs':
  11210. case 'sec':
  11211. case 's':
  11212. return n * s;
  11213. case 'milliseconds':
  11214. case 'millisecond':
  11215. case 'msecs':
  11216. case 'msec':
  11217. case 'ms':
  11218. return n;
  11219. default:
  11220. return undefined;
  11221. }
  11222. }
  11223. /**
  11224. * Short format for `ms`.
  11225. *
  11226. * @param {Number} ms
  11227. * @return {String}
  11228. * @api private
  11229. */
  11230. function fmtShort(ms) {
  11231. var msAbs = Math.abs(ms);
  11232. if (msAbs >= d) {
  11233. return Math.round(ms / d) + 'd';
  11234. }
  11235. if (msAbs >= h) {
  11236. return Math.round(ms / h) + 'h';
  11237. }
  11238. if (msAbs >= m) {
  11239. return Math.round(ms / m) + 'm';
  11240. }
  11241. if (msAbs >= s) {
  11242. return Math.round(ms / s) + 's';
  11243. }
  11244. return ms + 'ms';
  11245. }
  11246. /**
  11247. * Long format for `ms`.
  11248. *
  11249. * @param {Number} ms
  11250. * @return {String}
  11251. * @api private
  11252. */
  11253. function fmtLong(ms) {
  11254. var msAbs = Math.abs(ms);
  11255. if (msAbs >= d) {
  11256. return plural(ms, msAbs, d, 'day');
  11257. }
  11258. if (msAbs >= h) {
  11259. return plural(ms, msAbs, h, 'hour');
  11260. }
  11261. if (msAbs >= m) {
  11262. return plural(ms, msAbs, m, 'minute');
  11263. }
  11264. if (msAbs >= s) {
  11265. return plural(ms, msAbs, s, 'second');
  11266. }
  11267. return ms + ' ms';
  11268. }
  11269. /**
  11270. * Pluralization helper.
  11271. */
  11272. function plural(ms, msAbs, n, name) {
  11273. var isPlural = msAbs >= n * 1.5;
  11274. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  11275. }
  11276. },{}],46:[function(require,module,exports){
  11277. // Copyright Takatoshi Kondo 2021
  11278. //
  11279. // Distributed under the MIT License
  11280. const NumberAllocator = require('./lib/number-allocator.js')
  11281. module.exports.NumberAllocator = NumberAllocator
  11282. },{"./lib/number-allocator.js":47}],47:[function(require,module,exports){
  11283. // Copyright Takatoshi Kondo 2021
  11284. //
  11285. // Distributed under the MIT License
  11286. 'use strict'
  11287. const SortedSet = require('js-sdsl').Set
  11288. const debugTrace = require('debug')('number-allocator:trace')
  11289. const debugError = require('debug')('number-allocator:error')
  11290. /**
  11291. * Interval constructor
  11292. * @constructor
  11293. * @param {Number} low - The lowest value of the interval
  11294. * @param {Number} high - The highest value of the interval
  11295. */
  11296. function Interval (low, high) {
  11297. this.low = low
  11298. this.high = high
  11299. }
  11300. Interval.prototype.equals = function (other) {
  11301. return this.low === other.low && this.high === other.high
  11302. }
  11303. Interval.prototype.compare = function (other) {
  11304. if (this.low < other.low && this.high < other.low) return -1
  11305. if (other.low < this.low && other.high < this.low) return 1
  11306. return 0
  11307. }
  11308. /**
  11309. * NumberAllocator constructor.
  11310. * The all numbers are set to vacant status.
  11311. * Time Complexity O(1)
  11312. * @constructor
  11313. * @param {Number} min - The maximum number of allocatable. The number must be integer.
  11314. * @param {Number} maxh - The minimum number of allocatable. The number must be integer.
  11315. */
  11316. function NumberAllocator (min, max) {
  11317. if (!(this instanceof NumberAllocator)) {
  11318. return new NumberAllocator(min, max)
  11319. }
  11320. this.min = min
  11321. this.max = max
  11322. this.ss = new SortedSet(
  11323. [],
  11324. (lhs, rhs) => {
  11325. return lhs.compare(rhs)
  11326. }
  11327. )
  11328. debugTrace('Create')
  11329. this.clear()
  11330. }
  11331. /**
  11332. * Get the first vacant number. The status of the number is not updated.
  11333. * Time Complexity O(1)
  11334. * @return {Number} - The first vacant number. If all numbers are occupied, return null.
  11335. * When alloc() is called then the same value will be allocated.
  11336. */
  11337. NumberAllocator.prototype.firstVacant = function () {
  11338. if (this.ss.size() === 0) return null
  11339. return this.ss.front().low
  11340. }
  11341. /**
  11342. * Allocate the first vacant number. The number become occupied status.
  11343. * Time Complexity O(1)
  11344. * @return {Number} - The first vacant number. If all numbers are occupied, return null.
  11345. */
  11346. NumberAllocator.prototype.alloc = function () {
  11347. if (this.ss.size() === 0) {
  11348. debugTrace('alloc():empty')
  11349. return null
  11350. }
  11351. const it = this.ss.front()
  11352. const num = it.low
  11353. if (num + 1 <= it.high) {
  11354. // Overwrite the interval in the ss but it is safe,
  11355. // because no order violation is happened.
  11356. // x|----|
  11357. ++it.low
  11358. } else {
  11359. this.ss.eraseElementByPos(0)
  11360. }
  11361. debugTrace('alloc():' + num)
  11362. return num
  11363. }
  11364. /**
  11365. * Use the number. The number become occupied status.
  11366. * If the number has already been occupied, then return false.
  11367. * Time Complexity O(logN) : N is the number of intervals (not numbers)
  11368. * @param {Number} num - The number to request use.
  11369. * @return {Boolean} - If `num` was not occupied, then return true, otherwise return false.
  11370. */
  11371. NumberAllocator.prototype.use = function (num) {
  11372. const key = new Interval(num, num)
  11373. const it = this.ss.lowerBound(key)
  11374. if (it) {
  11375. if (it.equals(key)) {
  11376. // |x|
  11377. this.ss.eraseElementByValue(it)
  11378. debugTrace('use():' + num)
  11379. return true
  11380. }
  11381. // x |-----|
  11382. if (it.low > num) return false
  11383. // |x----|
  11384. if (it.low === num) {
  11385. // Overwrite the interval in the ss but it is safe,
  11386. // because no order violation is happened.
  11387. // x|----|
  11388. ++it.low
  11389. debugTrace('use():' + num)
  11390. return true
  11391. }
  11392. // |----x|
  11393. if (it.high === num) {
  11394. // Overwrite the interval in the ss but it is safe,
  11395. // because no order violation is happened.
  11396. // |----|x
  11397. --it.high
  11398. debugTrace('use():' + num)
  11399. return true
  11400. }
  11401. const low = it.low
  11402. // |--x--|
  11403. // Overwrite the interval in the ss but it is safe,
  11404. // because no order violation is happened.
  11405. // x|--|
  11406. it.low = num + 1
  11407. // |--|x|--|
  11408. this.ss.insert(new Interval(low, num - 1))
  11409. debugTrace('use():' + num)
  11410. return true
  11411. }
  11412. debugTrace('use():failed')
  11413. return false
  11414. }
  11415. /**
  11416. * Deallocate the number. The number become vacant status.
  11417. * Time Complexity O(logN) : N is the number of intervals (not numbers)
  11418. * @param {Number} num - The number to deallocate. The number must be occupied status.
  11419. * In other words, the number must be allocated by alloc() or occupied be use().
  11420. */
  11421. NumberAllocator.prototype.free = function (num) {
  11422. if (num < this.min || num > this.max) {
  11423. debugError('free():' + num + ' is out of range')
  11424. return
  11425. }
  11426. const key = new Interval(num, num)
  11427. const it = this.ss.lowerBound(key)
  11428. if (it) {
  11429. if (it.low <= num && num <= it.high) {
  11430. debugError('free():' + num + ' has already been vacant')
  11431. return
  11432. }
  11433. if (it === this.ss.front()) {
  11434. // v....
  11435. if (num + 1 === it.low) {
  11436. // Concat to right
  11437. // Overwrite the interval in the ss but it is safe,
  11438. // because no order violation is happened.
  11439. --it.low
  11440. } else {
  11441. // Insert new interval
  11442. this.ss.insert(key)
  11443. }
  11444. } else {
  11445. // ..v..
  11446. const itl = this.ss.reverseLowerBound(key)
  11447. if (itl.high + 1 === num) {
  11448. if (num + 1 === it.low) {
  11449. // Concat to left and right
  11450. this.ss.eraseElementByValue(itl)
  11451. // Overwrite the interval in the ss but it is safe,
  11452. // because no order violation is happened.
  11453. it.low = itl.low
  11454. } else {
  11455. // Concat to left
  11456. // Overwrite the interval in the ss but it is safe,
  11457. // because no order violation is happened.
  11458. itl.high = num
  11459. }
  11460. } else {
  11461. if (num + 1 === it.low) {
  11462. // Concat to right
  11463. // Overwrite the interval in the ss but it is safe,
  11464. // because no order violation is happened.
  11465. it.low = num
  11466. } else {
  11467. // Insert new interval
  11468. this.ss.insert(key)
  11469. }
  11470. }
  11471. }
  11472. } else {
  11473. // ....v
  11474. if (it === this.ss.front()) {
  11475. // Insert new interval
  11476. this.ss.insert(key)
  11477. return
  11478. }
  11479. const itl = this.ss.reverseLowerBound(key)
  11480. if (itl.high + 1 === num) {
  11481. // Concat to left
  11482. // Overwrite the interval in the ss but it is safe,
  11483. // because no order violation is happened.
  11484. itl.high = num
  11485. } else {
  11486. // Insert new interval
  11487. this.ss.insert(key)
  11488. }
  11489. }
  11490. debugTrace('free():' + num)
  11491. }
  11492. /**
  11493. * Clear all occupied numbers.
  11494. * The all numbers are set to vacant status.
  11495. * Time Complexity O(1)
  11496. */
  11497. NumberAllocator.prototype.clear = function () {
  11498. debugTrace('clear()')
  11499. this.ss.clear()
  11500. this.ss.insert(new Interval(this.min, this.max))
  11501. }
  11502. /**
  11503. * Get the number of intervals. Interval is internal structure of this library.
  11504. * This function is for debugging.
  11505. * Time Complexity O(1)
  11506. * @return {Number} - The number of intervals.
  11507. */
  11508. NumberAllocator.prototype.intervalCount = function () {
  11509. return this.ss.size()
  11510. }
  11511. /**
  11512. * Dump the internal structor of the library.
  11513. * This function is for debugging.
  11514. * Time Complexity O(N) : N is the number of intervals (not numbers)
  11515. */
  11516. NumberAllocator.prototype.dump = function () {
  11517. console.log('length:' + this.ss.size())
  11518. for (const element of this.ss) {
  11519. console.log(element)
  11520. }
  11521. }
  11522. module.exports = NumberAllocator
  11523. },{"debug":18,"js-sdsl":36}],48:[function(require,module,exports){
  11524. var wrappy = require('wrappy')
  11525. module.exports = wrappy(once)
  11526. module.exports.strict = wrappy(onceStrict)
  11527. once.proto = once(function () {
  11528. Object.defineProperty(Function.prototype, 'once', {
  11529. value: function () {
  11530. return once(this)
  11531. },
  11532. configurable: true
  11533. })
  11534. Object.defineProperty(Function.prototype, 'onceStrict', {
  11535. value: function () {
  11536. return onceStrict(this)
  11537. },
  11538. configurable: true
  11539. })
  11540. })
  11541. function once (fn) {
  11542. var f = function () {
  11543. if (f.called) return f.value
  11544. f.called = true
  11545. return f.value = fn.apply(this, arguments)
  11546. }
  11547. f.called = false
  11548. return f
  11549. }
  11550. function onceStrict (fn) {
  11551. var f = function () {
  11552. if (f.called)
  11553. throw new Error(f.onceError)
  11554. f.called = true
  11555. return f.value = fn.apply(this, arguments)
  11556. }
  11557. var name = fn.name || 'Function wrapped with `once`'
  11558. f.onceError = name + " shouldn't be called more than once"
  11559. f.called = false
  11560. return f
  11561. }
  11562. },{"wrappy":79}],49:[function(require,module,exports){
  11563. (function (process){(function (){
  11564. 'use strict';
  11565. if (typeof process === 'undefined' ||
  11566. !process.version ||
  11567. process.version.indexOf('v0.') === 0 ||
  11568. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  11569. module.exports = { nextTick: nextTick };
  11570. } else {
  11571. module.exports = process
  11572. }
  11573. function nextTick(fn, arg1, arg2, arg3) {
  11574. if (typeof fn !== 'function') {
  11575. throw new TypeError('"callback" argument must be a function');
  11576. }
  11577. var len = arguments.length;
  11578. var args, i;
  11579. switch (len) {
  11580. case 0:
  11581. case 1:
  11582. return process.nextTick(fn);
  11583. case 2:
  11584. return process.nextTick(function afterTickOne() {
  11585. fn.call(null, arg1);
  11586. });
  11587. case 3:
  11588. return process.nextTick(function afterTickTwo() {
  11589. fn.call(null, arg1, arg2);
  11590. });
  11591. case 4:
  11592. return process.nextTick(function afterTickThree() {
  11593. fn.call(null, arg1, arg2, arg3);
  11594. });
  11595. default:
  11596. args = new Array(len - 1);
  11597. i = 0;
  11598. while (i < args.length) {
  11599. args[i++] = arguments[i];
  11600. }
  11601. return process.nextTick(function afterTick() {
  11602. fn.apply(null, args);
  11603. });
  11604. }
  11605. }
  11606. }).call(this)}).call(this,require('_process'))
  11607. },{"_process":50}],50:[function(require,module,exports){
  11608. // shim for using process in browser
  11609. var process = module.exports = {};
  11610. // cached from whatever global is present so that test runners that stub it
  11611. // don't break things. But we need to wrap it in a try catch in case it is
  11612. // wrapped in strict mode code which doesn't define any globals. It's inside a
  11613. // function because try/catches deoptimize in certain engines.
  11614. var cachedSetTimeout;
  11615. var cachedClearTimeout;
  11616. function defaultSetTimout() {
  11617. throw new Error('setTimeout has not been defined');
  11618. }
  11619. function defaultClearTimeout () {
  11620. throw new Error('clearTimeout has not been defined');
  11621. }
  11622. (function () {
  11623. try {
  11624. if (typeof setTimeout === 'function') {
  11625. cachedSetTimeout = setTimeout;
  11626. } else {
  11627. cachedSetTimeout = defaultSetTimout;
  11628. }
  11629. } catch (e) {
  11630. cachedSetTimeout = defaultSetTimout;
  11631. }
  11632. try {
  11633. if (typeof clearTimeout === 'function') {
  11634. cachedClearTimeout = clearTimeout;
  11635. } else {
  11636. cachedClearTimeout = defaultClearTimeout;
  11637. }
  11638. } catch (e) {
  11639. cachedClearTimeout = defaultClearTimeout;
  11640. }
  11641. } ())
  11642. function runTimeout(fun) {
  11643. if (cachedSetTimeout === setTimeout) {
  11644. //normal enviroments in sane situations
  11645. return setTimeout(fun, 0);
  11646. }
  11647. // if setTimeout wasn't available but was latter defined
  11648. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  11649. cachedSetTimeout = setTimeout;
  11650. return setTimeout(fun, 0);
  11651. }
  11652. try {
  11653. // when when somebody has screwed with setTimeout but no I.E. maddness
  11654. return cachedSetTimeout(fun, 0);
  11655. } catch(e){
  11656. try {
  11657. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  11658. return cachedSetTimeout.call(null, fun, 0);
  11659. } catch(e){
  11660. // 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
  11661. return cachedSetTimeout.call(this, fun, 0);
  11662. }
  11663. }
  11664. }
  11665. function runClearTimeout(marker) {
  11666. if (cachedClearTimeout === clearTimeout) {
  11667. //normal enviroments in sane situations
  11668. return clearTimeout(marker);
  11669. }
  11670. // if clearTimeout wasn't available but was latter defined
  11671. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  11672. cachedClearTimeout = clearTimeout;
  11673. return clearTimeout(marker);
  11674. }
  11675. try {
  11676. // when when somebody has screwed with setTimeout but no I.E. maddness
  11677. return cachedClearTimeout(marker);
  11678. } catch (e){
  11679. try {
  11680. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  11681. return cachedClearTimeout.call(null, marker);
  11682. } catch (e){
  11683. // 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.
  11684. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  11685. return cachedClearTimeout.call(this, marker);
  11686. }
  11687. }
  11688. }
  11689. var queue = [];
  11690. var draining = false;
  11691. var currentQueue;
  11692. var queueIndex = -1;
  11693. function cleanUpNextTick() {
  11694. if (!draining || !currentQueue) {
  11695. return;
  11696. }
  11697. draining = false;
  11698. if (currentQueue.length) {
  11699. queue = currentQueue.concat(queue);
  11700. } else {
  11701. queueIndex = -1;
  11702. }
  11703. if (queue.length) {
  11704. drainQueue();
  11705. }
  11706. }
  11707. function drainQueue() {
  11708. if (draining) {
  11709. return;
  11710. }
  11711. var timeout = runTimeout(cleanUpNextTick);
  11712. draining = true;
  11713. var len = queue.length;
  11714. while(len) {
  11715. currentQueue = queue;
  11716. queue = [];
  11717. while (++queueIndex < len) {
  11718. if (currentQueue) {
  11719. currentQueue[queueIndex].run();
  11720. }
  11721. }
  11722. queueIndex = -1;
  11723. len = queue.length;
  11724. }
  11725. currentQueue = null;
  11726. draining = false;
  11727. runClearTimeout(timeout);
  11728. }
  11729. process.nextTick = function (fun) {
  11730. var args = new Array(arguments.length - 1);
  11731. if (arguments.length > 1) {
  11732. for (var i = 1; i < arguments.length; i++) {
  11733. args[i - 1] = arguments[i];
  11734. }
  11735. }
  11736. queue.push(new Item(fun, args));
  11737. if (queue.length === 1 && !draining) {
  11738. runTimeout(drainQueue);
  11739. }
  11740. };
  11741. // v8 likes predictible objects
  11742. function Item(fun, array) {
  11743. this.fun = fun;
  11744. this.array = array;
  11745. }
  11746. Item.prototype.run = function () {
  11747. this.fun.apply(null, this.array);
  11748. };
  11749. process.title = 'browser';
  11750. process.browser = true;
  11751. process.env = {};
  11752. process.argv = [];
  11753. process.version = ''; // empty string to avoid regexp issues
  11754. process.versions = {};
  11755. function noop() {}
  11756. process.on = noop;
  11757. process.addListener = noop;
  11758. process.once = noop;
  11759. process.off = noop;
  11760. process.removeListener = noop;
  11761. process.removeAllListeners = noop;
  11762. process.emit = noop;
  11763. process.prependListener = noop;
  11764. process.prependOnceListener = noop;
  11765. process.listeners = function (name) { return [] }
  11766. process.binding = function (name) {
  11767. throw new Error('process.binding is not supported');
  11768. };
  11769. process.cwd = function () { return '/' };
  11770. process.chdir = function (dir) {
  11771. throw new Error('process.chdir is not supported');
  11772. };
  11773. process.umask = function() { return 0; };
  11774. },{}],51:[function(require,module,exports){
  11775. (function (global){(function (){
  11776. /*! https://mths.be/punycode v1.4.1 by @mathias */
  11777. ;(function(root) {
  11778. /** Detect free variables */
  11779. var freeExports = typeof exports == 'object' && exports &&
  11780. !exports.nodeType && exports;
  11781. var freeModule = typeof module == 'object' && module &&
  11782. !module.nodeType && module;
  11783. var freeGlobal = typeof global == 'object' && global;
  11784. if (
  11785. freeGlobal.global === freeGlobal ||
  11786. freeGlobal.window === freeGlobal ||
  11787. freeGlobal.self === freeGlobal
  11788. ) {
  11789. root = freeGlobal;
  11790. }
  11791. /**
  11792. * The `punycode` object.
  11793. * @name punycode
  11794. * @type Object
  11795. */
  11796. var punycode,
  11797. /** Highest positive signed 32-bit float value */
  11798. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  11799. /** Bootstring parameters */
  11800. base = 36,
  11801. tMin = 1,
  11802. tMax = 26,
  11803. skew = 38,
  11804. damp = 700,
  11805. initialBias = 72,
  11806. initialN = 128, // 0x80
  11807. delimiter = '-', // '\x2D'
  11808. /** Regular expressions */
  11809. regexPunycode = /^xn--/,
  11810. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  11811. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  11812. /** Error messages */
  11813. errors = {
  11814. 'overflow': 'Overflow: input needs wider integers to process',
  11815. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  11816. 'invalid-input': 'Invalid input'
  11817. },
  11818. /** Convenience shortcuts */
  11819. baseMinusTMin = base - tMin,
  11820. floor = Math.floor,
  11821. stringFromCharCode = String.fromCharCode,
  11822. /** Temporary variable */
  11823. key;
  11824. /*--------------------------------------------------------------------------*/
  11825. /**
  11826. * A generic error utility function.
  11827. * @private
  11828. * @param {String} type The error type.
  11829. * @returns {Error} Throws a `RangeError` with the applicable error message.
  11830. */
  11831. function error(type) {
  11832. throw new RangeError(errors[type]);
  11833. }
  11834. /**
  11835. * A generic `Array#map` utility function.
  11836. * @private
  11837. * @param {Array} array The array to iterate over.
  11838. * @param {Function} callback The function that gets called for every array
  11839. * item.
  11840. * @returns {Array} A new array of values returned by the callback function.
  11841. */
  11842. function map(array, fn) {
  11843. var length = array.length;
  11844. var result = [];
  11845. while (length--) {
  11846. result[length] = fn(array[length]);
  11847. }
  11848. return result;
  11849. }
  11850. /**
  11851. * A simple `Array#map`-like wrapper to work with domain name strings or email
  11852. * addresses.
  11853. * @private
  11854. * @param {String} domain The domain name or email address.
  11855. * @param {Function} callback The function that gets called for every
  11856. * character.
  11857. * @returns {Array} A new string of characters returned by the callback
  11858. * function.
  11859. */
  11860. function mapDomain(string, fn) {
  11861. var parts = string.split('@');
  11862. var result = '';
  11863. if (parts.length > 1) {
  11864. // In email addresses, only the domain name should be punycoded. Leave
  11865. // the local part (i.e. everything up to `@`) intact.
  11866. result = parts[0] + '@';
  11867. string = parts[1];
  11868. }
  11869. // Avoid `split(regex)` for IE8 compatibility. See #17.
  11870. string = string.replace(regexSeparators, '\x2E');
  11871. var labels = string.split('.');
  11872. var encoded = map(labels, fn).join('.');
  11873. return result + encoded;
  11874. }
  11875. /**
  11876. * Creates an array containing the numeric code points of each Unicode
  11877. * character in the string. While JavaScript uses UCS-2 internally,
  11878. * this function will convert a pair of surrogate halves (each of which
  11879. * UCS-2 exposes as separate characters) into a single code point,
  11880. * matching UTF-16.
  11881. * @see `punycode.ucs2.encode`
  11882. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  11883. * @memberOf punycode.ucs2
  11884. * @name decode
  11885. * @param {String} string The Unicode input string (UCS-2).
  11886. * @returns {Array} The new array of code points.
  11887. */
  11888. function ucs2decode(string) {
  11889. var output = [],
  11890. counter = 0,
  11891. length = string.length,
  11892. value,
  11893. extra;
  11894. while (counter < length) {
  11895. value = string.charCodeAt(counter++);
  11896. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  11897. // high surrogate, and there is a next character
  11898. extra = string.charCodeAt(counter++);
  11899. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  11900. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  11901. } else {
  11902. // unmatched surrogate; only append this code unit, in case the next
  11903. // code unit is the high surrogate of a surrogate pair
  11904. output.push(value);
  11905. counter--;
  11906. }
  11907. } else {
  11908. output.push(value);
  11909. }
  11910. }
  11911. return output;
  11912. }
  11913. /**
  11914. * Creates a string based on an array of numeric code points.
  11915. * @see `punycode.ucs2.decode`
  11916. * @memberOf punycode.ucs2
  11917. * @name encode
  11918. * @param {Array} codePoints The array of numeric code points.
  11919. * @returns {String} The new Unicode string (UCS-2).
  11920. */
  11921. function ucs2encode(array) {
  11922. return map(array, function(value) {
  11923. var output = '';
  11924. if (value > 0xFFFF) {
  11925. value -= 0x10000;
  11926. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  11927. value = 0xDC00 | value & 0x3FF;
  11928. }
  11929. output += stringFromCharCode(value);
  11930. return output;
  11931. }).join('');
  11932. }
  11933. /**
  11934. * Converts a basic code point into a digit/integer.
  11935. * @see `digitToBasic()`
  11936. * @private
  11937. * @param {Number} codePoint The basic numeric code point value.
  11938. * @returns {Number} The numeric value of a basic code point (for use in
  11939. * representing integers) in the range `0` to `base - 1`, or `base` if
  11940. * the code point does not represent a value.
  11941. */
  11942. function basicToDigit(codePoint) {
  11943. if (codePoint - 48 < 10) {
  11944. return codePoint - 22;
  11945. }
  11946. if (codePoint - 65 < 26) {
  11947. return codePoint - 65;
  11948. }
  11949. if (codePoint - 97 < 26) {
  11950. return codePoint - 97;
  11951. }
  11952. return base;
  11953. }
  11954. /**
  11955. * Converts a digit/integer into a basic code point.
  11956. * @see `basicToDigit()`
  11957. * @private
  11958. * @param {Number} digit The numeric value of a basic code point.
  11959. * @returns {Number} The basic code point whose value (when used for
  11960. * representing integers) is `digit`, which needs to be in the range
  11961. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  11962. * used; else, the lowercase form is used. The behavior is undefined
  11963. * if `flag` is non-zero and `digit` has no uppercase form.
  11964. */
  11965. function digitToBasic(digit, flag) {
  11966. // 0..25 map to ASCII a..z or A..Z
  11967. // 26..35 map to ASCII 0..9
  11968. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  11969. }
  11970. /**
  11971. * Bias adaptation function as per section 3.4 of RFC 3492.
  11972. * https://tools.ietf.org/html/rfc3492#section-3.4
  11973. * @private
  11974. */
  11975. function adapt(delta, numPoints, firstTime) {
  11976. var k = 0;
  11977. delta = firstTime ? floor(delta / damp) : delta >> 1;
  11978. delta += floor(delta / numPoints);
  11979. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  11980. delta = floor(delta / baseMinusTMin);
  11981. }
  11982. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  11983. }
  11984. /**
  11985. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  11986. * symbols.
  11987. * @memberOf punycode
  11988. * @param {String} input The Punycode string of ASCII-only symbols.
  11989. * @returns {String} The resulting string of Unicode symbols.
  11990. */
  11991. function decode(input) {
  11992. // Don't use UCS-2
  11993. var output = [],
  11994. inputLength = input.length,
  11995. out,
  11996. i = 0,
  11997. n = initialN,
  11998. bias = initialBias,
  11999. basic,
  12000. j,
  12001. index,
  12002. oldi,
  12003. w,
  12004. k,
  12005. digit,
  12006. t,
  12007. /** Cached calculation results */
  12008. baseMinusT;
  12009. // Handle the basic code points: let `basic` be the number of input code
  12010. // points before the last delimiter, or `0` if there is none, then copy
  12011. // the first basic code points to the output.
  12012. basic = input.lastIndexOf(delimiter);
  12013. if (basic < 0) {
  12014. basic = 0;
  12015. }
  12016. for (j = 0; j < basic; ++j) {
  12017. // if it's not a basic code point
  12018. if (input.charCodeAt(j) >= 0x80) {
  12019. error('not-basic');
  12020. }
  12021. output.push(input.charCodeAt(j));
  12022. }
  12023. // Main decoding loop: start just after the last delimiter if any basic code
  12024. // points were copied; start at the beginning otherwise.
  12025. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  12026. // `index` is the index of the next character to be consumed.
  12027. // Decode a generalized variable-length integer into `delta`,
  12028. // which gets added to `i`. The overflow checking is easier
  12029. // if we increase `i` as we go, then subtract off its starting
  12030. // value at the end to obtain `delta`.
  12031. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  12032. if (index >= inputLength) {
  12033. error('invalid-input');
  12034. }
  12035. digit = basicToDigit(input.charCodeAt(index++));
  12036. if (digit >= base || digit > floor((maxInt - i) / w)) {
  12037. error('overflow');
  12038. }
  12039. i += digit * w;
  12040. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  12041. if (digit < t) {
  12042. break;
  12043. }
  12044. baseMinusT = base - t;
  12045. if (w > floor(maxInt / baseMinusT)) {
  12046. error('overflow');
  12047. }
  12048. w *= baseMinusT;
  12049. }
  12050. out = output.length + 1;
  12051. bias = adapt(i - oldi, out, oldi == 0);
  12052. // `i` was supposed to wrap around from `out` to `0`,
  12053. // incrementing `n` each time, so we'll fix that now:
  12054. if (floor(i / out) > maxInt - n) {
  12055. error('overflow');
  12056. }
  12057. n += floor(i / out);
  12058. i %= out;
  12059. // Insert `n` at position `i` of the output
  12060. output.splice(i++, 0, n);
  12061. }
  12062. return ucs2encode(output);
  12063. }
  12064. /**
  12065. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  12066. * Punycode string of ASCII-only symbols.
  12067. * @memberOf punycode
  12068. * @param {String} input The string of Unicode symbols.
  12069. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  12070. */
  12071. function encode(input) {
  12072. var n,
  12073. delta,
  12074. handledCPCount,
  12075. basicLength,
  12076. bias,
  12077. j,
  12078. m,
  12079. q,
  12080. k,
  12081. t,
  12082. currentValue,
  12083. output = [],
  12084. /** `inputLength` will hold the number of code points in `input`. */
  12085. inputLength,
  12086. /** Cached calculation results */
  12087. handledCPCountPlusOne,
  12088. baseMinusT,
  12089. qMinusT;
  12090. // Convert the input in UCS-2 to Unicode
  12091. input = ucs2decode(input);
  12092. // Cache the length
  12093. inputLength = input.length;
  12094. // Initialize the state
  12095. n = initialN;
  12096. delta = 0;
  12097. bias = initialBias;
  12098. // Handle the basic code points
  12099. for (j = 0; j < inputLength; ++j) {
  12100. currentValue = input[j];
  12101. if (currentValue < 0x80) {
  12102. output.push(stringFromCharCode(currentValue));
  12103. }
  12104. }
  12105. handledCPCount = basicLength = output.length;
  12106. // `handledCPCount` is the number of code points that have been handled;
  12107. // `basicLength` is the number of basic code points.
  12108. // Finish the basic string - if it is not empty - with a delimiter
  12109. if (basicLength) {
  12110. output.push(delimiter);
  12111. }
  12112. // Main encoding loop:
  12113. while (handledCPCount < inputLength) {
  12114. // All non-basic code points < n have been handled already. Find the next
  12115. // larger one:
  12116. for (m = maxInt, j = 0; j < inputLength; ++j) {
  12117. currentValue = input[j];
  12118. if (currentValue >= n && currentValue < m) {
  12119. m = currentValue;
  12120. }
  12121. }
  12122. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  12123. // but guard against overflow
  12124. handledCPCountPlusOne = handledCPCount + 1;
  12125. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  12126. error('overflow');
  12127. }
  12128. delta += (m - n) * handledCPCountPlusOne;
  12129. n = m;
  12130. for (j = 0; j < inputLength; ++j) {
  12131. currentValue = input[j];
  12132. if (currentValue < n && ++delta > maxInt) {
  12133. error('overflow');
  12134. }
  12135. if (currentValue == n) {
  12136. // Represent delta as a generalized variable-length integer
  12137. for (q = delta, k = base; /* no condition */; k += base) {
  12138. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  12139. if (q < t) {
  12140. break;
  12141. }
  12142. qMinusT = q - t;
  12143. baseMinusT = base - t;
  12144. output.push(
  12145. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  12146. );
  12147. q = floor(qMinusT / baseMinusT);
  12148. }
  12149. output.push(stringFromCharCode(digitToBasic(q, 0)));
  12150. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  12151. delta = 0;
  12152. ++handledCPCount;
  12153. }
  12154. }
  12155. ++delta;
  12156. ++n;
  12157. }
  12158. return output.join('');
  12159. }
  12160. /**
  12161. * Converts a Punycode string representing a domain name or an email address
  12162. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  12163. * it doesn't matter if you call it on a string that has already been
  12164. * converted to Unicode.
  12165. * @memberOf punycode
  12166. * @param {String} input The Punycoded domain name or email address to
  12167. * convert to Unicode.
  12168. * @returns {String} The Unicode representation of the given Punycode
  12169. * string.
  12170. */
  12171. function toUnicode(input) {
  12172. return mapDomain(input, function(string) {
  12173. return regexPunycode.test(string)
  12174. ? decode(string.slice(4).toLowerCase())
  12175. : string;
  12176. });
  12177. }
  12178. /**
  12179. * Converts a Unicode string representing a domain name or an email address to
  12180. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  12181. * i.e. it doesn't matter if you call it with a domain that's already in
  12182. * ASCII.
  12183. * @memberOf punycode
  12184. * @param {String} input The domain name or email address to convert, as a
  12185. * Unicode string.
  12186. * @returns {String} The Punycode representation of the given domain name or
  12187. * email address.
  12188. */
  12189. function toASCII(input) {
  12190. return mapDomain(input, function(string) {
  12191. return regexNonASCII.test(string)
  12192. ? 'xn--' + encode(string)
  12193. : string;
  12194. });
  12195. }
  12196. /*--------------------------------------------------------------------------*/
  12197. /** Define the public API */
  12198. punycode = {
  12199. /**
  12200. * A string representing the current Punycode.js version number.
  12201. * @memberOf punycode
  12202. * @type String
  12203. */
  12204. 'version': '1.4.1',
  12205. /**
  12206. * An object of methods to convert from JavaScript's internal character
  12207. * representation (UCS-2) to Unicode code points, and back.
  12208. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  12209. * @memberOf punycode
  12210. * @type Object
  12211. */
  12212. 'ucs2': {
  12213. 'decode': ucs2decode,
  12214. 'encode': ucs2encode
  12215. },
  12216. 'decode': decode,
  12217. 'encode': encode,
  12218. 'toASCII': toASCII,
  12219. 'toUnicode': toUnicode
  12220. };
  12221. /** Expose `punycode` */
  12222. // Some AMD build optimizers, like r.js, check for specific condition patterns
  12223. // like the following:
  12224. if (
  12225. typeof define == 'function' &&
  12226. typeof define.amd == 'object' &&
  12227. define.amd
  12228. ) {
  12229. define('punycode', function() {
  12230. return punycode;
  12231. });
  12232. } else if (freeExports && freeModule) {
  12233. if (module.exports == freeExports) {
  12234. // in Node.js, io.js, or RingoJS v0.8.0+
  12235. freeModule.exports = punycode;
  12236. } else {
  12237. // in Narwhal or RingoJS v0.7.0-
  12238. for (key in punycode) {
  12239. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  12240. }
  12241. }
  12242. } else {
  12243. // in Rhino or a web browser
  12244. root.punycode = punycode;
  12245. }
  12246. }(this));
  12247. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12248. },{}],52:[function(require,module,exports){
  12249. // Copyright Joyent, Inc. and other Node contributors.
  12250. //
  12251. // Permission is hereby granted, free of charge, to any person obtaining a
  12252. // copy of this software and associated documentation files (the
  12253. // "Software"), to deal in the Software without restriction, including
  12254. // without limitation the rights to use, copy, modify, merge, publish,
  12255. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12256. // persons to whom the Software is furnished to do so, subject to the
  12257. // following conditions:
  12258. //
  12259. // The above copyright notice and this permission notice shall be included
  12260. // in all copies or substantial portions of the Software.
  12261. //
  12262. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12263. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12264. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12265. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12266. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12267. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12268. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12269. 'use strict';
  12270. // If obj.hasOwnProperty has been overridden, then calling
  12271. // obj.hasOwnProperty(prop) will break.
  12272. // See: https://github.com/joyent/node/issues/1707
  12273. function hasOwnProperty(obj, prop) {
  12274. return Object.prototype.hasOwnProperty.call(obj, prop);
  12275. }
  12276. module.exports = function(qs, sep, eq, options) {
  12277. sep = sep || '&';
  12278. eq = eq || '=';
  12279. var obj = {};
  12280. if (typeof qs !== 'string' || qs.length === 0) {
  12281. return obj;
  12282. }
  12283. var regexp = /\+/g;
  12284. qs = qs.split(sep);
  12285. var maxKeys = 1000;
  12286. if (options && typeof options.maxKeys === 'number') {
  12287. maxKeys = options.maxKeys;
  12288. }
  12289. var len = qs.length;
  12290. // maxKeys <= 0 means that we should not limit keys count
  12291. if (maxKeys > 0 && len > maxKeys) {
  12292. len = maxKeys;
  12293. }
  12294. for (var i = 0; i < len; ++i) {
  12295. var x = qs[i].replace(regexp, '%20'),
  12296. idx = x.indexOf(eq),
  12297. kstr, vstr, k, v;
  12298. if (idx >= 0) {
  12299. kstr = x.substr(0, idx);
  12300. vstr = x.substr(idx + 1);
  12301. } else {
  12302. kstr = x;
  12303. vstr = '';
  12304. }
  12305. k = decodeURIComponent(kstr);
  12306. v = decodeURIComponent(vstr);
  12307. if (!hasOwnProperty(obj, k)) {
  12308. obj[k] = v;
  12309. } else if (isArray(obj[k])) {
  12310. obj[k].push(v);
  12311. } else {
  12312. obj[k] = [obj[k], v];
  12313. }
  12314. }
  12315. return obj;
  12316. };
  12317. var isArray = Array.isArray || function (xs) {
  12318. return Object.prototype.toString.call(xs) === '[object Array]';
  12319. };
  12320. },{}],53:[function(require,module,exports){
  12321. // Copyright Joyent, Inc. and other Node contributors.
  12322. //
  12323. // Permission is hereby granted, free of charge, to any person obtaining a
  12324. // copy of this software and associated documentation files (the
  12325. // "Software"), to deal in the Software without restriction, including
  12326. // without limitation the rights to use, copy, modify, merge, publish,
  12327. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12328. // persons to whom the Software is furnished to do so, subject to the
  12329. // following conditions:
  12330. //
  12331. // The above copyright notice and this permission notice shall be included
  12332. // in all copies or substantial portions of the Software.
  12333. //
  12334. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12335. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12336. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12337. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12338. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12339. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12340. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12341. 'use strict';
  12342. var stringifyPrimitive = function(v) {
  12343. switch (typeof v) {
  12344. case 'string':
  12345. return v;
  12346. case 'boolean':
  12347. return v ? 'true' : 'false';
  12348. case 'number':
  12349. return isFinite(v) ? v : '';
  12350. default:
  12351. return '';
  12352. }
  12353. };
  12354. module.exports = function(obj, sep, eq, name) {
  12355. sep = sep || '&';
  12356. eq = eq || '=';
  12357. if (obj === null) {
  12358. obj = undefined;
  12359. }
  12360. if (typeof obj === 'object') {
  12361. return map(objectKeys(obj), function(k) {
  12362. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  12363. if (isArray(obj[k])) {
  12364. return map(obj[k], function(v) {
  12365. return ks + encodeURIComponent(stringifyPrimitive(v));
  12366. }).join(sep);
  12367. } else {
  12368. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  12369. }
  12370. }).join(sep);
  12371. }
  12372. if (!name) return '';
  12373. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  12374. encodeURIComponent(stringifyPrimitive(obj));
  12375. };
  12376. var isArray = Array.isArray || function (xs) {
  12377. return Object.prototype.toString.call(xs) === '[object Array]';
  12378. };
  12379. function map (xs, f) {
  12380. if (xs.map) return xs.map(f);
  12381. var res = [];
  12382. for (var i = 0; i < xs.length; i++) {
  12383. res.push(f(xs[i], i));
  12384. }
  12385. return res;
  12386. }
  12387. var objectKeys = Object.keys || function (obj) {
  12388. var res = [];
  12389. for (var key in obj) {
  12390. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  12391. }
  12392. return res;
  12393. };
  12394. },{}],54:[function(require,module,exports){
  12395. 'use strict';
  12396. exports.decode = exports.parse = require('./decode');
  12397. exports.encode = exports.stringify = require('./encode');
  12398. },{"./decode":52,"./encode":53}],55:[function(require,module,exports){
  12399. 'use strict';
  12400. function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
  12401. var codes = {};
  12402. function createErrorType(code, message, Base) {
  12403. if (!Base) {
  12404. Base = Error;
  12405. }
  12406. function getMessage(arg1, arg2, arg3) {
  12407. if (typeof message === 'string') {
  12408. return message;
  12409. } else {
  12410. return message(arg1, arg2, arg3);
  12411. }
  12412. }
  12413. var NodeError =
  12414. /*#__PURE__*/
  12415. function (_Base) {
  12416. _inheritsLoose(NodeError, _Base);
  12417. function NodeError(arg1, arg2, arg3) {
  12418. return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
  12419. }
  12420. return NodeError;
  12421. }(Base);
  12422. NodeError.prototype.name = Base.name;
  12423. NodeError.prototype.code = code;
  12424. codes[code] = NodeError;
  12425. } // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
  12426. function oneOf(expected, thing) {
  12427. if (Array.isArray(expected)) {
  12428. var len = expected.length;
  12429. expected = expected.map(function (i) {
  12430. return String(i);
  12431. });
  12432. if (len > 2) {
  12433. return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
  12434. } else if (len === 2) {
  12435. return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
  12436. } else {
  12437. return "of ".concat(thing, " ").concat(expected[0]);
  12438. }
  12439. } else {
  12440. return "of ".concat(thing, " ").concat(String(expected));
  12441. }
  12442. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
  12443. function startsWith(str, search, pos) {
  12444. return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
  12445. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
  12446. function endsWith(str, search, this_len) {
  12447. if (this_len === undefined || this_len > str.length) {
  12448. this_len = str.length;
  12449. }
  12450. return str.substring(this_len - search.length, this_len) === search;
  12451. } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
  12452. function includes(str, search, start) {
  12453. if (typeof start !== 'number') {
  12454. start = 0;
  12455. }
  12456. if (start + search.length > str.length) {
  12457. return false;
  12458. } else {
  12459. return str.indexOf(search, start) !== -1;
  12460. }
  12461. }
  12462. createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
  12463. return 'The value "' + value + '" is invalid for option "' + name + '"';
  12464. }, TypeError);
  12465. createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
  12466. // determiner: 'must be' or 'must not be'
  12467. var determiner;
  12468. if (typeof expected === 'string' && startsWith(expected, 'not ')) {
  12469. determiner = 'must not be';
  12470. expected = expected.replace(/^not /, '');
  12471. } else {
  12472. determiner = 'must be';
  12473. }
  12474. var msg;
  12475. if (endsWith(name, ' argument')) {
  12476. // For cases like 'first argument'
  12477. msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  12478. } else {
  12479. var type = includes(name, '.') ? 'property' : 'argument';
  12480. msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
  12481. }
  12482. msg += ". Received type ".concat(typeof actual);
  12483. return msg;
  12484. }, TypeError);
  12485. createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
  12486. createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
  12487. return 'The ' + name + ' method is not implemented';
  12488. });
  12489. createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
  12490. createErrorType('ERR_STREAM_DESTROYED', function (name) {
  12491. return 'Cannot call ' + name + ' after a stream was destroyed';
  12492. });
  12493. createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
  12494. createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
  12495. createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
  12496. createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
  12497. createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
  12498. return 'Unknown encoding: ' + arg;
  12499. }, TypeError);
  12500. createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
  12501. module.exports.codes = codes;
  12502. },{}],56:[function(require,module,exports){
  12503. (function (process){(function (){
  12504. // Copyright Joyent, Inc. and other Node contributors.
  12505. //
  12506. // Permission is hereby granted, free of charge, to any person obtaining a
  12507. // copy of this software and associated documentation files (the
  12508. // "Software"), to deal in the Software without restriction, including
  12509. // without limitation the rights to use, copy, modify, merge, publish,
  12510. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12511. // persons to whom the Software is furnished to do so, subject to the
  12512. // following conditions:
  12513. //
  12514. // The above copyright notice and this permission notice shall be included
  12515. // in all copies or substantial portions of the Software.
  12516. //
  12517. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12518. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12519. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12520. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12521. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12522. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12523. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12524. // a duplex stream is just a stream that is both readable and writable.
  12525. // Since JS doesn't have multiple prototypal inheritance, this class
  12526. // prototypally inherits from Readable, and then parasitically from
  12527. // Writable.
  12528. 'use strict';
  12529. /*<replacement>*/
  12530. var objectKeys = Object.keys || function (obj) {
  12531. var keys = [];
  12532. for (var key in obj) {
  12533. keys.push(key);
  12534. }
  12535. return keys;
  12536. };
  12537. /*</replacement>*/
  12538. module.exports = Duplex;
  12539. var Readable = require('./_stream_readable');
  12540. var Writable = require('./_stream_writable');
  12541. require('inherits')(Duplex, Readable);
  12542. {
  12543. // Allow the keys array to be GC'ed.
  12544. var keys = objectKeys(Writable.prototype);
  12545. for (var v = 0; v < keys.length; v++) {
  12546. var method = keys[v];
  12547. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  12548. }
  12549. }
  12550. function Duplex(options) {
  12551. if (!(this instanceof Duplex)) return new Duplex(options);
  12552. Readable.call(this, options);
  12553. Writable.call(this, options);
  12554. this.allowHalfOpen = true;
  12555. if (options) {
  12556. if (options.readable === false) this.readable = false;
  12557. if (options.writable === false) this.writable = false;
  12558. if (options.allowHalfOpen === false) {
  12559. this.allowHalfOpen = false;
  12560. this.once('end', onend);
  12561. }
  12562. }
  12563. }
  12564. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  12565. // making it explicit this property is not enumerable
  12566. // because otherwise some prototype manipulation in
  12567. // userland will fail
  12568. enumerable: false,
  12569. get: function get() {
  12570. return this._writableState.highWaterMark;
  12571. }
  12572. });
  12573. Object.defineProperty(Duplex.prototype, 'writableBuffer', {
  12574. // making it explicit this property is not enumerable
  12575. // because otherwise some prototype manipulation in
  12576. // userland will fail
  12577. enumerable: false,
  12578. get: function get() {
  12579. return this._writableState && this._writableState.getBuffer();
  12580. }
  12581. });
  12582. Object.defineProperty(Duplex.prototype, 'writableLength', {
  12583. // making it explicit this property is not enumerable
  12584. // because otherwise some prototype manipulation in
  12585. // userland will fail
  12586. enumerable: false,
  12587. get: function get() {
  12588. return this._writableState.length;
  12589. }
  12590. }); // the no-half-open enforcer
  12591. function onend() {
  12592. // If the writable side ended, then we're ok.
  12593. if (this._writableState.ended) return; // no more data can be written.
  12594. // But allow more writes to happen in this tick.
  12595. process.nextTick(onEndNT, this);
  12596. }
  12597. function onEndNT(self) {
  12598. self.end();
  12599. }
  12600. Object.defineProperty(Duplex.prototype, 'destroyed', {
  12601. // making it explicit this property is not enumerable
  12602. // because otherwise some prototype manipulation in
  12603. // userland will fail
  12604. enumerable: false,
  12605. get: function get() {
  12606. if (this._readableState === undefined || this._writableState === undefined) {
  12607. return false;
  12608. }
  12609. return this._readableState.destroyed && this._writableState.destroyed;
  12610. },
  12611. set: function set(value) {
  12612. // we ignore the value if the stream
  12613. // has not been initialized yet
  12614. if (this._readableState === undefined || this._writableState === undefined) {
  12615. return;
  12616. } // backward compatibility, the user is explicitly
  12617. // managing destroyed
  12618. this._readableState.destroyed = value;
  12619. this._writableState.destroyed = value;
  12620. }
  12621. });
  12622. }).call(this)}).call(this,require('_process'))
  12623. },{"./_stream_readable":58,"./_stream_writable":60,"_process":50,"inherits":24}],57:[function(require,module,exports){
  12624. // Copyright Joyent, Inc. and other Node contributors.
  12625. //
  12626. // Permission is hereby granted, free of charge, to any person obtaining a
  12627. // copy of this software and associated documentation files (the
  12628. // "Software"), to deal in the Software without restriction, including
  12629. // without limitation the rights to use, copy, modify, merge, publish,
  12630. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12631. // persons to whom the Software is furnished to do so, subject to the
  12632. // following conditions:
  12633. //
  12634. // The above copyright notice and this permission notice shall be included
  12635. // in all copies or substantial portions of the Software.
  12636. //
  12637. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12638. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12639. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12640. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12641. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12642. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12643. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12644. // a passthrough stream.
  12645. // basically just the most minimal sort of Transform stream.
  12646. // Every written chunk gets output as-is.
  12647. 'use strict';
  12648. module.exports = PassThrough;
  12649. var Transform = require('./_stream_transform');
  12650. require('inherits')(PassThrough, Transform);
  12651. function PassThrough(options) {
  12652. if (!(this instanceof PassThrough)) return new PassThrough(options);
  12653. Transform.call(this, options);
  12654. }
  12655. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  12656. cb(null, chunk);
  12657. };
  12658. },{"./_stream_transform":59,"inherits":24}],58:[function(require,module,exports){
  12659. (function (process,global){(function (){
  12660. // Copyright Joyent, Inc. and other Node contributors.
  12661. //
  12662. // Permission is hereby granted, free of charge, to any person obtaining a
  12663. // copy of this software and associated documentation files (the
  12664. // "Software"), to deal in the Software without restriction, including
  12665. // without limitation the rights to use, copy, modify, merge, publish,
  12666. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12667. // persons to whom the Software is furnished to do so, subject to the
  12668. // following conditions:
  12669. //
  12670. // The above copyright notice and this permission notice shall be included
  12671. // in all copies or substantial portions of the Software.
  12672. //
  12673. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12674. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12675. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12676. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12677. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12678. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12679. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12680. 'use strict';
  12681. module.exports = Readable;
  12682. /*<replacement>*/
  12683. var Duplex;
  12684. /*</replacement>*/
  12685. Readable.ReadableState = ReadableState;
  12686. /*<replacement>*/
  12687. var EE = require('events').EventEmitter;
  12688. var EElistenerCount = function EElistenerCount(emitter, type) {
  12689. return emitter.listeners(type).length;
  12690. };
  12691. /*</replacement>*/
  12692. /*<replacement>*/
  12693. var Stream = require('./internal/streams/stream');
  12694. /*</replacement>*/
  12695. var Buffer = require('buffer').Buffer;
  12696. var OurUint8Array = global.Uint8Array || function () {};
  12697. function _uint8ArrayToBuffer(chunk) {
  12698. return Buffer.from(chunk);
  12699. }
  12700. function _isUint8Array(obj) {
  12701. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  12702. }
  12703. /*<replacement>*/
  12704. var debugUtil = require('util');
  12705. var debug;
  12706. if (debugUtil && debugUtil.debuglog) {
  12707. debug = debugUtil.debuglog('stream');
  12708. } else {
  12709. debug = function debug() {};
  12710. }
  12711. /*</replacement>*/
  12712. var BufferList = require('./internal/streams/buffer_list');
  12713. var destroyImpl = require('./internal/streams/destroy');
  12714. var _require = require('./internal/streams/state'),
  12715. getHighWaterMark = _require.getHighWaterMark;
  12716. var _require$codes = require('../errors').codes,
  12717. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  12718. ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
  12719. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  12720. ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
  12721. var StringDecoder;
  12722. var createReadableStreamAsyncIterator;
  12723. var from;
  12724. require('inherits')(Readable, Stream);
  12725. var errorOrDestroy = destroyImpl.errorOrDestroy;
  12726. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  12727. function prependListener(emitter, event, fn) {
  12728. // Sadly this is not cacheable as some libraries bundle their own
  12729. // event emitter implementation with them.
  12730. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
  12731. // userland ones. NEVER DO THIS. This is here only because this code needs
  12732. // to continue to work with older versions of Node.js that do not include
  12733. // the prependListener() method. The goal is to eventually remove this hack.
  12734. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  12735. }
  12736. function ReadableState(options, stream, isDuplex) {
  12737. Duplex = Duplex || require('./_stream_duplex');
  12738. options = options || {}; // Duplex streams are both readable and writable, but share
  12739. // the same options object.
  12740. // However, some cases require setting options to different
  12741. // values for the readable and the writable sides of the duplex stream.
  12742. // These options can be provided separately as readableXXX and writableXXX.
  12743. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
  12744. // make all the buffer merging and length checks go away
  12745. this.objectMode = !!options.objectMode;
  12746. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
  12747. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  12748. this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
  12749. // linked list can remove elements from the beginning faster than
  12750. // array.shift()
  12751. this.buffer = new BufferList();
  12752. this.length = 0;
  12753. this.pipes = null;
  12754. this.pipesCount = 0;
  12755. this.flowing = null;
  12756. this.ended = false;
  12757. this.endEmitted = false;
  12758. this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
  12759. // immediately, or on a later tick. We set this to true at first, because
  12760. // any actions that shouldn't happen until "later" should generally also
  12761. // not happen before the first read call.
  12762. this.sync = true; // whenever we return null, then we set a flag to say
  12763. // that we're awaiting a 'readable' event emission.
  12764. this.needReadable = false;
  12765. this.emittedReadable = false;
  12766. this.readableListening = false;
  12767. this.resumeScheduled = false;
  12768. this.paused = true; // Should close be emitted on destroy. Defaults to true.
  12769. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
  12770. this.autoDestroy = !!options.autoDestroy; // has it been destroyed
  12771. this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
  12772. // encoding is 'binary' so we have to make this configurable.
  12773. // Everything else in the universe uses 'utf8', though.
  12774. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
  12775. this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
  12776. this.readingMore = false;
  12777. this.decoder = null;
  12778. this.encoding = null;
  12779. if (options.encoding) {
  12780. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  12781. this.decoder = new StringDecoder(options.encoding);
  12782. this.encoding = options.encoding;
  12783. }
  12784. }
  12785. function Readable(options) {
  12786. Duplex = Duplex || require('./_stream_duplex');
  12787. if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
  12788. // the ReadableState constructor, at least with V8 6.5
  12789. var isDuplex = this instanceof Duplex;
  12790. this._readableState = new ReadableState(options, this, isDuplex); // legacy
  12791. this.readable = true;
  12792. if (options) {
  12793. if (typeof options.read === 'function') this._read = options.read;
  12794. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  12795. }
  12796. Stream.call(this);
  12797. }
  12798. Object.defineProperty(Readable.prototype, 'destroyed', {
  12799. // making it explicit this property is not enumerable
  12800. // because otherwise some prototype manipulation in
  12801. // userland will fail
  12802. enumerable: false,
  12803. get: function get() {
  12804. if (this._readableState === undefined) {
  12805. return false;
  12806. }
  12807. return this._readableState.destroyed;
  12808. },
  12809. set: function set(value) {
  12810. // we ignore the value if the stream
  12811. // has not been initialized yet
  12812. if (!this._readableState) {
  12813. return;
  12814. } // backward compatibility, the user is explicitly
  12815. // managing destroyed
  12816. this._readableState.destroyed = value;
  12817. }
  12818. });
  12819. Readable.prototype.destroy = destroyImpl.destroy;
  12820. Readable.prototype._undestroy = destroyImpl.undestroy;
  12821. Readable.prototype._destroy = function (err, cb) {
  12822. cb(err);
  12823. }; // Manually shove something into the read() buffer.
  12824. // This returns true if the highWaterMark has not been hit yet,
  12825. // similar to how Writable.write() returns true if you should
  12826. // write() some more.
  12827. Readable.prototype.push = function (chunk, encoding) {
  12828. var state = this._readableState;
  12829. var skipChunkCheck;
  12830. if (!state.objectMode) {
  12831. if (typeof chunk === 'string') {
  12832. encoding = encoding || state.defaultEncoding;
  12833. if (encoding !== state.encoding) {
  12834. chunk = Buffer.from(chunk, encoding);
  12835. encoding = '';
  12836. }
  12837. skipChunkCheck = true;
  12838. }
  12839. } else {
  12840. skipChunkCheck = true;
  12841. }
  12842. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  12843. }; // Unshift should *always* be something directly out of read()
  12844. Readable.prototype.unshift = function (chunk) {
  12845. return readableAddChunk(this, chunk, null, true, false);
  12846. };
  12847. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  12848. debug('readableAddChunk', chunk);
  12849. var state = stream._readableState;
  12850. if (chunk === null) {
  12851. state.reading = false;
  12852. onEofChunk(stream, state);
  12853. } else {
  12854. var er;
  12855. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  12856. if (er) {
  12857. errorOrDestroy(stream, er);
  12858. } else if (state.objectMode || chunk && chunk.length > 0) {
  12859. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  12860. chunk = _uint8ArrayToBuffer(chunk);
  12861. }
  12862. if (addToFront) {
  12863. if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
  12864. } else if (state.ended) {
  12865. errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
  12866. } else if (state.destroyed) {
  12867. return false;
  12868. } else {
  12869. state.reading = false;
  12870. if (state.decoder && !encoding) {
  12871. chunk = state.decoder.write(chunk);
  12872. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  12873. } else {
  12874. addChunk(stream, state, chunk, false);
  12875. }
  12876. }
  12877. } else if (!addToFront) {
  12878. state.reading = false;
  12879. maybeReadMore(stream, state);
  12880. }
  12881. } // We can push more data if we are below the highWaterMark.
  12882. // Also, if we have no data yet, we can stand some more bytes.
  12883. // This is to work around cases where hwm=0, such as the repl.
  12884. return !state.ended && (state.length < state.highWaterMark || state.length === 0);
  12885. }
  12886. function addChunk(stream, state, chunk, addToFront) {
  12887. if (state.flowing && state.length === 0 && !state.sync) {
  12888. state.awaitDrain = 0;
  12889. stream.emit('data', chunk);
  12890. } else {
  12891. // update the buffer info.
  12892. state.length += state.objectMode ? 1 : chunk.length;
  12893. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  12894. if (state.needReadable) emitReadable(stream);
  12895. }
  12896. maybeReadMore(stream, state);
  12897. }
  12898. function chunkInvalid(state, chunk) {
  12899. var er;
  12900. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  12901. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
  12902. }
  12903. return er;
  12904. }
  12905. Readable.prototype.isPaused = function () {
  12906. return this._readableState.flowing === false;
  12907. }; // backwards compatibility.
  12908. Readable.prototype.setEncoding = function (enc) {
  12909. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  12910. var decoder = new StringDecoder(enc);
  12911. this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
  12912. this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
  12913. var p = this._readableState.buffer.head;
  12914. var content = '';
  12915. while (p !== null) {
  12916. content += decoder.write(p.data);
  12917. p = p.next;
  12918. }
  12919. this._readableState.buffer.clear();
  12920. if (content !== '') this._readableState.buffer.push(content);
  12921. this._readableState.length = content.length;
  12922. return this;
  12923. }; // Don't raise the hwm > 1GB
  12924. var MAX_HWM = 0x40000000;
  12925. function computeNewHighWaterMark(n) {
  12926. if (n >= MAX_HWM) {
  12927. // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
  12928. n = MAX_HWM;
  12929. } else {
  12930. // Get the next highest power of 2 to prevent increasing hwm excessively in
  12931. // tiny amounts
  12932. n--;
  12933. n |= n >>> 1;
  12934. n |= n >>> 2;
  12935. n |= n >>> 4;
  12936. n |= n >>> 8;
  12937. n |= n >>> 16;
  12938. n++;
  12939. }
  12940. return n;
  12941. } // This function is designed to be inlinable, so please take care when making
  12942. // changes to the function body.
  12943. function howMuchToRead(n, state) {
  12944. if (n <= 0 || state.length === 0 && state.ended) return 0;
  12945. if (state.objectMode) return 1;
  12946. if (n !== n) {
  12947. // Only flow one buffer at a time
  12948. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  12949. } // If we're asking for more than the current hwm, then raise the hwm.
  12950. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  12951. if (n <= state.length) return n; // Don't have enough
  12952. if (!state.ended) {
  12953. state.needReadable = true;
  12954. return 0;
  12955. }
  12956. return state.length;
  12957. } // you can override either this method, or the async _read(n) below.
  12958. Readable.prototype.read = function (n) {
  12959. debug('read', n);
  12960. n = parseInt(n, 10);
  12961. var state = this._readableState;
  12962. var nOrig = n;
  12963. if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
  12964. // already have a bunch of data in the buffer, then just trigger
  12965. // the 'readable' event and move on.
  12966. if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
  12967. debug('read: emitReadable', state.length, state.ended);
  12968. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  12969. return null;
  12970. }
  12971. n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
  12972. if (n === 0 && state.ended) {
  12973. if (state.length === 0) endReadable(this);
  12974. return null;
  12975. } // All the actual chunk generation logic needs to be
  12976. // *below* the call to _read. The reason is that in certain
  12977. // synthetic stream cases, such as passthrough streams, _read
  12978. // may be a completely synchronous operation which may change
  12979. // the state of the read buffer, providing enough data when
  12980. // before there was *not* enough.
  12981. //
  12982. // So, the steps are:
  12983. // 1. Figure out what the state of things will be after we do
  12984. // a read from the buffer.
  12985. //
  12986. // 2. If that resulting state will trigger a _read, then call _read.
  12987. // Note that this may be asynchronous, or synchronous. Yes, it is
  12988. // deeply ugly to write APIs this way, but that still doesn't mean
  12989. // that the Readable class should behave improperly, as streams are
  12990. // designed to be sync/async agnostic.
  12991. // Take note if the _read call is sync or async (ie, if the read call
  12992. // has returned yet), so that we know whether or not it's safe to emit
  12993. // 'readable' etc.
  12994. //
  12995. // 3. Actually pull the requested chunks out of the buffer and return.
  12996. // if we need a readable event, then we need to do some reading.
  12997. var doRead = state.needReadable;
  12998. debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
  12999. if (state.length === 0 || state.length - n < state.highWaterMark) {
  13000. doRead = true;
  13001. debug('length less than watermark', doRead);
  13002. } // however, if we've ended, then there's no point, and if we're already
  13003. // reading, then it's unnecessary.
  13004. if (state.ended || state.reading) {
  13005. doRead = false;
  13006. debug('reading or ended', doRead);
  13007. } else if (doRead) {
  13008. debug('do read');
  13009. state.reading = true;
  13010. state.sync = true; // if the length is currently zero, then we *need* a readable event.
  13011. if (state.length === 0) state.needReadable = true; // call internal read method
  13012. this._read(state.highWaterMark);
  13013. state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
  13014. // and we need to re-evaluate how much data we can return to the user.
  13015. if (!state.reading) n = howMuchToRead(nOrig, state);
  13016. }
  13017. var ret;
  13018. if (n > 0) ret = fromList(n, state);else ret = null;
  13019. if (ret === null) {
  13020. state.needReadable = state.length <= state.highWaterMark;
  13021. n = 0;
  13022. } else {
  13023. state.length -= n;
  13024. state.awaitDrain = 0;
  13025. }
  13026. if (state.length === 0) {
  13027. // If we have nothing in the buffer, then we want to know
  13028. // as soon as we *do* get something into the buffer.
  13029. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
  13030. if (nOrig !== n && state.ended) endReadable(this);
  13031. }
  13032. if (ret !== null) this.emit('data', ret);
  13033. return ret;
  13034. };
  13035. function onEofChunk(stream, state) {
  13036. debug('onEofChunk');
  13037. if (state.ended) return;
  13038. if (state.decoder) {
  13039. var chunk = state.decoder.end();
  13040. if (chunk && chunk.length) {
  13041. state.buffer.push(chunk);
  13042. state.length += state.objectMode ? 1 : chunk.length;
  13043. }
  13044. }
  13045. state.ended = true;
  13046. if (state.sync) {
  13047. // if we are sync, wait until next tick to emit the data.
  13048. // Otherwise we risk emitting data in the flow()
  13049. // the readable code triggers during a read() call
  13050. emitReadable(stream);
  13051. } else {
  13052. // emit 'readable' now to make sure it gets picked up.
  13053. state.needReadable = false;
  13054. if (!state.emittedReadable) {
  13055. state.emittedReadable = true;
  13056. emitReadable_(stream);
  13057. }
  13058. }
  13059. } // Don't emit readable right away in sync mode, because this can trigger
  13060. // another read() call => stack overflow. This way, it might trigger
  13061. // a nextTick recursion warning, but that's not so bad.
  13062. function emitReadable(stream) {
  13063. var state = stream._readableState;
  13064. debug('emitReadable', state.needReadable, state.emittedReadable);
  13065. state.needReadable = false;
  13066. if (!state.emittedReadable) {
  13067. debug('emitReadable', state.flowing);
  13068. state.emittedReadable = true;
  13069. process.nextTick(emitReadable_, stream);
  13070. }
  13071. }
  13072. function emitReadable_(stream) {
  13073. var state = stream._readableState;
  13074. debug('emitReadable_', state.destroyed, state.length, state.ended);
  13075. if (!state.destroyed && (state.length || state.ended)) {
  13076. stream.emit('readable');
  13077. state.emittedReadable = false;
  13078. } // The stream needs another readable event if
  13079. // 1. It is not flowing, as the flow mechanism will take
  13080. // care of it.
  13081. // 2. It is not ended.
  13082. // 3. It is below the highWaterMark, so we can schedule
  13083. // another readable later.
  13084. state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
  13085. flow(stream);
  13086. } // at this point, the user has presumably seen the 'readable' event,
  13087. // and called read() to consume some data. that may have triggered
  13088. // in turn another _read(n) call, in which case reading = true if
  13089. // it's in progress.
  13090. // However, if we're not ended, or reading, and the length < hwm,
  13091. // then go ahead and try to read some more preemptively.
  13092. function maybeReadMore(stream, state) {
  13093. if (!state.readingMore) {
  13094. state.readingMore = true;
  13095. process.nextTick(maybeReadMore_, stream, state);
  13096. }
  13097. }
  13098. function maybeReadMore_(stream, state) {
  13099. // Attempt to read more data if we should.
  13100. //
  13101. // The conditions for reading more data are (one of):
  13102. // - Not enough data buffered (state.length < state.highWaterMark). The loop
  13103. // is responsible for filling the buffer with enough data if such data
  13104. // is available. If highWaterMark is 0 and we are not in the flowing mode
  13105. // we should _not_ attempt to buffer any extra data. We'll get more data
  13106. // when the stream consumer calls read() instead.
  13107. // - No data in the buffer, and the stream is in flowing mode. In this mode
  13108. // the loop below is responsible for ensuring read() is called. Failing to
  13109. // call read here would abort the flow and there's no other mechanism for
  13110. // continuing the flow if the stream consumer has just subscribed to the
  13111. // 'data' event.
  13112. //
  13113. // In addition to the above conditions to keep reading data, the following
  13114. // conditions prevent the data from being read:
  13115. // - The stream has ended (state.ended).
  13116. // - There is already a pending 'read' operation (state.reading). This is a
  13117. // case where the the stream has called the implementation defined _read()
  13118. // method, but they are processing the call asynchronously and have _not_
  13119. // called push() with new data. In this case we skip performing more
  13120. // read()s. The execution ends in this method again after the _read() ends
  13121. // up calling push() with more data.
  13122. while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
  13123. var len = state.length;
  13124. debug('maybeReadMore read 0');
  13125. stream.read(0);
  13126. if (len === state.length) // didn't get any data, stop spinning.
  13127. break;
  13128. }
  13129. state.readingMore = false;
  13130. } // abstract method. to be overridden in specific implementation classes.
  13131. // call cb(er, data) where data is <= n in length.
  13132. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  13133. // arbitrary, and perhaps not very meaningful.
  13134. Readable.prototype._read = function (n) {
  13135. errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
  13136. };
  13137. Readable.prototype.pipe = function (dest, pipeOpts) {
  13138. var src = this;
  13139. var state = this._readableState;
  13140. switch (state.pipesCount) {
  13141. case 0:
  13142. state.pipes = dest;
  13143. break;
  13144. case 1:
  13145. state.pipes = [state.pipes, dest];
  13146. break;
  13147. default:
  13148. state.pipes.push(dest);
  13149. break;
  13150. }
  13151. state.pipesCount += 1;
  13152. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  13153. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  13154. var endFn = doEnd ? onend : unpipe;
  13155. if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
  13156. dest.on('unpipe', onunpipe);
  13157. function onunpipe(readable, unpipeInfo) {
  13158. debug('onunpipe');
  13159. if (readable === src) {
  13160. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  13161. unpipeInfo.hasUnpiped = true;
  13162. cleanup();
  13163. }
  13164. }
  13165. }
  13166. function onend() {
  13167. debug('onend');
  13168. dest.end();
  13169. } // when the dest drains, it reduces the awaitDrain counter
  13170. // on the source. This would be more elegant with a .once()
  13171. // handler in flow(), but adding and removing repeatedly is
  13172. // too slow.
  13173. var ondrain = pipeOnDrain(src);
  13174. dest.on('drain', ondrain);
  13175. var cleanedUp = false;
  13176. function cleanup() {
  13177. debug('cleanup'); // cleanup event handlers once the pipe is broken
  13178. dest.removeListener('close', onclose);
  13179. dest.removeListener('finish', onfinish);
  13180. dest.removeListener('drain', ondrain);
  13181. dest.removeListener('error', onerror);
  13182. dest.removeListener('unpipe', onunpipe);
  13183. src.removeListener('end', onend);
  13184. src.removeListener('end', unpipe);
  13185. src.removeListener('data', ondata);
  13186. cleanedUp = true; // if the reader is waiting for a drain event from this
  13187. // specific writer, then it would cause it to never start
  13188. // flowing again.
  13189. // So, if this is awaiting a drain, then we just call it now.
  13190. // If we don't know, then assume that we are waiting for one.
  13191. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  13192. }
  13193. src.on('data', ondata);
  13194. function ondata(chunk) {
  13195. debug('ondata');
  13196. var ret = dest.write(chunk);
  13197. debug('dest.write', ret);
  13198. if (ret === false) {
  13199. // If the user unpiped during `dest.write()`, it is possible
  13200. // to get stuck in a permanently paused state if that write
  13201. // also returned false.
  13202. // => Check whether `dest` is still a piping destination.
  13203. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  13204. debug('false write response, pause', state.awaitDrain);
  13205. state.awaitDrain++;
  13206. }
  13207. src.pause();
  13208. }
  13209. } // if the dest has an error, then stop piping into it.
  13210. // however, don't suppress the throwing behavior for this.
  13211. function onerror(er) {
  13212. debug('onerror', er);
  13213. unpipe();
  13214. dest.removeListener('error', onerror);
  13215. if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
  13216. } // Make sure our error handler is attached before userland ones.
  13217. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
  13218. function onclose() {
  13219. dest.removeListener('finish', onfinish);
  13220. unpipe();
  13221. }
  13222. dest.once('close', onclose);
  13223. function onfinish() {
  13224. debug('onfinish');
  13225. dest.removeListener('close', onclose);
  13226. unpipe();
  13227. }
  13228. dest.once('finish', onfinish);
  13229. function unpipe() {
  13230. debug('unpipe');
  13231. src.unpipe(dest);
  13232. } // tell the dest that it's being piped to
  13233. dest.emit('pipe', src); // start the flow if it hasn't been started already.
  13234. if (!state.flowing) {
  13235. debug('pipe resume');
  13236. src.resume();
  13237. }
  13238. return dest;
  13239. };
  13240. function pipeOnDrain(src) {
  13241. return function pipeOnDrainFunctionResult() {
  13242. var state = src._readableState;
  13243. debug('pipeOnDrain', state.awaitDrain);
  13244. if (state.awaitDrain) state.awaitDrain--;
  13245. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  13246. state.flowing = true;
  13247. flow(src);
  13248. }
  13249. };
  13250. }
  13251. Readable.prototype.unpipe = function (dest) {
  13252. var state = this._readableState;
  13253. var unpipeInfo = {
  13254. hasUnpiped: false
  13255. }; // if we're not piping anywhere, then do nothing.
  13256. if (state.pipesCount === 0) return this; // just one destination. most common case.
  13257. if (state.pipesCount === 1) {
  13258. // passed in one, but it's not the right one.
  13259. if (dest && dest !== state.pipes) return this;
  13260. if (!dest) dest = state.pipes; // got a match.
  13261. state.pipes = null;
  13262. state.pipesCount = 0;
  13263. state.flowing = false;
  13264. if (dest) dest.emit('unpipe', this, unpipeInfo);
  13265. return this;
  13266. } // slow case. multiple pipe destinations.
  13267. if (!dest) {
  13268. // remove all.
  13269. var dests = state.pipes;
  13270. var len = state.pipesCount;
  13271. state.pipes = null;
  13272. state.pipesCount = 0;
  13273. state.flowing = false;
  13274. for (var i = 0; i < len; i++) {
  13275. dests[i].emit('unpipe', this, {
  13276. hasUnpiped: false
  13277. });
  13278. }
  13279. return this;
  13280. } // try to find the right one.
  13281. var index = indexOf(state.pipes, dest);
  13282. if (index === -1) return this;
  13283. state.pipes.splice(index, 1);
  13284. state.pipesCount -= 1;
  13285. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  13286. dest.emit('unpipe', this, unpipeInfo);
  13287. return this;
  13288. }; // set up data events if they are asked for
  13289. // Ensure readable listeners eventually get something
  13290. Readable.prototype.on = function (ev, fn) {
  13291. var res = Stream.prototype.on.call(this, ev, fn);
  13292. var state = this._readableState;
  13293. if (ev === 'data') {
  13294. // update readableListening so that resume() may be a no-op
  13295. // a few lines down. This is needed to support once('readable').
  13296. state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
  13297. if (state.flowing !== false) this.resume();
  13298. } else if (ev === 'readable') {
  13299. if (!state.endEmitted && !state.readableListening) {
  13300. state.readableListening = state.needReadable = true;
  13301. state.flowing = false;
  13302. state.emittedReadable = false;
  13303. debug('on readable', state.length, state.reading);
  13304. if (state.length) {
  13305. emitReadable(this);
  13306. } else if (!state.reading) {
  13307. process.nextTick(nReadingNextTick, this);
  13308. }
  13309. }
  13310. }
  13311. return res;
  13312. };
  13313. Readable.prototype.addListener = Readable.prototype.on;
  13314. Readable.prototype.removeListener = function (ev, fn) {
  13315. var res = Stream.prototype.removeListener.call(this, ev, fn);
  13316. if (ev === 'readable') {
  13317. // We need to check if there is someone still listening to
  13318. // readable and reset the state. However this needs to happen
  13319. // after readable has been emitted but before I/O (nextTick) to
  13320. // support once('readable', fn) cycles. This means that calling
  13321. // resume within the same tick will have no
  13322. // effect.
  13323. process.nextTick(updateReadableListening, this);
  13324. }
  13325. return res;
  13326. };
  13327. Readable.prototype.removeAllListeners = function (ev) {
  13328. var res = Stream.prototype.removeAllListeners.apply(this, arguments);
  13329. if (ev === 'readable' || ev === undefined) {
  13330. // We need to check if there is someone still listening to
  13331. // readable and reset the state. However this needs to happen
  13332. // after readable has been emitted but before I/O (nextTick) to
  13333. // support once('readable', fn) cycles. This means that calling
  13334. // resume within the same tick will have no
  13335. // effect.
  13336. process.nextTick(updateReadableListening, this);
  13337. }
  13338. return res;
  13339. };
  13340. function updateReadableListening(self) {
  13341. var state = self._readableState;
  13342. state.readableListening = self.listenerCount('readable') > 0;
  13343. if (state.resumeScheduled && !state.paused) {
  13344. // flowing needs to be set to true now, otherwise
  13345. // the upcoming resume will not flow.
  13346. state.flowing = true; // crude way to check if we should resume
  13347. } else if (self.listenerCount('data') > 0) {
  13348. self.resume();
  13349. }
  13350. }
  13351. function nReadingNextTick(self) {
  13352. debug('readable nexttick read 0');
  13353. self.read(0);
  13354. } // pause() and resume() are remnants of the legacy readable stream API
  13355. // If the user uses them, then switch into old mode.
  13356. Readable.prototype.resume = function () {
  13357. var state = this._readableState;
  13358. if (!state.flowing) {
  13359. debug('resume'); // we flow only if there is no one listening
  13360. // for readable, but we still have to call
  13361. // resume()
  13362. state.flowing = !state.readableListening;
  13363. resume(this, state);
  13364. }
  13365. state.paused = false;
  13366. return this;
  13367. };
  13368. function resume(stream, state) {
  13369. if (!state.resumeScheduled) {
  13370. state.resumeScheduled = true;
  13371. process.nextTick(resume_, stream, state);
  13372. }
  13373. }
  13374. function resume_(stream, state) {
  13375. debug('resume', state.reading);
  13376. if (!state.reading) {
  13377. stream.read(0);
  13378. }
  13379. state.resumeScheduled = false;
  13380. stream.emit('resume');
  13381. flow(stream);
  13382. if (state.flowing && !state.reading) stream.read(0);
  13383. }
  13384. Readable.prototype.pause = function () {
  13385. debug('call pause flowing=%j', this._readableState.flowing);
  13386. if (this._readableState.flowing !== false) {
  13387. debug('pause');
  13388. this._readableState.flowing = false;
  13389. this.emit('pause');
  13390. }
  13391. this._readableState.paused = true;
  13392. return this;
  13393. };
  13394. function flow(stream) {
  13395. var state = stream._readableState;
  13396. debug('flow', state.flowing);
  13397. while (state.flowing && stream.read() !== null) {
  13398. ;
  13399. }
  13400. } // wrap an old-style stream as the async data source.
  13401. // This is *not* part of the readable stream interface.
  13402. // It is an ugly unfortunate mess of history.
  13403. Readable.prototype.wrap = function (stream) {
  13404. var _this = this;
  13405. var state = this._readableState;
  13406. var paused = false;
  13407. stream.on('end', function () {
  13408. debug('wrapped end');
  13409. if (state.decoder && !state.ended) {
  13410. var chunk = state.decoder.end();
  13411. if (chunk && chunk.length) _this.push(chunk);
  13412. }
  13413. _this.push(null);
  13414. });
  13415. stream.on('data', function (chunk) {
  13416. debug('wrapped data');
  13417. if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
  13418. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  13419. var ret = _this.push(chunk);
  13420. if (!ret) {
  13421. paused = true;
  13422. stream.pause();
  13423. }
  13424. }); // proxy all the other methods.
  13425. // important when wrapping filters and duplexes.
  13426. for (var i in stream) {
  13427. if (this[i] === undefined && typeof stream[i] === 'function') {
  13428. this[i] = function methodWrap(method) {
  13429. return function methodWrapReturnFunction() {
  13430. return stream[method].apply(stream, arguments);
  13431. };
  13432. }(i);
  13433. }
  13434. } // proxy certain important events.
  13435. for (var n = 0; n < kProxyEvents.length; n++) {
  13436. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  13437. } // when we try to consume some more bytes, simply unpause the
  13438. // underlying stream.
  13439. this._read = function (n) {
  13440. debug('wrapped _read', n);
  13441. if (paused) {
  13442. paused = false;
  13443. stream.resume();
  13444. }
  13445. };
  13446. return this;
  13447. };
  13448. if (typeof Symbol === 'function') {
  13449. Readable.prototype[Symbol.asyncIterator] = function () {
  13450. if (createReadableStreamAsyncIterator === undefined) {
  13451. createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
  13452. }
  13453. return createReadableStreamAsyncIterator(this);
  13454. };
  13455. }
  13456. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  13457. // making it explicit this property is not enumerable
  13458. // because otherwise some prototype manipulation in
  13459. // userland will fail
  13460. enumerable: false,
  13461. get: function get() {
  13462. return this._readableState.highWaterMark;
  13463. }
  13464. });
  13465. Object.defineProperty(Readable.prototype, 'readableBuffer', {
  13466. // making it explicit this property is not enumerable
  13467. // because otherwise some prototype manipulation in
  13468. // userland will fail
  13469. enumerable: false,
  13470. get: function get() {
  13471. return this._readableState && this._readableState.buffer;
  13472. }
  13473. });
  13474. Object.defineProperty(Readable.prototype, 'readableFlowing', {
  13475. // making it explicit this property is not enumerable
  13476. // because otherwise some prototype manipulation in
  13477. // userland will fail
  13478. enumerable: false,
  13479. get: function get() {
  13480. return this._readableState.flowing;
  13481. },
  13482. set: function set(state) {
  13483. if (this._readableState) {
  13484. this._readableState.flowing = state;
  13485. }
  13486. }
  13487. }); // exposed for testing purposes only.
  13488. Readable._fromList = fromList;
  13489. Object.defineProperty(Readable.prototype, 'readableLength', {
  13490. // making it explicit this property is not enumerable
  13491. // because otherwise some prototype manipulation in
  13492. // userland will fail
  13493. enumerable: false,
  13494. get: function get() {
  13495. return this._readableState.length;
  13496. }
  13497. }); // Pluck off n bytes from an array of buffers.
  13498. // Length is the combined lengths of all the buffers in the list.
  13499. // This function is designed to be inlinable, so please take care when making
  13500. // changes to the function body.
  13501. function fromList(n, state) {
  13502. // nothing buffered
  13503. if (state.length === 0) return null;
  13504. var ret;
  13505. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  13506. // read it all, truncate the list
  13507. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
  13508. state.buffer.clear();
  13509. } else {
  13510. // read part of list
  13511. ret = state.buffer.consume(n, state.decoder);
  13512. }
  13513. return ret;
  13514. }
  13515. function endReadable(stream) {
  13516. var state = stream._readableState;
  13517. debug('endReadable', state.endEmitted);
  13518. if (!state.endEmitted) {
  13519. state.ended = true;
  13520. process.nextTick(endReadableNT, state, stream);
  13521. }
  13522. }
  13523. function endReadableNT(state, stream) {
  13524. debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
  13525. if (!state.endEmitted && state.length === 0) {
  13526. state.endEmitted = true;
  13527. stream.readable = false;
  13528. stream.emit('end');
  13529. if (state.autoDestroy) {
  13530. // In case of duplex streams we need a way to detect
  13531. // if the writable side is ready for autoDestroy as well
  13532. var wState = stream._writableState;
  13533. if (!wState || wState.autoDestroy && wState.finished) {
  13534. stream.destroy();
  13535. }
  13536. }
  13537. }
  13538. }
  13539. if (typeof Symbol === 'function') {
  13540. Readable.from = function (iterable, opts) {
  13541. if (from === undefined) {
  13542. from = require('./internal/streams/from');
  13543. }
  13544. return from(Readable, iterable, opts);
  13545. };
  13546. }
  13547. function indexOf(xs, x) {
  13548. for (var i = 0, l = xs.length; i < l; i++) {
  13549. if (xs[i] === x) return i;
  13550. }
  13551. return -1;
  13552. }
  13553. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13554. },{"../errors":55,"./_stream_duplex":56,"./internal/streams/async_iterator":61,"./internal/streams/buffer_list":62,"./internal/streams/destroy":63,"./internal/streams/from":65,"./internal/streams/state":67,"./internal/streams/stream":68,"_process":50,"buffer":17,"events":22,"inherits":24,"string_decoder/":75,"util":16}],59:[function(require,module,exports){
  13555. // Copyright Joyent, Inc. and other Node contributors.
  13556. //
  13557. // Permission is hereby granted, free of charge, to any person obtaining a
  13558. // copy of this software and associated documentation files (the
  13559. // "Software"), to deal in the Software without restriction, including
  13560. // without limitation the rights to use, copy, modify, merge, publish,
  13561. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13562. // persons to whom the Software is furnished to do so, subject to the
  13563. // following conditions:
  13564. //
  13565. // The above copyright notice and this permission notice shall be included
  13566. // in all copies or substantial portions of the Software.
  13567. //
  13568. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13569. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13570. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13571. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13572. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13573. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13574. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13575. // a transform stream is a readable/writable stream where you do
  13576. // something with the data. Sometimes it's called a "filter",
  13577. // but that's not a great name for it, since that implies a thing where
  13578. // some bits pass through, and others are simply ignored. (That would
  13579. // be a valid example of a transform, of course.)
  13580. //
  13581. // While the output is causally related to the input, it's not a
  13582. // necessarily symmetric or synchronous transformation. For example,
  13583. // a zlib stream might take multiple plain-text writes(), and then
  13584. // emit a single compressed chunk some time in the future.
  13585. //
  13586. // Here's how this works:
  13587. //
  13588. // The Transform stream has all the aspects of the readable and writable
  13589. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  13590. // internally, and returns false if there's a lot of pending writes
  13591. // buffered up. When you call read(), that calls _read(n) until
  13592. // there's enough pending readable data buffered up.
  13593. //
  13594. // In a transform stream, the written data is placed in a buffer. When
  13595. // _read(n) is called, it transforms the queued up data, calling the
  13596. // buffered _write cb's as it consumes chunks. If consuming a single
  13597. // written chunk would result in multiple output chunks, then the first
  13598. // outputted bit calls the readcb, and subsequent chunks just go into
  13599. // the read buffer, and will cause it to emit 'readable' if necessary.
  13600. //
  13601. // This way, back-pressure is actually determined by the reading side,
  13602. // since _read has to be called to start processing a new chunk. However,
  13603. // a pathological inflate type of transform can cause excessive buffering
  13604. // here. For example, imagine a stream where every byte of input is
  13605. // interpreted as an integer from 0-255, and then results in that many
  13606. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  13607. // 1kb of data being output. In this case, you could write a very small
  13608. // amount of input, and end up with a very large amount of output. In
  13609. // such a pathological inflating mechanism, there'd be no way to tell
  13610. // the system to stop doing the transform. A single 4MB write could
  13611. // cause the system to run out of memory.
  13612. //
  13613. // However, even in such a pathological case, only a single written chunk
  13614. // would be consumed, and then the rest would wait (un-transformed) until
  13615. // the results of the previous transformed chunk were consumed.
  13616. 'use strict';
  13617. module.exports = Transform;
  13618. var _require$codes = require('../errors').codes,
  13619. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  13620. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  13621. ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
  13622. ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
  13623. var Duplex = require('./_stream_duplex');
  13624. require('inherits')(Transform, Duplex);
  13625. function afterTransform(er, data) {
  13626. var ts = this._transformState;
  13627. ts.transforming = false;
  13628. var cb = ts.writecb;
  13629. if (cb === null) {
  13630. return this.emit('error', new ERR_MULTIPLE_CALLBACK());
  13631. }
  13632. ts.writechunk = null;
  13633. ts.writecb = null;
  13634. if (data != null) // single equals check for both `null` and `undefined`
  13635. this.push(data);
  13636. cb(er);
  13637. var rs = this._readableState;
  13638. rs.reading = false;
  13639. if (rs.needReadable || rs.length < rs.highWaterMark) {
  13640. this._read(rs.highWaterMark);
  13641. }
  13642. }
  13643. function Transform(options) {
  13644. if (!(this instanceof Transform)) return new Transform(options);
  13645. Duplex.call(this, options);
  13646. this._transformState = {
  13647. afterTransform: afterTransform.bind(this),
  13648. needTransform: false,
  13649. transforming: false,
  13650. writecb: null,
  13651. writechunk: null,
  13652. writeencoding: null
  13653. }; // start out asking for a readable event once data is transformed.
  13654. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
  13655. // that Readable wants before the first _read call, so unset the
  13656. // sync guard flag.
  13657. this._readableState.sync = false;
  13658. if (options) {
  13659. if (typeof options.transform === 'function') this._transform = options.transform;
  13660. if (typeof options.flush === 'function') this._flush = options.flush;
  13661. } // When the writable side finishes, then flush out anything remaining.
  13662. this.on('prefinish', prefinish);
  13663. }
  13664. function prefinish() {
  13665. var _this = this;
  13666. if (typeof this._flush === 'function' && !this._readableState.destroyed) {
  13667. this._flush(function (er, data) {
  13668. done(_this, er, data);
  13669. });
  13670. } else {
  13671. done(this, null, null);
  13672. }
  13673. }
  13674. Transform.prototype.push = function (chunk, encoding) {
  13675. this._transformState.needTransform = false;
  13676. return Duplex.prototype.push.call(this, chunk, encoding);
  13677. }; // This is the part where you do stuff!
  13678. // override this function in implementation classes.
  13679. // 'chunk' is an input chunk.
  13680. //
  13681. // Call `push(newChunk)` to pass along transformed output
  13682. // to the readable side. You may call 'push' zero or more times.
  13683. //
  13684. // Call `cb(err)` when you are done with this chunk. If you pass
  13685. // an error, then that'll put the hurt on the whole operation. If you
  13686. // never call cb(), then you'll never get another chunk.
  13687. Transform.prototype._transform = function (chunk, encoding, cb) {
  13688. cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
  13689. };
  13690. Transform.prototype._write = function (chunk, encoding, cb) {
  13691. var ts = this._transformState;
  13692. ts.writecb = cb;
  13693. ts.writechunk = chunk;
  13694. ts.writeencoding = encoding;
  13695. if (!ts.transforming) {
  13696. var rs = this._readableState;
  13697. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  13698. }
  13699. }; // Doesn't matter what the args are here.
  13700. // _transform does all the work.
  13701. // That we got here means that the readable side wants more data.
  13702. Transform.prototype._read = function (n) {
  13703. var ts = this._transformState;
  13704. if (ts.writechunk !== null && !ts.transforming) {
  13705. ts.transforming = true;
  13706. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  13707. } else {
  13708. // mark that we need a transform, so that any data that comes in
  13709. // will get processed, now that we've asked for it.
  13710. ts.needTransform = true;
  13711. }
  13712. };
  13713. Transform.prototype._destroy = function (err, cb) {
  13714. Duplex.prototype._destroy.call(this, err, function (err2) {
  13715. cb(err2);
  13716. });
  13717. };
  13718. function done(stream, er, data) {
  13719. if (er) return stream.emit('error', er);
  13720. if (data != null) // single equals check for both `null` and `undefined`
  13721. stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
  13722. // if there's nothing in the write buffer, then that means
  13723. // that nothing more will ever be provided
  13724. if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
  13725. if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
  13726. return stream.push(null);
  13727. }
  13728. },{"../errors":55,"./_stream_duplex":56,"inherits":24}],60:[function(require,module,exports){
  13729. (function (process,global){(function (){
  13730. // Copyright Joyent, Inc. and other Node contributors.
  13731. //
  13732. // Permission is hereby granted, free of charge, to any person obtaining a
  13733. // copy of this software and associated documentation files (the
  13734. // "Software"), to deal in the Software without restriction, including
  13735. // without limitation the rights to use, copy, modify, merge, publish,
  13736. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13737. // persons to whom the Software is furnished to do so, subject to the
  13738. // following conditions:
  13739. //
  13740. // The above copyright notice and this permission notice shall be included
  13741. // in all copies or substantial portions of the Software.
  13742. //
  13743. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13744. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13745. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13746. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13747. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13748. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13749. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13750. // A bit simpler than readable streams.
  13751. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  13752. // the drain event emission and buffering.
  13753. 'use strict';
  13754. module.exports = Writable;
  13755. /* <replacement> */
  13756. function WriteReq(chunk, encoding, cb) {
  13757. this.chunk = chunk;
  13758. this.encoding = encoding;
  13759. this.callback = cb;
  13760. this.next = null;
  13761. } // It seems a linked list but it is not
  13762. // there will be only 2 of these for each stream
  13763. function CorkedRequest(state) {
  13764. var _this = this;
  13765. this.next = null;
  13766. this.entry = null;
  13767. this.finish = function () {
  13768. onCorkedFinish(_this, state);
  13769. };
  13770. }
  13771. /* </replacement> */
  13772. /*<replacement>*/
  13773. var Duplex;
  13774. /*</replacement>*/
  13775. Writable.WritableState = WritableState;
  13776. /*<replacement>*/
  13777. var internalUtil = {
  13778. deprecate: require('util-deprecate')
  13779. };
  13780. /*</replacement>*/
  13781. /*<replacement>*/
  13782. var Stream = require('./internal/streams/stream');
  13783. /*</replacement>*/
  13784. var Buffer = require('buffer').Buffer;
  13785. var OurUint8Array = global.Uint8Array || function () {};
  13786. function _uint8ArrayToBuffer(chunk) {
  13787. return Buffer.from(chunk);
  13788. }
  13789. function _isUint8Array(obj) {
  13790. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  13791. }
  13792. var destroyImpl = require('./internal/streams/destroy');
  13793. var _require = require('./internal/streams/state'),
  13794. getHighWaterMark = _require.getHighWaterMark;
  13795. var _require$codes = require('../errors').codes,
  13796. ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
  13797. ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
  13798. ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
  13799. ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
  13800. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
  13801. ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
  13802. ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
  13803. ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
  13804. var errorOrDestroy = destroyImpl.errorOrDestroy;
  13805. require('inherits')(Writable, Stream);
  13806. function nop() {}
  13807. function WritableState(options, stream, isDuplex) {
  13808. Duplex = Duplex || require('./_stream_duplex');
  13809. options = options || {}; // Duplex streams are both readable and writable, but share
  13810. // the same options object.
  13811. // However, some cases require setting options to different
  13812. // values for the readable and the writable sides of the duplex stream,
  13813. // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
  13814. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
  13815. // contains buffers or objects.
  13816. this.objectMode = !!options.objectMode;
  13817. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
  13818. // Note: 0 is a valid value, means that we always return false if
  13819. // the entire buffer is not flushed immediately on write()
  13820. this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
  13821. this.finalCalled = false; // drain event flag.
  13822. this.needDrain = false; // at the start of calling end()
  13823. this.ending = false; // when end() has been called, and returned
  13824. this.ended = false; // when 'finish' is emitted
  13825. this.finished = false; // has it been destroyed
  13826. this.destroyed = false; // should we decode strings into buffers before passing to _write?
  13827. // this is here so that some node-core streams can optimize string
  13828. // handling at a lower level.
  13829. var noDecode = options.decodeStrings === false;
  13830. this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
  13831. // encoding is 'binary' so we have to make this configurable.
  13832. // Everything else in the universe uses 'utf8', though.
  13833. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
  13834. // of how much we're waiting to get pushed to some underlying
  13835. // socket or file.
  13836. this.length = 0; // a flag to see when we're in the middle of a write.
  13837. this.writing = false; // when true all writes will be buffered until .uncork() call
  13838. this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
  13839. // or on a later tick. We set this to true at first, because any
  13840. // actions that shouldn't happen until "later" should generally also
  13841. // not happen before the first write call.
  13842. this.sync = true; // a flag to know if we're processing previously buffered items, which
  13843. // may call the _write() callback in the same tick, so that we don't
  13844. // end up in an overlapped onwrite situation.
  13845. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
  13846. this.onwrite = function (er) {
  13847. onwrite(stream, er);
  13848. }; // the callback that the user supplies to write(chunk,encoding,cb)
  13849. this.writecb = null; // the amount that is being written when _write is called.
  13850. this.writelen = 0;
  13851. this.bufferedRequest = null;
  13852. this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
  13853. // this must be 0 before 'finish' can be emitted
  13854. this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
  13855. // This is relevant for synchronous Transform streams
  13856. this.prefinished = false; // True if the error was already emitted and should not be thrown again
  13857. this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
  13858. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
  13859. this.autoDestroy = !!options.autoDestroy; // count buffered requests
  13860. this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
  13861. // one allocated and free to use, and we maintain at most two
  13862. this.corkedRequestsFree = new CorkedRequest(this);
  13863. }
  13864. WritableState.prototype.getBuffer = function getBuffer() {
  13865. var current = this.bufferedRequest;
  13866. var out = [];
  13867. while (current) {
  13868. out.push(current);
  13869. current = current.next;
  13870. }
  13871. return out;
  13872. };
  13873. (function () {
  13874. try {
  13875. Object.defineProperty(WritableState.prototype, 'buffer', {
  13876. get: internalUtil.deprecate(function writableStateBufferGetter() {
  13877. return this.getBuffer();
  13878. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  13879. });
  13880. } catch (_) {}
  13881. })(); // Test _writableState for inheritance to account for Duplex streams,
  13882. // whose prototype chain only points to Readable.
  13883. var realHasInstance;
  13884. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  13885. realHasInstance = Function.prototype[Symbol.hasInstance];
  13886. Object.defineProperty(Writable, Symbol.hasInstance, {
  13887. value: function value(object) {
  13888. if (realHasInstance.call(this, object)) return true;
  13889. if (this !== Writable) return false;
  13890. return object && object._writableState instanceof WritableState;
  13891. }
  13892. });
  13893. } else {
  13894. realHasInstance = function realHasInstance(object) {
  13895. return object instanceof this;
  13896. };
  13897. }
  13898. function Writable(options) {
  13899. Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
  13900. // `realHasInstance` is necessary because using plain `instanceof`
  13901. // would return false, as no `_writableState` property is attached.
  13902. // Trying to use the custom `instanceof` for Writable here will also break the
  13903. // Node.js LazyTransform implementation, which has a non-trivial getter for
  13904. // `_writableState` that would lead to infinite recursion.
  13905. // Checking for a Stream.Duplex instance is faster here instead of inside
  13906. // the WritableState constructor, at least with V8 6.5
  13907. var isDuplex = this instanceof Duplex;
  13908. if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
  13909. this._writableState = new WritableState(options, this, isDuplex); // legacy.
  13910. this.writable = true;
  13911. if (options) {
  13912. if (typeof options.write === 'function') this._write = options.write;
  13913. if (typeof options.writev === 'function') this._writev = options.writev;
  13914. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  13915. if (typeof options.final === 'function') this._final = options.final;
  13916. }
  13917. Stream.call(this);
  13918. } // Otherwise people can pipe Writable streams, which is just wrong.
  13919. Writable.prototype.pipe = function () {
  13920. errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
  13921. };
  13922. function writeAfterEnd(stream, cb) {
  13923. var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
  13924. errorOrDestroy(stream, er);
  13925. process.nextTick(cb, er);
  13926. } // Checks that a user-supplied chunk is valid, especially for the particular
  13927. // mode the stream is in. Currently this means that `null` is never accepted
  13928. // and undefined/non-string values are only allowed in object mode.
  13929. function validChunk(stream, state, chunk, cb) {
  13930. var er;
  13931. if (chunk === null) {
  13932. er = new ERR_STREAM_NULL_VALUES();
  13933. } else if (typeof chunk !== 'string' && !state.objectMode) {
  13934. er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
  13935. }
  13936. if (er) {
  13937. errorOrDestroy(stream, er);
  13938. process.nextTick(cb, er);
  13939. return false;
  13940. }
  13941. return true;
  13942. }
  13943. Writable.prototype.write = function (chunk, encoding, cb) {
  13944. var state = this._writableState;
  13945. var ret = false;
  13946. var isBuf = !state.objectMode && _isUint8Array(chunk);
  13947. if (isBuf && !Buffer.isBuffer(chunk)) {
  13948. chunk = _uint8ArrayToBuffer(chunk);
  13949. }
  13950. if (typeof encoding === 'function') {
  13951. cb = encoding;
  13952. encoding = null;
  13953. }
  13954. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  13955. if (typeof cb !== 'function') cb = nop;
  13956. if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  13957. state.pendingcb++;
  13958. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  13959. }
  13960. return ret;
  13961. };
  13962. Writable.prototype.cork = function () {
  13963. this._writableState.corked++;
  13964. };
  13965. Writable.prototype.uncork = function () {
  13966. var state = this._writableState;
  13967. if (state.corked) {
  13968. state.corked--;
  13969. if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  13970. }
  13971. };
  13972. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  13973. // node::ParseEncoding() requires lower case.
  13974. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  13975. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
  13976. this._writableState.defaultEncoding = encoding;
  13977. return this;
  13978. };
  13979. Object.defineProperty(Writable.prototype, 'writableBuffer', {
  13980. // making it explicit this property is not enumerable
  13981. // because otherwise some prototype manipulation in
  13982. // userland will fail
  13983. enumerable: false,
  13984. get: function get() {
  13985. return this._writableState && this._writableState.getBuffer();
  13986. }
  13987. });
  13988. function decodeChunk(state, chunk, encoding) {
  13989. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  13990. chunk = Buffer.from(chunk, encoding);
  13991. }
  13992. return chunk;
  13993. }
  13994. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  13995. // making it explicit this property is not enumerable
  13996. // because otherwise some prototype manipulation in
  13997. // userland will fail
  13998. enumerable: false,
  13999. get: function get() {
  14000. return this._writableState.highWaterMark;
  14001. }
  14002. }); // if we're already writing something, then just put this
  14003. // in the queue, and wait our turn. Otherwise, call _write
  14004. // If we return false, then we need a drain event, so set that flag.
  14005. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  14006. if (!isBuf) {
  14007. var newChunk = decodeChunk(state, chunk, encoding);
  14008. if (chunk !== newChunk) {
  14009. isBuf = true;
  14010. encoding = 'buffer';
  14011. chunk = newChunk;
  14012. }
  14013. }
  14014. var len = state.objectMode ? 1 : chunk.length;
  14015. state.length += len;
  14016. var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
  14017. if (!ret) state.needDrain = true;
  14018. if (state.writing || state.corked) {
  14019. var last = state.lastBufferedRequest;
  14020. state.lastBufferedRequest = {
  14021. chunk: chunk,
  14022. encoding: encoding,
  14023. isBuf: isBuf,
  14024. callback: cb,
  14025. next: null
  14026. };
  14027. if (last) {
  14028. last.next = state.lastBufferedRequest;
  14029. } else {
  14030. state.bufferedRequest = state.lastBufferedRequest;
  14031. }
  14032. state.bufferedRequestCount += 1;
  14033. } else {
  14034. doWrite(stream, state, false, len, chunk, encoding, cb);
  14035. }
  14036. return ret;
  14037. }
  14038. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  14039. state.writelen = len;
  14040. state.writecb = cb;
  14041. state.writing = true;
  14042. state.sync = true;
  14043. if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  14044. state.sync = false;
  14045. }
  14046. function onwriteError(stream, state, sync, er, cb) {
  14047. --state.pendingcb;
  14048. if (sync) {
  14049. // defer the callback if we are being called synchronously
  14050. // to avoid piling up things on the stack
  14051. process.nextTick(cb, er); // this can emit finish, and it will always happen
  14052. // after error
  14053. process.nextTick(finishMaybe, stream, state);
  14054. stream._writableState.errorEmitted = true;
  14055. errorOrDestroy(stream, er);
  14056. } else {
  14057. // the caller expect this to happen before if
  14058. // it is async
  14059. cb(er);
  14060. stream._writableState.errorEmitted = true;
  14061. errorOrDestroy(stream, er); // this can emit finish, but finish must
  14062. // always follow error
  14063. finishMaybe(stream, state);
  14064. }
  14065. }
  14066. function onwriteStateUpdate(state) {
  14067. state.writing = false;
  14068. state.writecb = null;
  14069. state.length -= state.writelen;
  14070. state.writelen = 0;
  14071. }
  14072. function onwrite(stream, er) {
  14073. var state = stream._writableState;
  14074. var sync = state.sync;
  14075. var cb = state.writecb;
  14076. if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
  14077. onwriteStateUpdate(state);
  14078. if (er) onwriteError(stream, state, sync, er, cb);else {
  14079. // Check if we're actually ready to finish, but don't emit yet
  14080. var finished = needFinish(state) || stream.destroyed;
  14081. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  14082. clearBuffer(stream, state);
  14083. }
  14084. if (sync) {
  14085. process.nextTick(afterWrite, stream, state, finished, cb);
  14086. } else {
  14087. afterWrite(stream, state, finished, cb);
  14088. }
  14089. }
  14090. }
  14091. function afterWrite(stream, state, finished, cb) {
  14092. if (!finished) onwriteDrain(stream, state);
  14093. state.pendingcb--;
  14094. cb();
  14095. finishMaybe(stream, state);
  14096. } // Must force callback to be called on nextTick, so that we don't
  14097. // emit 'drain' before the write() consumer gets the 'false' return
  14098. // value, and has a chance to attach a 'drain' listener.
  14099. function onwriteDrain(stream, state) {
  14100. if (state.length === 0 && state.needDrain) {
  14101. state.needDrain = false;
  14102. stream.emit('drain');
  14103. }
  14104. } // if there's something in the buffer waiting, then process it
  14105. function clearBuffer(stream, state) {
  14106. state.bufferProcessing = true;
  14107. var entry = state.bufferedRequest;
  14108. if (stream._writev && entry && entry.next) {
  14109. // Fast case, write everything using _writev()
  14110. var l = state.bufferedRequestCount;
  14111. var buffer = new Array(l);
  14112. var holder = state.corkedRequestsFree;
  14113. holder.entry = entry;
  14114. var count = 0;
  14115. var allBuffers = true;
  14116. while (entry) {
  14117. buffer[count] = entry;
  14118. if (!entry.isBuf) allBuffers = false;
  14119. entry = entry.next;
  14120. count += 1;
  14121. }
  14122. buffer.allBuffers = allBuffers;
  14123. doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
  14124. // as the hot path ends with doWrite
  14125. state.pendingcb++;
  14126. state.lastBufferedRequest = null;
  14127. if (holder.next) {
  14128. state.corkedRequestsFree = holder.next;
  14129. holder.next = null;
  14130. } else {
  14131. state.corkedRequestsFree = new CorkedRequest(state);
  14132. }
  14133. state.bufferedRequestCount = 0;
  14134. } else {
  14135. // Slow case, write chunks one-by-one
  14136. while (entry) {
  14137. var chunk = entry.chunk;
  14138. var encoding = entry.encoding;
  14139. var cb = entry.callback;
  14140. var len = state.objectMode ? 1 : chunk.length;
  14141. doWrite(stream, state, false, len, chunk, encoding, cb);
  14142. entry = entry.next;
  14143. state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
  14144. // it means that we need to wait until it does.
  14145. // also, that means that the chunk and cb are currently
  14146. // being processed, so move the buffer counter past them.
  14147. if (state.writing) {
  14148. break;
  14149. }
  14150. }
  14151. if (entry === null) state.lastBufferedRequest = null;
  14152. }
  14153. state.bufferedRequest = entry;
  14154. state.bufferProcessing = false;
  14155. }
  14156. Writable.prototype._write = function (chunk, encoding, cb) {
  14157. cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
  14158. };
  14159. Writable.prototype._writev = null;
  14160. Writable.prototype.end = function (chunk, encoding, cb) {
  14161. var state = this._writableState;
  14162. if (typeof chunk === 'function') {
  14163. cb = chunk;
  14164. chunk = null;
  14165. encoding = null;
  14166. } else if (typeof encoding === 'function') {
  14167. cb = encoding;
  14168. encoding = null;
  14169. }
  14170. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
  14171. if (state.corked) {
  14172. state.corked = 1;
  14173. this.uncork();
  14174. } // ignore unnecessary end() calls.
  14175. if (!state.ending) endWritable(this, state, cb);
  14176. return this;
  14177. };
  14178. Object.defineProperty(Writable.prototype, 'writableLength', {
  14179. // making it explicit this property is not enumerable
  14180. // because otherwise some prototype manipulation in
  14181. // userland will fail
  14182. enumerable: false,
  14183. get: function get() {
  14184. return this._writableState.length;
  14185. }
  14186. });
  14187. function needFinish(state) {
  14188. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  14189. }
  14190. function callFinal(stream, state) {
  14191. stream._final(function (err) {
  14192. state.pendingcb--;
  14193. if (err) {
  14194. errorOrDestroy(stream, err);
  14195. }
  14196. state.prefinished = true;
  14197. stream.emit('prefinish');
  14198. finishMaybe(stream, state);
  14199. });
  14200. }
  14201. function prefinish(stream, state) {
  14202. if (!state.prefinished && !state.finalCalled) {
  14203. if (typeof stream._final === 'function' && !state.destroyed) {
  14204. state.pendingcb++;
  14205. state.finalCalled = true;
  14206. process.nextTick(callFinal, stream, state);
  14207. } else {
  14208. state.prefinished = true;
  14209. stream.emit('prefinish');
  14210. }
  14211. }
  14212. }
  14213. function finishMaybe(stream, state) {
  14214. var need = needFinish(state);
  14215. if (need) {
  14216. prefinish(stream, state);
  14217. if (state.pendingcb === 0) {
  14218. state.finished = true;
  14219. stream.emit('finish');
  14220. if (state.autoDestroy) {
  14221. // In case of duplex streams we need a way to detect
  14222. // if the readable side is ready for autoDestroy as well
  14223. var rState = stream._readableState;
  14224. if (!rState || rState.autoDestroy && rState.endEmitted) {
  14225. stream.destroy();
  14226. }
  14227. }
  14228. }
  14229. }
  14230. return need;
  14231. }
  14232. function endWritable(stream, state, cb) {
  14233. state.ending = true;
  14234. finishMaybe(stream, state);
  14235. if (cb) {
  14236. if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
  14237. }
  14238. state.ended = true;
  14239. stream.writable = false;
  14240. }
  14241. function onCorkedFinish(corkReq, state, err) {
  14242. var entry = corkReq.entry;
  14243. corkReq.entry = null;
  14244. while (entry) {
  14245. var cb = entry.callback;
  14246. state.pendingcb--;
  14247. cb(err);
  14248. entry = entry.next;
  14249. } // reuse the free corkReq.
  14250. state.corkedRequestsFree.next = corkReq;
  14251. }
  14252. Object.defineProperty(Writable.prototype, 'destroyed', {
  14253. // making it explicit this property is not enumerable
  14254. // because otherwise some prototype manipulation in
  14255. // userland will fail
  14256. enumerable: false,
  14257. get: function get() {
  14258. if (this._writableState === undefined) {
  14259. return false;
  14260. }
  14261. return this._writableState.destroyed;
  14262. },
  14263. set: function set(value) {
  14264. // we ignore the value if the stream
  14265. // has not been initialized yet
  14266. if (!this._writableState) {
  14267. return;
  14268. } // backward compatibility, the user is explicitly
  14269. // managing destroyed
  14270. this._writableState.destroyed = value;
  14271. }
  14272. });
  14273. Writable.prototype.destroy = destroyImpl.destroy;
  14274. Writable.prototype._undestroy = destroyImpl.undestroy;
  14275. Writable.prototype._destroy = function (err, cb) {
  14276. cb(err);
  14277. };
  14278. }).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14279. },{"../errors":55,"./_stream_duplex":56,"./internal/streams/destroy":63,"./internal/streams/state":67,"./internal/streams/stream":68,"_process":50,"buffer":17,"inherits":24,"util-deprecate":78}],61:[function(require,module,exports){
  14280. (function (process){(function (){
  14281. 'use strict';
  14282. var _Object$setPrototypeO;
  14283. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  14284. var finished = require('./end-of-stream');
  14285. var kLastResolve = Symbol('lastResolve');
  14286. var kLastReject = Symbol('lastReject');
  14287. var kError = Symbol('error');
  14288. var kEnded = Symbol('ended');
  14289. var kLastPromise = Symbol('lastPromise');
  14290. var kHandlePromise = Symbol('handlePromise');
  14291. var kStream = Symbol('stream');
  14292. function createIterResult(value, done) {
  14293. return {
  14294. value: value,
  14295. done: done
  14296. };
  14297. }
  14298. function readAndResolve(iter) {
  14299. var resolve = iter[kLastResolve];
  14300. if (resolve !== null) {
  14301. var data = iter[kStream].read(); // we defer if data is null
  14302. // we can be expecting either 'end' or
  14303. // 'error'
  14304. if (data !== null) {
  14305. iter[kLastPromise] = null;
  14306. iter[kLastResolve] = null;
  14307. iter[kLastReject] = null;
  14308. resolve(createIterResult(data, false));
  14309. }
  14310. }
  14311. }
  14312. function onReadable(iter) {
  14313. // we wait for the next tick, because it might
  14314. // emit an error with process.nextTick
  14315. process.nextTick(readAndResolve, iter);
  14316. }
  14317. function wrapForNext(lastPromise, iter) {
  14318. return function (resolve, reject) {
  14319. lastPromise.then(function () {
  14320. if (iter[kEnded]) {
  14321. resolve(createIterResult(undefined, true));
  14322. return;
  14323. }
  14324. iter[kHandlePromise](resolve, reject);
  14325. }, reject);
  14326. };
  14327. }
  14328. var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
  14329. var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
  14330. get stream() {
  14331. return this[kStream];
  14332. },
  14333. next: function next() {
  14334. var _this = this;
  14335. // if we have detected an error in the meanwhile
  14336. // reject straight away
  14337. var error = this[kError];
  14338. if (error !== null) {
  14339. return Promise.reject(error);
  14340. }
  14341. if (this[kEnded]) {
  14342. return Promise.resolve(createIterResult(undefined, true));
  14343. }
  14344. if (this[kStream].destroyed) {
  14345. // We need to defer via nextTick because if .destroy(err) is
  14346. // called, the error will be emitted via nextTick, and
  14347. // we cannot guarantee that there is no error lingering around
  14348. // waiting to be emitted.
  14349. return new Promise(function (resolve, reject) {
  14350. process.nextTick(function () {
  14351. if (_this[kError]) {
  14352. reject(_this[kError]);
  14353. } else {
  14354. resolve(createIterResult(undefined, true));
  14355. }
  14356. });
  14357. });
  14358. } // if we have multiple next() calls
  14359. // we will wait for the previous Promise to finish
  14360. // this logic is optimized to support for await loops,
  14361. // where next() is only called once at a time
  14362. var lastPromise = this[kLastPromise];
  14363. var promise;
  14364. if (lastPromise) {
  14365. promise = new Promise(wrapForNext(lastPromise, this));
  14366. } else {
  14367. // fast path needed to support multiple this.push()
  14368. // without triggering the next() queue
  14369. var data = this[kStream].read();
  14370. if (data !== null) {
  14371. return Promise.resolve(createIterResult(data, false));
  14372. }
  14373. promise = new Promise(this[kHandlePromise]);
  14374. }
  14375. this[kLastPromise] = promise;
  14376. return promise;
  14377. }
  14378. }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
  14379. return this;
  14380. }), _defineProperty(_Object$setPrototypeO, "return", function _return() {
  14381. var _this2 = this;
  14382. // destroy(err, cb) is a private API
  14383. // we can guarantee we have that here, because we control the
  14384. // Readable class this is attached to
  14385. return new Promise(function (resolve, reject) {
  14386. _this2[kStream].destroy(null, function (err) {
  14387. if (err) {
  14388. reject(err);
  14389. return;
  14390. }
  14391. resolve(createIterResult(undefined, true));
  14392. });
  14393. });
  14394. }), _Object$setPrototypeO), AsyncIteratorPrototype);
  14395. var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
  14396. var _Object$create;
  14397. var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
  14398. value: stream,
  14399. writable: true
  14400. }), _defineProperty(_Object$create, kLastResolve, {
  14401. value: null,
  14402. writable: true
  14403. }), _defineProperty(_Object$create, kLastReject, {
  14404. value: null,
  14405. writable: true
  14406. }), _defineProperty(_Object$create, kError, {
  14407. value: null,
  14408. writable: true
  14409. }), _defineProperty(_Object$create, kEnded, {
  14410. value: stream._readableState.endEmitted,
  14411. writable: true
  14412. }), _defineProperty(_Object$create, kHandlePromise, {
  14413. value: function value(resolve, reject) {
  14414. var data = iterator[kStream].read();
  14415. if (data) {
  14416. iterator[kLastPromise] = null;
  14417. iterator[kLastResolve] = null;
  14418. iterator[kLastReject] = null;
  14419. resolve(createIterResult(data, false));
  14420. } else {
  14421. iterator[kLastResolve] = resolve;
  14422. iterator[kLastReject] = reject;
  14423. }
  14424. },
  14425. writable: true
  14426. }), _Object$create));
  14427. iterator[kLastPromise] = null;
  14428. finished(stream, function (err) {
  14429. if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
  14430. var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
  14431. // returned by next() and store the error
  14432. if (reject !== null) {
  14433. iterator[kLastPromise] = null;
  14434. iterator[kLastResolve] = null;
  14435. iterator[kLastReject] = null;
  14436. reject(err);
  14437. }
  14438. iterator[kError] = err;
  14439. return;
  14440. }
  14441. var resolve = iterator[kLastResolve];
  14442. if (resolve !== null) {
  14443. iterator[kLastPromise] = null;
  14444. iterator[kLastResolve] = null;
  14445. iterator[kLastReject] = null;
  14446. resolve(createIterResult(undefined, true));
  14447. }
  14448. iterator[kEnded] = true;
  14449. });
  14450. stream.on('readable', onReadable.bind(null, iterator));
  14451. return iterator;
  14452. };
  14453. module.exports = createReadableStreamAsyncIterator;
  14454. }).call(this)}).call(this,require('_process'))
  14455. },{"./end-of-stream":64,"_process":50}],62:[function(require,module,exports){
  14456. 'use strict';
  14457. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
  14458. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
  14459. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  14460. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  14461. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  14462. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  14463. var _require = require('buffer'),
  14464. Buffer = _require.Buffer;
  14465. var _require2 = require('util'),
  14466. inspect = _require2.inspect;
  14467. var custom = inspect && inspect.custom || 'inspect';
  14468. function copyBuffer(src, target, offset) {
  14469. Buffer.prototype.copy.call(src, target, offset);
  14470. }
  14471. module.exports =
  14472. /*#__PURE__*/
  14473. function () {
  14474. function BufferList() {
  14475. _classCallCheck(this, BufferList);
  14476. this.head = null;
  14477. this.tail = null;
  14478. this.length = 0;
  14479. }
  14480. _createClass(BufferList, [{
  14481. key: "push",
  14482. value: function push(v) {
  14483. var entry = {
  14484. data: v,
  14485. next: null
  14486. };
  14487. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  14488. this.tail = entry;
  14489. ++this.length;
  14490. }
  14491. }, {
  14492. key: "unshift",
  14493. value: function unshift(v) {
  14494. var entry = {
  14495. data: v,
  14496. next: this.head
  14497. };
  14498. if (this.length === 0) this.tail = entry;
  14499. this.head = entry;
  14500. ++this.length;
  14501. }
  14502. }, {
  14503. key: "shift",
  14504. value: function shift() {
  14505. if (this.length === 0) return;
  14506. var ret = this.head.data;
  14507. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  14508. --this.length;
  14509. return ret;
  14510. }
  14511. }, {
  14512. key: "clear",
  14513. value: function clear() {
  14514. this.head = this.tail = null;
  14515. this.length = 0;
  14516. }
  14517. }, {
  14518. key: "join",
  14519. value: function join(s) {
  14520. if (this.length === 0) return '';
  14521. var p = this.head;
  14522. var ret = '' + p.data;
  14523. while (p = p.next) {
  14524. ret += s + p.data;
  14525. }
  14526. return ret;
  14527. }
  14528. }, {
  14529. key: "concat",
  14530. value: function concat(n) {
  14531. if (this.length === 0) return Buffer.alloc(0);
  14532. var ret = Buffer.allocUnsafe(n >>> 0);
  14533. var p = this.head;
  14534. var i = 0;
  14535. while (p) {
  14536. copyBuffer(p.data, ret, i);
  14537. i += p.data.length;
  14538. p = p.next;
  14539. }
  14540. return ret;
  14541. } // Consumes a specified amount of bytes or characters from the buffered data.
  14542. }, {
  14543. key: "consume",
  14544. value: function consume(n, hasStrings) {
  14545. var ret;
  14546. if (n < this.head.data.length) {
  14547. // `slice` is the same for buffers and strings.
  14548. ret = this.head.data.slice(0, n);
  14549. this.head.data = this.head.data.slice(n);
  14550. } else if (n === this.head.data.length) {
  14551. // First chunk is a perfect match.
  14552. ret = this.shift();
  14553. } else {
  14554. // Result spans more than one buffer.
  14555. ret = hasStrings ? this._getString(n) : this._getBuffer(n);
  14556. }
  14557. return ret;
  14558. }
  14559. }, {
  14560. key: "first",
  14561. value: function first() {
  14562. return this.head.data;
  14563. } // Consumes a specified amount of characters from the buffered data.
  14564. }, {
  14565. key: "_getString",
  14566. value: function _getString(n) {
  14567. var p = this.head;
  14568. var c = 1;
  14569. var ret = p.data;
  14570. n -= ret.length;
  14571. while (p = p.next) {
  14572. var str = p.data;
  14573. var nb = n > str.length ? str.length : n;
  14574. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  14575. n -= nb;
  14576. if (n === 0) {
  14577. if (nb === str.length) {
  14578. ++c;
  14579. if (p.next) this.head = p.next;else this.head = this.tail = null;
  14580. } else {
  14581. this.head = p;
  14582. p.data = str.slice(nb);
  14583. }
  14584. break;
  14585. }
  14586. ++c;
  14587. }
  14588. this.length -= c;
  14589. return ret;
  14590. } // Consumes a specified amount of bytes from the buffered data.
  14591. }, {
  14592. key: "_getBuffer",
  14593. value: function _getBuffer(n) {
  14594. var ret = Buffer.allocUnsafe(n);
  14595. var p = this.head;
  14596. var c = 1;
  14597. p.data.copy(ret);
  14598. n -= p.data.length;
  14599. while (p = p.next) {
  14600. var buf = p.data;
  14601. var nb = n > buf.length ? buf.length : n;
  14602. buf.copy(ret, ret.length - n, 0, nb);
  14603. n -= nb;
  14604. if (n === 0) {
  14605. if (nb === buf.length) {
  14606. ++c;
  14607. if (p.next) this.head = p.next;else this.head = this.tail = null;
  14608. } else {
  14609. this.head = p;
  14610. p.data = buf.slice(nb);
  14611. }
  14612. break;
  14613. }
  14614. ++c;
  14615. }
  14616. this.length -= c;
  14617. return ret;
  14618. } // Make sure the linked list only shows the minimal necessary information.
  14619. }, {
  14620. key: custom,
  14621. value: function value(_, options) {
  14622. return inspect(this, _objectSpread({}, options, {
  14623. // Only inspect one level.
  14624. depth: 0,
  14625. // It should not recurse.
  14626. customInspect: false
  14627. }));
  14628. }
  14629. }]);
  14630. return BufferList;
  14631. }();
  14632. },{"buffer":17,"util":16}],63:[function(require,module,exports){
  14633. (function (process){(function (){
  14634. 'use strict'; // undocumented cb() API, needed for core, not for public API
  14635. function destroy(err, cb) {
  14636. var _this = this;
  14637. var readableDestroyed = this._readableState && this._readableState.destroyed;
  14638. var writableDestroyed = this._writableState && this._writableState.destroyed;
  14639. if (readableDestroyed || writableDestroyed) {
  14640. if (cb) {
  14641. cb(err);
  14642. } else if (err) {
  14643. if (!this._writableState) {
  14644. process.nextTick(emitErrorNT, this, err);
  14645. } else if (!this._writableState.errorEmitted) {
  14646. this._writableState.errorEmitted = true;
  14647. process.nextTick(emitErrorNT, this, err);
  14648. }
  14649. }
  14650. return this;
  14651. } // we set destroyed to true before firing error callbacks in order
  14652. // to make it re-entrance safe in case destroy() is called within callbacks
  14653. if (this._readableState) {
  14654. this._readableState.destroyed = true;
  14655. } // if this is a duplex stream mark the writable part as destroyed as well
  14656. if (this._writableState) {
  14657. this._writableState.destroyed = true;
  14658. }
  14659. this._destroy(err || null, function (err) {
  14660. if (!cb && err) {
  14661. if (!_this._writableState) {
  14662. process.nextTick(emitErrorAndCloseNT, _this, err);
  14663. } else if (!_this._writableState.errorEmitted) {
  14664. _this._writableState.errorEmitted = true;
  14665. process.nextTick(emitErrorAndCloseNT, _this, err);
  14666. } else {
  14667. process.nextTick(emitCloseNT, _this);
  14668. }
  14669. } else if (cb) {
  14670. process.nextTick(emitCloseNT, _this);
  14671. cb(err);
  14672. } else {
  14673. process.nextTick(emitCloseNT, _this);
  14674. }
  14675. });
  14676. return this;
  14677. }
  14678. function emitErrorAndCloseNT(self, err) {
  14679. emitErrorNT(self, err);
  14680. emitCloseNT(self);
  14681. }
  14682. function emitCloseNT(self) {
  14683. if (self._writableState && !self._writableState.emitClose) return;
  14684. if (self._readableState && !self._readableState.emitClose) return;
  14685. self.emit('close');
  14686. }
  14687. function undestroy() {
  14688. if (this._readableState) {
  14689. this._readableState.destroyed = false;
  14690. this._readableState.reading = false;
  14691. this._readableState.ended = false;
  14692. this._readableState.endEmitted = false;
  14693. }
  14694. if (this._writableState) {
  14695. this._writableState.destroyed = false;
  14696. this._writableState.ended = false;
  14697. this._writableState.ending = false;
  14698. this._writableState.finalCalled = false;
  14699. this._writableState.prefinished = false;
  14700. this._writableState.finished = false;
  14701. this._writableState.errorEmitted = false;
  14702. }
  14703. }
  14704. function emitErrorNT(self, err) {
  14705. self.emit('error', err);
  14706. }
  14707. function errorOrDestroy(stream, err) {
  14708. // We have tests that rely on errors being emitted
  14709. // in the same tick, so changing this is semver major.
  14710. // For now when you opt-in to autoDestroy we allow
  14711. // the error to be emitted nextTick. In a future
  14712. // semver major update we should change the default to this.
  14713. var rState = stream._readableState;
  14714. var wState = stream._writableState;
  14715. if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
  14716. }
  14717. module.exports = {
  14718. destroy: destroy,
  14719. undestroy: undestroy,
  14720. errorOrDestroy: errorOrDestroy
  14721. };
  14722. }).call(this)}).call(this,require('_process'))
  14723. },{"_process":50}],64:[function(require,module,exports){
  14724. // Ported from https://github.com/mafintosh/end-of-stream with
  14725. // permission from the author, Mathias Buus (@mafintosh).
  14726. 'use strict';
  14727. var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
  14728. function once(callback) {
  14729. var called = false;
  14730. return function () {
  14731. if (called) return;
  14732. called = true;
  14733. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  14734. args[_key] = arguments[_key];
  14735. }
  14736. callback.apply(this, args);
  14737. };
  14738. }
  14739. function noop() {}
  14740. function isRequest(stream) {
  14741. return stream.setHeader && typeof stream.abort === 'function';
  14742. }
  14743. function eos(stream, opts, callback) {
  14744. if (typeof opts === 'function') return eos(stream, null, opts);
  14745. if (!opts) opts = {};
  14746. callback = once(callback || noop);
  14747. var readable = opts.readable || opts.readable !== false && stream.readable;
  14748. var writable = opts.writable || opts.writable !== false && stream.writable;
  14749. var onlegacyfinish = function onlegacyfinish() {
  14750. if (!stream.writable) onfinish();
  14751. };
  14752. var writableEnded = stream._writableState && stream._writableState.finished;
  14753. var onfinish = function onfinish() {
  14754. writable = false;
  14755. writableEnded = true;
  14756. if (!readable) callback.call(stream);
  14757. };
  14758. var readableEnded = stream._readableState && stream._readableState.endEmitted;
  14759. var onend = function onend() {
  14760. readable = false;
  14761. readableEnded = true;
  14762. if (!writable) callback.call(stream);
  14763. };
  14764. var onerror = function onerror(err) {
  14765. callback.call(stream, err);
  14766. };
  14767. var onclose = function onclose() {
  14768. var err;
  14769. if (readable && !readableEnded) {
  14770. if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  14771. return callback.call(stream, err);
  14772. }
  14773. if (writable && !writableEnded) {
  14774. if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
  14775. return callback.call(stream, err);
  14776. }
  14777. };
  14778. var onrequest = function onrequest() {
  14779. stream.req.on('finish', onfinish);
  14780. };
  14781. if (isRequest(stream)) {
  14782. stream.on('complete', onfinish);
  14783. stream.on('abort', onclose);
  14784. if (stream.req) onrequest();else stream.on('request', onrequest);
  14785. } else if (writable && !stream._writableState) {
  14786. // legacy streams
  14787. stream.on('end', onlegacyfinish);
  14788. stream.on('close', onlegacyfinish);
  14789. }
  14790. stream.on('end', onend);
  14791. stream.on('finish', onfinish);
  14792. if (opts.error !== false) stream.on('error', onerror);
  14793. stream.on('close', onclose);
  14794. return function () {
  14795. stream.removeListener('complete', onfinish);
  14796. stream.removeListener('abort', onclose);
  14797. stream.removeListener('request', onrequest);
  14798. if (stream.req) stream.req.removeListener('finish', onfinish);
  14799. stream.removeListener('end', onlegacyfinish);
  14800. stream.removeListener('close', onlegacyfinish);
  14801. stream.removeListener('finish', onfinish);
  14802. stream.removeListener('end', onend);
  14803. stream.removeListener('error', onerror);
  14804. stream.removeListener('close', onclose);
  14805. };
  14806. }
  14807. module.exports = eos;
  14808. },{"../../../errors":55}],65:[function(require,module,exports){
  14809. module.exports = function () {
  14810. throw new Error('Readable.from is not available in the browser')
  14811. };
  14812. },{}],66:[function(require,module,exports){
  14813. // Ported from https://github.com/mafintosh/pump with
  14814. // permission from the author, Mathias Buus (@mafintosh).
  14815. 'use strict';
  14816. var eos;
  14817. function once(callback) {
  14818. var called = false;
  14819. return function () {
  14820. if (called) return;
  14821. called = true;
  14822. callback.apply(void 0, arguments);
  14823. };
  14824. }
  14825. var _require$codes = require('../../../errors').codes,
  14826. ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
  14827. ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
  14828. function noop(err) {
  14829. // Rethrow the error if it exists to avoid swallowing it
  14830. if (err) throw err;
  14831. }
  14832. function isRequest(stream) {
  14833. return stream.setHeader && typeof stream.abort === 'function';
  14834. }
  14835. function destroyer(stream, reading, writing, callback) {
  14836. callback = once(callback);
  14837. var closed = false;
  14838. stream.on('close', function () {
  14839. closed = true;
  14840. });
  14841. if (eos === undefined) eos = require('./end-of-stream');
  14842. eos(stream, {
  14843. readable: reading,
  14844. writable: writing
  14845. }, function (err) {
  14846. if (err) return callback(err);
  14847. closed = true;
  14848. callback();
  14849. });
  14850. var destroyed = false;
  14851. return function (err) {
  14852. if (closed) return;
  14853. if (destroyed) return;
  14854. destroyed = true; // request.destroy just do .end - .abort is what we want
  14855. if (isRequest(stream)) return stream.abort();
  14856. if (typeof stream.destroy === 'function') return stream.destroy();
  14857. callback(err || new ERR_STREAM_DESTROYED('pipe'));
  14858. };
  14859. }
  14860. function call(fn) {
  14861. fn();
  14862. }
  14863. function pipe(from, to) {
  14864. return from.pipe(to);
  14865. }
  14866. function popCallback(streams) {
  14867. if (!streams.length) return noop;
  14868. if (typeof streams[streams.length - 1] !== 'function') return noop;
  14869. return streams.pop();
  14870. }
  14871. function pipeline() {
  14872. for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
  14873. streams[_key] = arguments[_key];
  14874. }
  14875. var callback = popCallback(streams);
  14876. if (Array.isArray(streams[0])) streams = streams[0];
  14877. if (streams.length < 2) {
  14878. throw new ERR_MISSING_ARGS('streams');
  14879. }
  14880. var error;
  14881. var destroys = streams.map(function (stream, i) {
  14882. var reading = i < streams.length - 1;
  14883. var writing = i > 0;
  14884. return destroyer(stream, reading, writing, function (err) {
  14885. if (!error) error = err;
  14886. if (err) destroys.forEach(call);
  14887. if (reading) return;
  14888. destroys.forEach(call);
  14889. callback(error);
  14890. });
  14891. });
  14892. return streams.reduce(pipe);
  14893. }
  14894. module.exports = pipeline;
  14895. },{"../../../errors":55,"./end-of-stream":64}],67:[function(require,module,exports){
  14896. 'use strict';
  14897. var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
  14898. function highWaterMarkFrom(options, isDuplex, duplexKey) {
  14899. return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
  14900. }
  14901. function getHighWaterMark(state, options, duplexKey, isDuplex) {
  14902. var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
  14903. if (hwm != null) {
  14904. if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
  14905. var name = isDuplex ? duplexKey : 'highWaterMark';
  14906. throw new ERR_INVALID_OPT_VALUE(name, hwm);
  14907. }
  14908. return Math.floor(hwm);
  14909. } // Default value
  14910. return state.objectMode ? 16 : 16 * 1024;
  14911. }
  14912. module.exports = {
  14913. getHighWaterMark: getHighWaterMark
  14914. };
  14915. },{"../../../errors":55}],68:[function(require,module,exports){
  14916. module.exports = require('events').EventEmitter;
  14917. },{"events":22}],69:[function(require,module,exports){
  14918. exports = module.exports = require('./lib/_stream_readable.js');
  14919. exports.Stream = exports;
  14920. exports.Readable = exports;
  14921. exports.Writable = require('./lib/_stream_writable.js');
  14922. exports.Duplex = require('./lib/_stream_duplex.js');
  14923. exports.Transform = require('./lib/_stream_transform.js');
  14924. exports.PassThrough = require('./lib/_stream_passthrough.js');
  14925. exports.finished = require('./lib/internal/streams/end-of-stream.js');
  14926. exports.pipeline = require('./lib/internal/streams/pipeline.js');
  14927. },{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(require,module,exports){
  14928. 'use strict'
  14929. function ReInterval (callback, interval, args) {
  14930. var self = this;
  14931. this._callback = callback;
  14932. this._args = args;
  14933. this._interval = setInterval(callback, interval, this._args);
  14934. this.reschedule = function (interval) {
  14935. // if no interval entered, use the interval passed in on creation
  14936. if (!interval)
  14937. interval = self._interval;
  14938. if (self._interval)
  14939. clearInterval(self._interval);
  14940. self._interval = setInterval(self._callback, interval, self._args);
  14941. };
  14942. this.clear = function () {
  14943. if (self._interval) {
  14944. clearInterval(self._interval);
  14945. self._interval = undefined;
  14946. }
  14947. };
  14948. this.destroy = function () {
  14949. if (self._interval) {
  14950. clearInterval(self._interval);
  14951. }
  14952. self._callback = undefined;
  14953. self._interval = undefined;
  14954. self._args = undefined;
  14955. };
  14956. }
  14957. function reInterval () {
  14958. if (typeof arguments[0] !== 'function')
  14959. throw new Error('callback needed');
  14960. if (typeof arguments[1] !== 'number')
  14961. throw new Error('interval needed');
  14962. var args;
  14963. if (arguments.length > 0) {
  14964. args = new Array(arguments.length - 2);
  14965. for (var i = 0; i < args.length; i++) {
  14966. args[i] = arguments[i + 2];
  14967. }
  14968. }
  14969. return new ReInterval(arguments[0], arguments[1], args);
  14970. }
  14971. module.exports = reInterval;
  14972. },{}],71:[function(require,module,exports){
  14973. 'use strict'
  14974. module.exports = require('./index.js')()
  14975. },{"./index.js":72}],72:[function(require,module,exports){
  14976. (function (Buffer){(function (){
  14977. 'use strict'
  14978. module.exports = rfdc
  14979. function copyBuffer (cur) {
  14980. if (cur instanceof Buffer) {
  14981. return Buffer.from(cur)
  14982. }
  14983. return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length)
  14984. }
  14985. function rfdc (opts) {
  14986. opts = opts || {}
  14987. if (opts.circles) return rfdcCircles(opts)
  14988. return opts.proto ? cloneProto : clone
  14989. function cloneArray (a, fn) {
  14990. var keys = Object.keys(a)
  14991. var a2 = new Array(keys.length)
  14992. for (var i = 0; i < keys.length; i++) {
  14993. var k = keys[i]
  14994. var cur = a[k]
  14995. if (typeof cur !== 'object' || cur === null) {
  14996. a2[k] = cur
  14997. } else if (cur instanceof Date) {
  14998. a2[k] = new Date(cur)
  14999. } else if (ArrayBuffer.isView(cur)) {
  15000. a2[k] = copyBuffer(cur)
  15001. } else {
  15002. a2[k] = fn(cur)
  15003. }
  15004. }
  15005. return a2
  15006. }
  15007. function clone (o) {
  15008. if (typeof o !== 'object' || o === null) return o
  15009. if (o instanceof Date) return new Date(o)
  15010. if (Array.isArray(o)) return cloneArray(o, clone)
  15011. if (o instanceof Map) return new Map(cloneArray(Array.from(o), clone))
  15012. if (o instanceof Set) return new Set(cloneArray(Array.from(o), clone))
  15013. var o2 = {}
  15014. for (var k in o) {
  15015. if (Object.hasOwnProperty.call(o, k) === false) continue
  15016. var cur = o[k]
  15017. if (typeof cur !== 'object' || cur === null) {
  15018. o2[k] = cur
  15019. } else if (cur instanceof Date) {
  15020. o2[k] = new Date(cur)
  15021. } else if (cur instanceof Map) {
  15022. o2[k] = new Map(cloneArray(Array.from(cur), clone))
  15023. } else if (cur instanceof Set) {
  15024. o2[k] = new Set(cloneArray(Array.from(cur), clone))
  15025. } else if (ArrayBuffer.isView(cur)) {
  15026. o2[k] = copyBuffer(cur)
  15027. } else {
  15028. o2[k] = clone(cur)
  15029. }
  15030. }
  15031. return o2
  15032. }
  15033. function cloneProto (o) {
  15034. if (typeof o !== 'object' || o === null) return o
  15035. if (o instanceof Date) return new Date(o)
  15036. if (Array.isArray(o)) return cloneArray(o, cloneProto)
  15037. if (o instanceof Map) return new Map(cloneArray(Array.from(o), cloneProto))
  15038. if (o instanceof Set) return new Set(cloneArray(Array.from(o), cloneProto))
  15039. var o2 = {}
  15040. for (var k in o) {
  15041. var cur = o[k]
  15042. if (typeof cur !== 'object' || cur === null) {
  15043. o2[k] = cur
  15044. } else if (cur instanceof Date) {
  15045. o2[k] = new Date(cur)
  15046. } else if (cur instanceof Map) {
  15047. o2[k] = new Map(cloneArray(Array.from(cur), cloneProto))
  15048. } else if (cur instanceof Set) {
  15049. o2[k] = new Set(cloneArray(Array.from(cur), cloneProto))
  15050. } else if (ArrayBuffer.isView(cur)) {
  15051. o2[k] = copyBuffer(cur)
  15052. } else {
  15053. o2[k] = cloneProto(cur)
  15054. }
  15055. }
  15056. return o2
  15057. }
  15058. }
  15059. function rfdcCircles (opts) {
  15060. var refs = []
  15061. var refsNew = []
  15062. return opts.proto ? cloneProto : clone
  15063. function cloneArray (a, fn) {
  15064. var keys = Object.keys(a)
  15065. var a2 = new Array(keys.length)
  15066. for (var i = 0; i < keys.length; i++) {
  15067. var k = keys[i]
  15068. var cur = a[k]
  15069. if (typeof cur !== 'object' || cur === null) {
  15070. a2[k] = cur
  15071. } else if (cur instanceof Date) {
  15072. a2[k] = new Date(cur)
  15073. } else if (ArrayBuffer.isView(cur)) {
  15074. a2[k] = copyBuffer(cur)
  15075. } else {
  15076. var index = refs.indexOf(cur)
  15077. if (index !== -1) {
  15078. a2[k] = refsNew[index]
  15079. } else {
  15080. a2[k] = fn(cur)
  15081. }
  15082. }
  15083. }
  15084. return a2
  15085. }
  15086. function clone (o) {
  15087. if (typeof o !== 'object' || o === null) return o
  15088. if (o instanceof Date) return new Date(o)
  15089. if (Array.isArray(o)) return cloneArray(o, clone)
  15090. if (o instanceof Map) return new Map(cloneArray(Array.from(o), clone))
  15091. if (o instanceof Set) return new Set(cloneArray(Array.from(o), clone))
  15092. var o2 = {}
  15093. refs.push(o)
  15094. refsNew.push(o2)
  15095. for (var k in o) {
  15096. if (Object.hasOwnProperty.call(o, k) === false) continue
  15097. var cur = o[k]
  15098. if (typeof cur !== 'object' || cur === null) {
  15099. o2[k] = cur
  15100. } else if (cur instanceof Date) {
  15101. o2[k] = new Date(cur)
  15102. } else if (cur instanceof Map) {
  15103. o2[k] = new Map(cloneArray(Array.from(cur), clone))
  15104. } else if (cur instanceof Set) {
  15105. o2[k] = new Set(cloneArray(Array.from(cur), clone))
  15106. } else if (ArrayBuffer.isView(cur)) {
  15107. o2[k] = copyBuffer(cur)
  15108. } else {
  15109. var i = refs.indexOf(cur)
  15110. if (i !== -1) {
  15111. o2[k] = refsNew[i]
  15112. } else {
  15113. o2[k] = clone(cur)
  15114. }
  15115. }
  15116. }
  15117. refs.pop()
  15118. refsNew.pop()
  15119. return o2
  15120. }
  15121. function cloneProto (o) {
  15122. if (typeof o !== 'object' || o === null) return o
  15123. if (o instanceof Date) return new Date(o)
  15124. if (Array.isArray(o)) return cloneArray(o, cloneProto)
  15125. if (o instanceof Map) return new Map(cloneArray(Array.from(o), cloneProto))
  15126. if (o instanceof Set) return new Set(cloneArray(Array.from(o), cloneProto))
  15127. var o2 = {}
  15128. refs.push(o)
  15129. refsNew.push(o2)
  15130. for (var k in o) {
  15131. var cur = o[k]
  15132. if (typeof cur !== 'object' || cur === null) {
  15133. o2[k] = cur
  15134. } else if (cur instanceof Date) {
  15135. o2[k] = new Date(cur)
  15136. } else if (cur instanceof Map) {
  15137. o2[k] = new Map(cloneArray(Array.from(cur), cloneProto))
  15138. } else if (cur instanceof Set) {
  15139. o2[k] = new Set(cloneArray(Array.from(cur), cloneProto))
  15140. } else if (ArrayBuffer.isView(cur)) {
  15141. o2[k] = copyBuffer(cur)
  15142. } else {
  15143. var i = refs.indexOf(cur)
  15144. if (i !== -1) {
  15145. o2[k] = refsNew[i]
  15146. } else {
  15147. o2[k] = cloneProto(cur)
  15148. }
  15149. }
  15150. }
  15151. refs.pop()
  15152. refsNew.pop()
  15153. return o2
  15154. }
  15155. }
  15156. }).call(this)}).call(this,require("buffer").Buffer)
  15157. },{"buffer":17}],73:[function(require,module,exports){
  15158. /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
  15159. /* eslint-disable node/no-deprecated-api */
  15160. var buffer = require('buffer')
  15161. var Buffer = buffer.Buffer
  15162. // alternative to using Object.keys for old browsers
  15163. function copyProps (src, dst) {
  15164. for (var key in src) {
  15165. dst[key] = src[key]
  15166. }
  15167. }
  15168. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  15169. module.exports = buffer
  15170. } else {
  15171. // Copy properties from require('buffer')
  15172. copyProps(buffer, exports)
  15173. exports.Buffer = SafeBuffer
  15174. }
  15175. function SafeBuffer (arg, encodingOrOffset, length) {
  15176. return Buffer(arg, encodingOrOffset, length)
  15177. }
  15178. SafeBuffer.prototype = Object.create(Buffer.prototype)
  15179. // Copy static methods from Buffer
  15180. copyProps(Buffer, SafeBuffer)
  15181. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  15182. if (typeof arg === 'number') {
  15183. throw new TypeError('Argument must not be a number')
  15184. }
  15185. return Buffer(arg, encodingOrOffset, length)
  15186. }
  15187. SafeBuffer.alloc = function (size, fill, encoding) {
  15188. if (typeof size !== 'number') {
  15189. throw new TypeError('Argument must be a number')
  15190. }
  15191. var buf = Buffer(size)
  15192. if (fill !== undefined) {
  15193. if (typeof encoding === 'string') {
  15194. buf.fill(fill, encoding)
  15195. } else {
  15196. buf.fill(fill)
  15197. }
  15198. } else {
  15199. buf.fill(0)
  15200. }
  15201. return buf
  15202. }
  15203. SafeBuffer.allocUnsafe = function (size) {
  15204. if (typeof size !== 'number') {
  15205. throw new TypeError('Argument must be a number')
  15206. }
  15207. return Buffer(size)
  15208. }
  15209. SafeBuffer.allocUnsafeSlow = function (size) {
  15210. if (typeof size !== 'number') {
  15211. throw new TypeError('Argument must be a number')
  15212. }
  15213. return buffer.SlowBuffer(size)
  15214. }
  15215. },{"buffer":17}],74:[function(require,module,exports){
  15216. module.exports = shift
  15217. function shift (stream) {
  15218. var rs = stream._readableState
  15219. if (!rs) return null
  15220. return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs))
  15221. }
  15222. function getStateLength (state) {
  15223. if (state.buffer.length) {
  15224. // Since node 6.3.0 state.buffer is a BufferList not an array
  15225. if (state.buffer.head) {
  15226. return state.buffer.head.data.length
  15227. }
  15228. return state.buffer[0].length
  15229. }
  15230. return state.length
  15231. }
  15232. },{}],75:[function(require,module,exports){
  15233. // Copyright Joyent, Inc. and other Node contributors.
  15234. //
  15235. // Permission is hereby granted, free of charge, to any person obtaining a
  15236. // copy of this software and associated documentation files (the
  15237. // "Software"), to deal in the Software without restriction, including
  15238. // without limitation the rights to use, copy, modify, merge, publish,
  15239. // distribute, sublicense, and/or sell copies of the Software, and to permit
  15240. // persons to whom the Software is furnished to do so, subject to the
  15241. // following conditions:
  15242. //
  15243. // The above copyright notice and this permission notice shall be included
  15244. // in all copies or substantial portions of the Software.
  15245. //
  15246. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15247. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15248. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  15249. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  15250. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15251. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  15252. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  15253. 'use strict';
  15254. /*<replacement>*/
  15255. var Buffer = require('safe-buffer').Buffer;
  15256. /*</replacement>*/
  15257. var isEncoding = Buffer.isEncoding || function (encoding) {
  15258. encoding = '' + encoding;
  15259. switch (encoding && encoding.toLowerCase()) {
  15260. case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
  15261. return true;
  15262. default:
  15263. return false;
  15264. }
  15265. };
  15266. function _normalizeEncoding(enc) {
  15267. if (!enc) return 'utf8';
  15268. var retried;
  15269. while (true) {
  15270. switch (enc) {
  15271. case 'utf8':
  15272. case 'utf-8':
  15273. return 'utf8';
  15274. case 'ucs2':
  15275. case 'ucs-2':
  15276. case 'utf16le':
  15277. case 'utf-16le':
  15278. return 'utf16le';
  15279. case 'latin1':
  15280. case 'binary':
  15281. return 'latin1';
  15282. case 'base64':
  15283. case 'ascii':
  15284. case 'hex':
  15285. return enc;
  15286. default:
  15287. if (retried) return; // undefined
  15288. enc = ('' + enc).toLowerCase();
  15289. retried = true;
  15290. }
  15291. }
  15292. };
  15293. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  15294. // modules monkey-patch it to support additional encodings
  15295. function normalizeEncoding(enc) {
  15296. var nenc = _normalizeEncoding(enc);
  15297. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  15298. return nenc || enc;
  15299. }
  15300. // StringDecoder provides an interface for efficiently splitting a series of
  15301. // buffers into a series of JS strings without breaking apart multi-byte
  15302. // characters.
  15303. exports.StringDecoder = StringDecoder;
  15304. function StringDecoder(encoding) {
  15305. this.encoding = normalizeEncoding(encoding);
  15306. var nb;
  15307. switch (this.encoding) {
  15308. case 'utf16le':
  15309. this.text = utf16Text;
  15310. this.end = utf16End;
  15311. nb = 4;
  15312. break;
  15313. case 'utf8':
  15314. this.fillLast = utf8FillLast;
  15315. nb = 4;
  15316. break;
  15317. case 'base64':
  15318. this.text = base64Text;
  15319. this.end = base64End;
  15320. nb = 3;
  15321. break;
  15322. default:
  15323. this.write = simpleWrite;
  15324. this.end = simpleEnd;
  15325. return;
  15326. }
  15327. this.lastNeed = 0;
  15328. this.lastTotal = 0;
  15329. this.lastChar = Buffer.allocUnsafe(nb);
  15330. }
  15331. StringDecoder.prototype.write = function (buf) {
  15332. if (buf.length === 0) return '';
  15333. var r;
  15334. var i;
  15335. if (this.lastNeed) {
  15336. r = this.fillLast(buf);
  15337. if (r === undefined) return '';
  15338. i = this.lastNeed;
  15339. this.lastNeed = 0;
  15340. } else {
  15341. i = 0;
  15342. }
  15343. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  15344. return r || '';
  15345. };
  15346. StringDecoder.prototype.end = utf8End;
  15347. // Returns only complete characters in a Buffer
  15348. StringDecoder.prototype.text = utf8Text;
  15349. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  15350. StringDecoder.prototype.fillLast = function (buf) {
  15351. if (this.lastNeed <= buf.length) {
  15352. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  15353. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  15354. }
  15355. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  15356. this.lastNeed -= buf.length;
  15357. };
  15358. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  15359. // continuation byte. If an invalid byte is detected, -2 is returned.
  15360. function utf8CheckByte(byte) {
  15361. if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  15362. return byte >> 6 === 0x02 ? -1 : -2;
  15363. }
  15364. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  15365. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  15366. // needed to complete the UTF-8 character (if applicable) are returned.
  15367. function utf8CheckIncomplete(self, buf, i) {
  15368. var j = buf.length - 1;
  15369. if (j < i) return 0;
  15370. var nb = utf8CheckByte(buf[j]);
  15371. if (nb >= 0) {
  15372. if (nb > 0) self.lastNeed = nb - 1;
  15373. return nb;
  15374. }
  15375. if (--j < i || nb === -2) return 0;
  15376. nb = utf8CheckByte(buf[j]);
  15377. if (nb >= 0) {
  15378. if (nb > 0) self.lastNeed = nb - 2;
  15379. return nb;
  15380. }
  15381. if (--j < i || nb === -2) return 0;
  15382. nb = utf8CheckByte(buf[j]);
  15383. if (nb >= 0) {
  15384. if (nb > 0) {
  15385. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  15386. }
  15387. return nb;
  15388. }
  15389. return 0;
  15390. }
  15391. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  15392. // needed or are available. If we see a non-continuation byte where we expect
  15393. // one, we "replace" the validated continuation bytes we've seen so far with
  15394. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  15395. // behavior. The continuation byte check is included three times in the case
  15396. // where all of the continuation bytes for a character exist in the same buffer.
  15397. // It is also done this way as a slight performance increase instead of using a
  15398. // loop.
  15399. function utf8CheckExtraBytes(self, buf, p) {
  15400. if ((buf[0] & 0xC0) !== 0x80) {
  15401. self.lastNeed = 0;
  15402. return '\ufffd';
  15403. }
  15404. if (self.lastNeed > 1 && buf.length > 1) {
  15405. if ((buf[1] & 0xC0) !== 0x80) {
  15406. self.lastNeed = 1;
  15407. return '\ufffd';
  15408. }
  15409. if (self.lastNeed > 2 && buf.length > 2) {
  15410. if ((buf[2] & 0xC0) !== 0x80) {
  15411. self.lastNeed = 2;
  15412. return '\ufffd';
  15413. }
  15414. }
  15415. }
  15416. }
  15417. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  15418. function utf8FillLast(buf) {
  15419. var p = this.lastTotal - this.lastNeed;
  15420. var r = utf8CheckExtraBytes(this, buf, p);
  15421. if (r !== undefined) return r;
  15422. if (this.lastNeed <= buf.length) {
  15423. buf.copy(this.lastChar, p, 0, this.lastNeed);
  15424. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  15425. }
  15426. buf.copy(this.lastChar, p, 0, buf.length);
  15427. this.lastNeed -= buf.length;
  15428. }
  15429. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  15430. // partial character, the character's bytes are buffered until the required
  15431. // number of bytes are available.
  15432. function utf8Text(buf, i) {
  15433. var total = utf8CheckIncomplete(this, buf, i);
  15434. if (!this.lastNeed) return buf.toString('utf8', i);
  15435. this.lastTotal = total;
  15436. var end = buf.length - (total - this.lastNeed);
  15437. buf.copy(this.lastChar, 0, end);
  15438. return buf.toString('utf8', i, end);
  15439. }
  15440. // For UTF-8, a replacement character is added when ending on a partial
  15441. // character.
  15442. function utf8End(buf) {
  15443. var r = buf && buf.length ? this.write(buf) : '';
  15444. if (this.lastNeed) return r + '\ufffd';
  15445. return r;
  15446. }
  15447. // UTF-16LE typically needs two bytes per character, but even if we have an even
  15448. // number of bytes available, we need to check if we end on a leading/high
  15449. // surrogate. In that case, we need to wait for the next two bytes in order to
  15450. // decode the last character properly.
  15451. function utf16Text(buf, i) {
  15452. if ((buf.length - i) % 2 === 0) {
  15453. var r = buf.toString('utf16le', i);
  15454. if (r) {
  15455. var c = r.charCodeAt(r.length - 1);
  15456. if (c >= 0xD800 && c <= 0xDBFF) {
  15457. this.lastNeed = 2;
  15458. this.lastTotal = 4;
  15459. this.lastChar[0] = buf[buf.length - 2];
  15460. this.lastChar[1] = buf[buf.length - 1];
  15461. return r.slice(0, -1);
  15462. }
  15463. }
  15464. return r;
  15465. }
  15466. this.lastNeed = 1;
  15467. this.lastTotal = 2;
  15468. this.lastChar[0] = buf[buf.length - 1];
  15469. return buf.toString('utf16le', i, buf.length - 1);
  15470. }
  15471. // For UTF-16LE we do not explicitly append special replacement characters if we
  15472. // end on a partial character, we simply let v8 handle that.
  15473. function utf16End(buf) {
  15474. var r = buf && buf.length ? this.write(buf) : '';
  15475. if (this.lastNeed) {
  15476. var end = this.lastTotal - this.lastNeed;
  15477. return r + this.lastChar.toString('utf16le', 0, end);
  15478. }
  15479. return r;
  15480. }
  15481. function base64Text(buf, i) {
  15482. var n = (buf.length - i) % 3;
  15483. if (n === 0) return buf.toString('base64', i);
  15484. this.lastNeed = 3 - n;
  15485. this.lastTotal = 3;
  15486. if (n === 1) {
  15487. this.lastChar[0] = buf[buf.length - 1];
  15488. } else {
  15489. this.lastChar[0] = buf[buf.length - 2];
  15490. this.lastChar[1] = buf[buf.length - 1];
  15491. }
  15492. return buf.toString('base64', i, buf.length - n);
  15493. }
  15494. function base64End(buf) {
  15495. var r = buf && buf.length ? this.write(buf) : '';
  15496. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  15497. return r;
  15498. }
  15499. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  15500. function simpleWrite(buf) {
  15501. return buf.toString(this.encoding);
  15502. }
  15503. function simpleEnd(buf) {
  15504. return buf && buf.length ? this.write(buf) : '';
  15505. }
  15506. },{"safe-buffer":73}],76:[function(require,module,exports){
  15507. // Copyright Joyent, Inc. and other Node contributors.
  15508. //
  15509. // Permission is hereby granted, free of charge, to any person obtaining a
  15510. // copy of this software and associated documentation files (the
  15511. // "Software"), to deal in the Software without restriction, including
  15512. // without limitation the rights to use, copy, modify, merge, publish,
  15513. // distribute, sublicense, and/or sell copies of the Software, and to permit
  15514. // persons to whom the Software is furnished to do so, subject to the
  15515. // following conditions:
  15516. //
  15517. // The above copyright notice and this permission notice shall be included
  15518. // in all copies or substantial portions of the Software.
  15519. //
  15520. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  15521. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15522. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  15523. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  15524. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15525. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  15526. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  15527. 'use strict';
  15528. var punycode = require('punycode');
  15529. var util = require('./util');
  15530. exports.parse = urlParse;
  15531. exports.resolve = urlResolve;
  15532. exports.resolveObject = urlResolveObject;
  15533. exports.format = urlFormat;
  15534. exports.Url = Url;
  15535. function Url() {
  15536. this.protocol = null;
  15537. this.slashes = null;
  15538. this.auth = null;
  15539. this.host = null;
  15540. this.port = null;
  15541. this.hostname = null;
  15542. this.hash = null;
  15543. this.search = null;
  15544. this.query = null;
  15545. this.pathname = null;
  15546. this.path = null;
  15547. this.href = null;
  15548. }
  15549. // Reference: RFC 3986, RFC 1808, RFC 2396
  15550. // define these here so at least they only have to be
  15551. // compiled once on the first module load.
  15552. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  15553. portPattern = /:[0-9]*$/,
  15554. // Special case for a simple path URL
  15555. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  15556. // RFC 2396: characters reserved for delimiting URLs.
  15557. // We actually just auto-escape these.
  15558. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  15559. // RFC 2396: characters not allowed for various reasons.
  15560. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  15561. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  15562. autoEscape = ['\''].concat(unwise),
  15563. // Characters that are never ever allowed in a hostname.
  15564. // Note that any invalid chars are also handled, but these
  15565. // are the ones that are *expected* to be seen, so we fast-path
  15566. // them.
  15567. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  15568. hostEndingChars = ['/', '?', '#'],
  15569. hostnameMaxLen = 255,
  15570. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  15571. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  15572. // protocols that can allow "unsafe" and "unwise" chars.
  15573. unsafeProtocol = {
  15574. 'javascript': true,
  15575. 'javascript:': true
  15576. },
  15577. // protocols that never have a hostname.
  15578. hostlessProtocol = {
  15579. 'javascript': true,
  15580. 'javascript:': true
  15581. },
  15582. // protocols that always contain a // bit.
  15583. slashedProtocol = {
  15584. 'http': true,
  15585. 'https': true,
  15586. 'ftp': true,
  15587. 'gopher': true,
  15588. 'file': true,
  15589. 'http:': true,
  15590. 'https:': true,
  15591. 'ftp:': true,
  15592. 'gopher:': true,
  15593. 'file:': true
  15594. },
  15595. querystring = require('querystring');
  15596. function urlParse(url, parseQueryString, slashesDenoteHost) {
  15597. if (url && util.isObject(url) && url instanceof Url) return url;
  15598. var u = new Url;
  15599. u.parse(url, parseQueryString, slashesDenoteHost);
  15600. return u;
  15601. }
  15602. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  15603. if (!util.isString(url)) {
  15604. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  15605. }
  15606. // Copy chrome, IE, opera backslash-handling behavior.
  15607. // Back slashes before the query string get converted to forward slashes
  15608. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  15609. var queryIndex = url.indexOf('?'),
  15610. splitter =
  15611. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  15612. uSplit = url.split(splitter),
  15613. slashRegex = /\\/g;
  15614. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  15615. url = uSplit.join(splitter);
  15616. var rest = url;
  15617. // trim before proceeding.
  15618. // This is to support parse stuff like " http://foo.com \n"
  15619. rest = rest.trim();
  15620. if (!slashesDenoteHost && url.split('#').length === 1) {
  15621. // Try fast path regexp
  15622. var simplePath = simplePathPattern.exec(rest);
  15623. if (simplePath) {
  15624. this.path = rest;
  15625. this.href = rest;
  15626. this.pathname = simplePath[1];
  15627. if (simplePath[2]) {
  15628. this.search = simplePath[2];
  15629. if (parseQueryString) {
  15630. this.query = querystring.parse(this.search.substr(1));
  15631. } else {
  15632. this.query = this.search.substr(1);
  15633. }
  15634. } else if (parseQueryString) {
  15635. this.search = '';
  15636. this.query = {};
  15637. }
  15638. return this;
  15639. }
  15640. }
  15641. var proto = protocolPattern.exec(rest);
  15642. if (proto) {
  15643. proto = proto[0];
  15644. var lowerProto = proto.toLowerCase();
  15645. this.protocol = lowerProto;
  15646. rest = rest.substr(proto.length);
  15647. }
  15648. // figure out if it's got a host
  15649. // user@server is *always* interpreted as a hostname, and url
  15650. // resolution will treat //foo/bar as host=foo,path=bar because that's
  15651. // how the browser resolves relative URLs.
  15652. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  15653. var slashes = rest.substr(0, 2) === '//';
  15654. if (slashes && !(proto && hostlessProtocol[proto])) {
  15655. rest = rest.substr(2);
  15656. this.slashes = true;
  15657. }
  15658. }
  15659. if (!hostlessProtocol[proto] &&
  15660. (slashes || (proto && !slashedProtocol[proto]))) {
  15661. // there's a hostname.
  15662. // the first instance of /, ?, ;, or # ends the host.
  15663. //
  15664. // If there is an @ in the hostname, then non-host chars *are* allowed
  15665. // to the left of the last @ sign, unless some host-ending character
  15666. // comes *before* the @-sign.
  15667. // URLs are obnoxious.
  15668. //
  15669. // ex:
  15670. // http://a@b@c/ => user:a@b host:c
  15671. // http://a@b?@c => user:a host:c path:/?@c
  15672. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  15673. // Review our test case against browsers more comprehensively.
  15674. // find the first instance of any hostEndingChars
  15675. var hostEnd = -1;
  15676. for (var i = 0; i < hostEndingChars.length; i++) {
  15677. var hec = rest.indexOf(hostEndingChars[i]);
  15678. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  15679. hostEnd = hec;
  15680. }
  15681. // at this point, either we have an explicit point where the
  15682. // auth portion cannot go past, or the last @ char is the decider.
  15683. var auth, atSign;
  15684. if (hostEnd === -1) {
  15685. // atSign can be anywhere.
  15686. atSign = rest.lastIndexOf('@');
  15687. } else {
  15688. // atSign must be in auth portion.
  15689. // http://a@b/c@d => host:b auth:a path:/c@d
  15690. atSign = rest.lastIndexOf('@', hostEnd);
  15691. }
  15692. // Now we have a portion which is definitely the auth.
  15693. // Pull that off.
  15694. if (atSign !== -1) {
  15695. auth = rest.slice(0, atSign);
  15696. rest = rest.slice(atSign + 1);
  15697. this.auth = decodeURIComponent(auth);
  15698. }
  15699. // the host is the remaining to the left of the first non-host char
  15700. hostEnd = -1;
  15701. for (var i = 0; i < nonHostChars.length; i++) {
  15702. var hec = rest.indexOf(nonHostChars[i]);
  15703. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  15704. hostEnd = hec;
  15705. }
  15706. // if we still have not hit it, then the entire thing is a host.
  15707. if (hostEnd === -1)
  15708. hostEnd = rest.length;
  15709. this.host = rest.slice(0, hostEnd);
  15710. rest = rest.slice(hostEnd);
  15711. // pull out port.
  15712. this.parseHost();
  15713. // we've indicated that there is a hostname,
  15714. // so even if it's empty, it has to be present.
  15715. this.hostname = this.hostname || '';
  15716. // if hostname begins with [ and ends with ]
  15717. // assume that it's an IPv6 address.
  15718. var ipv6Hostname = this.hostname[0] === '[' &&
  15719. this.hostname[this.hostname.length - 1] === ']';
  15720. // validate a little.
  15721. if (!ipv6Hostname) {
  15722. var hostparts = this.hostname.split(/\./);
  15723. for (var i = 0, l = hostparts.length; i < l; i++) {
  15724. var part = hostparts[i];
  15725. if (!part) continue;
  15726. if (!part.match(hostnamePartPattern)) {
  15727. var newpart = '';
  15728. for (var j = 0, k = part.length; j < k; j++) {
  15729. if (part.charCodeAt(j) > 127) {
  15730. // we replace non-ASCII char with a temporary placeholder
  15731. // we need this to make sure size of hostname is not
  15732. // broken by replacing non-ASCII by nothing
  15733. newpart += 'x';
  15734. } else {
  15735. newpart += part[j];
  15736. }
  15737. }
  15738. // we test again with ASCII char only
  15739. if (!newpart.match(hostnamePartPattern)) {
  15740. var validParts = hostparts.slice(0, i);
  15741. var notHost = hostparts.slice(i + 1);
  15742. var bit = part.match(hostnamePartStart);
  15743. if (bit) {
  15744. validParts.push(bit[1]);
  15745. notHost.unshift(bit[2]);
  15746. }
  15747. if (notHost.length) {
  15748. rest = '/' + notHost.join('.') + rest;
  15749. }
  15750. this.hostname = validParts.join('.');
  15751. break;
  15752. }
  15753. }
  15754. }
  15755. }
  15756. if (this.hostname.length > hostnameMaxLen) {
  15757. this.hostname = '';
  15758. } else {
  15759. // hostnames are always lower case.
  15760. this.hostname = this.hostname.toLowerCase();
  15761. }
  15762. if (!ipv6Hostname) {
  15763. // IDNA Support: Returns a punycoded representation of "domain".
  15764. // It only converts parts of the domain name that
  15765. // have non-ASCII characters, i.e. it doesn't matter if
  15766. // you call it with a domain that already is ASCII-only.
  15767. this.hostname = punycode.toASCII(this.hostname);
  15768. }
  15769. var p = this.port ? ':' + this.port : '';
  15770. var h = this.hostname || '';
  15771. this.host = h + p;
  15772. this.href += this.host;
  15773. // strip [ and ] from the hostname
  15774. // the host field still retains them, though
  15775. if (ipv6Hostname) {
  15776. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  15777. if (rest[0] !== '/') {
  15778. rest = '/' + rest;
  15779. }
  15780. }
  15781. }
  15782. // now rest is set to the post-host stuff.
  15783. // chop off any delim chars.
  15784. if (!unsafeProtocol[lowerProto]) {
  15785. // First, make 100% sure that any "autoEscape" chars get
  15786. // escaped, even if encodeURIComponent doesn't think they
  15787. // need to be.
  15788. for (var i = 0, l = autoEscape.length; i < l; i++) {
  15789. var ae = autoEscape[i];
  15790. if (rest.indexOf(ae) === -1)
  15791. continue;
  15792. var esc = encodeURIComponent(ae);
  15793. if (esc === ae) {
  15794. esc = escape(ae);
  15795. }
  15796. rest = rest.split(ae).join(esc);
  15797. }
  15798. }
  15799. // chop off from the tail first.
  15800. var hash = rest.indexOf('#');
  15801. if (hash !== -1) {
  15802. // got a fragment string.
  15803. this.hash = rest.substr(hash);
  15804. rest = rest.slice(0, hash);
  15805. }
  15806. var qm = rest.indexOf('?');
  15807. if (qm !== -1) {
  15808. this.search = rest.substr(qm);
  15809. this.query = rest.substr(qm + 1);
  15810. if (parseQueryString) {
  15811. this.query = querystring.parse(this.query);
  15812. }
  15813. rest = rest.slice(0, qm);
  15814. } else if (parseQueryString) {
  15815. // no query string, but parseQueryString still requested
  15816. this.search = '';
  15817. this.query = {};
  15818. }
  15819. if (rest) this.pathname = rest;
  15820. if (slashedProtocol[lowerProto] &&
  15821. this.hostname && !this.pathname) {
  15822. this.pathname = '/';
  15823. }
  15824. //to support http.request
  15825. if (this.pathname || this.search) {
  15826. var p = this.pathname || '';
  15827. var s = this.search || '';
  15828. this.path = p + s;
  15829. }
  15830. // finally, reconstruct the href based on what has been validated.
  15831. this.href = this.format();
  15832. return this;
  15833. };
  15834. // format a parsed object into a url string
  15835. function urlFormat(obj) {
  15836. // ensure it's an object, and not a string url.
  15837. // If it's an obj, this is a no-op.
  15838. // this way, you can call url_format() on strings
  15839. // to clean up potentially wonky urls.
  15840. if (util.isString(obj)) obj = urlParse(obj);
  15841. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  15842. return obj.format();
  15843. }
  15844. Url.prototype.format = function() {
  15845. var auth = this.auth || '';
  15846. if (auth) {
  15847. auth = encodeURIComponent(auth);
  15848. auth = auth.replace(/%3A/i, ':');
  15849. auth += '@';
  15850. }
  15851. var protocol = this.protocol || '',
  15852. pathname = this.pathname || '',
  15853. hash = this.hash || '',
  15854. host = false,
  15855. query = '';
  15856. if (this.host) {
  15857. host = auth + this.host;
  15858. } else if (this.hostname) {
  15859. host = auth + (this.hostname.indexOf(':') === -1 ?
  15860. this.hostname :
  15861. '[' + this.hostname + ']');
  15862. if (this.port) {
  15863. host += ':' + this.port;
  15864. }
  15865. }
  15866. if (this.query &&
  15867. util.isObject(this.query) &&
  15868. Object.keys(this.query).length) {
  15869. query = querystring.stringify(this.query);
  15870. }
  15871. var search = this.search || (query && ('?' + query)) || '';
  15872. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  15873. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  15874. // unless they had them to begin with.
  15875. if (this.slashes ||
  15876. (!protocol || slashedProtocol[protocol]) && host !== false) {
  15877. host = '//' + (host || '');
  15878. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  15879. } else if (!host) {
  15880. host = '';
  15881. }
  15882. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  15883. if (search && search.charAt(0) !== '?') search = '?' + search;
  15884. pathname = pathname.replace(/[?#]/g, function(match) {
  15885. return encodeURIComponent(match);
  15886. });
  15887. search = search.replace('#', '%23');
  15888. return protocol + host + pathname + search + hash;
  15889. };
  15890. function urlResolve(source, relative) {
  15891. return urlParse(source, false, true).resolve(relative);
  15892. }
  15893. Url.prototype.resolve = function(relative) {
  15894. return this.resolveObject(urlParse(relative, false, true)).format();
  15895. };
  15896. function urlResolveObject(source, relative) {
  15897. if (!source) return relative;
  15898. return urlParse(source, false, true).resolveObject(relative);
  15899. }
  15900. Url.prototype.resolveObject = function(relative) {
  15901. if (util.isString(relative)) {
  15902. var rel = new Url();
  15903. rel.parse(relative, false, true);
  15904. relative = rel;
  15905. }
  15906. var result = new Url();
  15907. var tkeys = Object.keys(this);
  15908. for (var tk = 0; tk < tkeys.length; tk++) {
  15909. var tkey = tkeys[tk];
  15910. result[tkey] = this[tkey];
  15911. }
  15912. // hash is always overridden, no matter what.
  15913. // even href="" will remove it.
  15914. result.hash = relative.hash;
  15915. // if the relative url is empty, then there's nothing left to do here.
  15916. if (relative.href === '') {
  15917. result.href = result.format();
  15918. return result;
  15919. }
  15920. // hrefs like //foo/bar always cut to the protocol.
  15921. if (relative.slashes && !relative.protocol) {
  15922. // take everything except the protocol from relative
  15923. var rkeys = Object.keys(relative);
  15924. for (var rk = 0; rk < rkeys.length; rk++) {
  15925. var rkey = rkeys[rk];
  15926. if (rkey !== 'protocol')
  15927. result[rkey] = relative[rkey];
  15928. }
  15929. //urlParse appends trailing / to urls like http://www.example.com
  15930. if (slashedProtocol[result.protocol] &&
  15931. result.hostname && !result.pathname) {
  15932. result.path = result.pathname = '/';
  15933. }
  15934. result.href = result.format();
  15935. return result;
  15936. }
  15937. if (relative.protocol && relative.protocol !== result.protocol) {
  15938. // if it's a known url protocol, then changing
  15939. // the protocol does weird things
  15940. // first, if it's not file:, then we MUST have a host,
  15941. // and if there was a path
  15942. // to begin with, then we MUST have a path.
  15943. // if it is file:, then the host is dropped,
  15944. // because that's known to be hostless.
  15945. // anything else is assumed to be absolute.
  15946. if (!slashedProtocol[relative.protocol]) {
  15947. var keys = Object.keys(relative);
  15948. for (var v = 0; v < keys.length; v++) {
  15949. var k = keys[v];
  15950. result[k] = relative[k];
  15951. }
  15952. result.href = result.format();
  15953. return result;
  15954. }
  15955. result.protocol = relative.protocol;
  15956. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  15957. var relPath = (relative.pathname || '').split('/');
  15958. while (relPath.length && !(relative.host = relPath.shift()));
  15959. if (!relative.host) relative.host = '';
  15960. if (!relative.hostname) relative.hostname = '';
  15961. if (relPath[0] !== '') relPath.unshift('');
  15962. if (relPath.length < 2) relPath.unshift('');
  15963. result.pathname = relPath.join('/');
  15964. } else {
  15965. result.pathname = relative.pathname;
  15966. }
  15967. result.search = relative.search;
  15968. result.query = relative.query;
  15969. result.host = relative.host || '';
  15970. result.auth = relative.auth;
  15971. result.hostname = relative.hostname || relative.host;
  15972. result.port = relative.port;
  15973. // to support http.request
  15974. if (result.pathname || result.search) {
  15975. var p = result.pathname || '';
  15976. var s = result.search || '';
  15977. result.path = p + s;
  15978. }
  15979. result.slashes = result.slashes || relative.slashes;
  15980. result.href = result.format();
  15981. return result;
  15982. }
  15983. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  15984. isRelAbs = (
  15985. relative.host ||
  15986. relative.pathname && relative.pathname.charAt(0) === '/'
  15987. ),
  15988. mustEndAbs = (isRelAbs || isSourceAbs ||
  15989. (result.host && relative.pathname)),
  15990. removeAllDots = mustEndAbs,
  15991. srcPath = result.pathname && result.pathname.split('/') || [],
  15992. relPath = relative.pathname && relative.pathname.split('/') || [],
  15993. psychotic = result.protocol && !slashedProtocol[result.protocol];
  15994. // if the url is a non-slashed url, then relative
  15995. // links like ../.. should be able
  15996. // to crawl up to the hostname, as well. This is strange.
  15997. // result.protocol has already been set by now.
  15998. // Later on, put the first path part into the host field.
  15999. if (psychotic) {
  16000. result.hostname = '';
  16001. result.port = null;
  16002. if (result.host) {
  16003. if (srcPath[0] === '') srcPath[0] = result.host;
  16004. else srcPath.unshift(result.host);
  16005. }
  16006. result.host = '';
  16007. if (relative.protocol) {
  16008. relative.hostname = null;
  16009. relative.port = null;
  16010. if (relative.host) {
  16011. if (relPath[0] === '') relPath[0] = relative.host;
  16012. else relPath.unshift(relative.host);
  16013. }
  16014. relative.host = null;
  16015. }
  16016. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  16017. }
  16018. if (isRelAbs) {
  16019. // it's absolute.
  16020. result.host = (relative.host || relative.host === '') ?
  16021. relative.host : result.host;
  16022. result.hostname = (relative.hostname || relative.hostname === '') ?
  16023. relative.hostname : result.hostname;
  16024. result.search = relative.search;
  16025. result.query = relative.query;
  16026. srcPath = relPath;
  16027. // fall through to the dot-handling below.
  16028. } else if (relPath.length) {
  16029. // it's relative
  16030. // throw away the existing file, and take the new path instead.
  16031. if (!srcPath) srcPath = [];
  16032. srcPath.pop();
  16033. srcPath = srcPath.concat(relPath);
  16034. result.search = relative.search;
  16035. result.query = relative.query;
  16036. } else if (!util.isNullOrUndefined(relative.search)) {
  16037. // just pull out the search.
  16038. // like href='?foo'.
  16039. // Put this after the other two cases because it simplifies the booleans
  16040. if (psychotic) {
  16041. result.hostname = result.host = srcPath.shift();
  16042. //occationaly the auth can get stuck only in host
  16043. //this especially happens in cases like
  16044. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  16045. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  16046. result.host.split('@') : false;
  16047. if (authInHost) {
  16048. result.auth = authInHost.shift();
  16049. result.host = result.hostname = authInHost.shift();
  16050. }
  16051. }
  16052. result.search = relative.search;
  16053. result.query = relative.query;
  16054. //to support http.request
  16055. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  16056. result.path = (result.pathname ? result.pathname : '') +
  16057. (result.search ? result.search : '');
  16058. }
  16059. result.href = result.format();
  16060. return result;
  16061. }
  16062. if (!srcPath.length) {
  16063. // no path at all. easy.
  16064. // we've already handled the other stuff above.
  16065. result.pathname = null;
  16066. //to support http.request
  16067. if (result.search) {
  16068. result.path = '/' + result.search;
  16069. } else {
  16070. result.path = null;
  16071. }
  16072. result.href = result.format();
  16073. return result;
  16074. }
  16075. // if a url ENDs in . or .., then it must get a trailing slash.
  16076. // however, if it ends in anything else non-slashy,
  16077. // then it must NOT get a trailing slash.
  16078. var last = srcPath.slice(-1)[0];
  16079. var hasTrailingSlash = (
  16080. (result.host || relative.host || srcPath.length > 1) &&
  16081. (last === '.' || last === '..') || last === '');
  16082. // strip single dots, resolve double dots to parent dir
  16083. // if the path tries to go above the root, `up` ends up > 0
  16084. var up = 0;
  16085. for (var i = srcPath.length; i >= 0; i--) {
  16086. last = srcPath[i];
  16087. if (last === '.') {
  16088. srcPath.splice(i, 1);
  16089. } else if (last === '..') {
  16090. srcPath.splice(i, 1);
  16091. up++;
  16092. } else if (up) {
  16093. srcPath.splice(i, 1);
  16094. up--;
  16095. }
  16096. }
  16097. // if the path is allowed to go above the root, restore leading ..s
  16098. if (!mustEndAbs && !removeAllDots) {
  16099. for (; up--; up) {
  16100. srcPath.unshift('..');
  16101. }
  16102. }
  16103. if (mustEndAbs && srcPath[0] !== '' &&
  16104. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  16105. srcPath.unshift('');
  16106. }
  16107. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  16108. srcPath.push('');
  16109. }
  16110. var isAbsolute = srcPath[0] === '' ||
  16111. (srcPath[0] && srcPath[0].charAt(0) === '/');
  16112. // put the host back
  16113. if (psychotic) {
  16114. result.hostname = result.host = isAbsolute ? '' :
  16115. srcPath.length ? srcPath.shift() : '';
  16116. //occationaly the auth can get stuck only in host
  16117. //this especially happens in cases like
  16118. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  16119. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  16120. result.host.split('@') : false;
  16121. if (authInHost) {
  16122. result.auth = authInHost.shift();
  16123. result.host = result.hostname = authInHost.shift();
  16124. }
  16125. }
  16126. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  16127. if (mustEndAbs && !isAbsolute) {
  16128. srcPath.unshift('');
  16129. }
  16130. if (!srcPath.length) {
  16131. result.pathname = null;
  16132. result.path = null;
  16133. } else {
  16134. result.pathname = srcPath.join('/');
  16135. }
  16136. //to support request.http
  16137. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  16138. result.path = (result.pathname ? result.pathname : '') +
  16139. (result.search ? result.search : '');
  16140. }
  16141. result.auth = relative.auth || result.auth;
  16142. result.slashes = result.slashes || relative.slashes;
  16143. result.href = result.format();
  16144. return result;
  16145. };
  16146. Url.prototype.parseHost = function() {
  16147. var host = this.host;
  16148. var port = portPattern.exec(host);
  16149. if (port) {
  16150. port = port[0];
  16151. if (port !== ':') {
  16152. this.port = port.substr(1);
  16153. }
  16154. host = host.substr(0, host.length - port.length);
  16155. }
  16156. if (host) this.hostname = host;
  16157. };
  16158. },{"./util":77,"punycode":51,"querystring":54}],77:[function(require,module,exports){
  16159. 'use strict';
  16160. module.exports = {
  16161. isString: function(arg) {
  16162. return typeof(arg) === 'string';
  16163. },
  16164. isObject: function(arg) {
  16165. return typeof(arg) === 'object' && arg !== null;
  16166. },
  16167. isNull: function(arg) {
  16168. return arg === null;
  16169. },
  16170. isNullOrUndefined: function(arg) {
  16171. return arg == null;
  16172. }
  16173. };
  16174. },{}],78:[function(require,module,exports){
  16175. (function (global){(function (){
  16176. /**
  16177. * Module exports.
  16178. */
  16179. module.exports = deprecate;
  16180. /**
  16181. * Mark that a method should not be used.
  16182. * Returns a modified function which warns once by default.
  16183. *
  16184. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  16185. *
  16186. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  16187. * will throw an Error when invoked.
  16188. *
  16189. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  16190. * will invoke `console.trace()` instead of `console.error()`.
  16191. *
  16192. * @param {Function} fn - the function to deprecate
  16193. * @param {String} msg - the string to print to the console when `fn` is invoked
  16194. * @returns {Function} a new "deprecated" version of `fn`
  16195. * @api public
  16196. */
  16197. function deprecate (fn, msg) {
  16198. if (config('noDeprecation')) {
  16199. return fn;
  16200. }
  16201. var warned = false;
  16202. function deprecated() {
  16203. if (!warned) {
  16204. if (config('throwDeprecation')) {
  16205. throw new Error(msg);
  16206. } else if (config('traceDeprecation')) {
  16207. console.trace(msg);
  16208. } else {
  16209. console.warn(msg);
  16210. }
  16211. warned = true;
  16212. }
  16213. return fn.apply(this, arguments);
  16214. }
  16215. return deprecated;
  16216. }
  16217. /**
  16218. * Checks `localStorage` for boolean values for the given `name`.
  16219. *
  16220. * @param {String} name
  16221. * @returns {Boolean}
  16222. * @api private
  16223. */
  16224. function config (name) {
  16225. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  16226. try {
  16227. if (!global.localStorage) return false;
  16228. } catch (_) {
  16229. return false;
  16230. }
  16231. var val = global.localStorage[name];
  16232. if (null == val) return false;
  16233. return String(val).toLowerCase() === 'true';
  16234. }
  16235. }).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  16236. },{}],79:[function(require,module,exports){
  16237. // Returns a wrapper function that returns a wrapped callback
  16238. // The wrapper function should do some stuff, and return a
  16239. // presumably different callback function.
  16240. // This makes sure that own properties are retained, so that
  16241. // decorations and such are not lost along the way.
  16242. module.exports = wrappy
  16243. function wrappy (fn, cb) {
  16244. if (fn && cb) return wrappy(fn)(cb)
  16245. if (typeof fn !== 'function')
  16246. throw new TypeError('need wrapper function')
  16247. Object.keys(fn).forEach(function (k) {
  16248. wrapper[k] = fn[k]
  16249. })
  16250. return wrapper
  16251. function wrapper() {
  16252. var args = new Array(arguments.length)
  16253. for (var i = 0; i < args.length; i++) {
  16254. args[i] = arguments[i]
  16255. }
  16256. var ret = fn.apply(this, args)
  16257. var cb = args[args.length-1]
  16258. if (typeof ret === 'function' && ret !== cb) {
  16259. Object.keys(cb).forEach(function (k) {
  16260. ret[k] = cb[k]
  16261. })
  16262. }
  16263. return ret
  16264. }
  16265. }
  16266. },{}],80:[function(require,module,exports){
  16267. 'use strict';
  16268. module.exports = function () {
  16269. throw new Error(
  16270. 'ws does not work in the browser. Browser clients must use the native ' +
  16271. 'WebSocket object'
  16272. );
  16273. };
  16274. },{}],81:[function(require,module,exports){
  16275. module.exports = extend
  16276. var hasOwnProperty = Object.prototype.hasOwnProperty;
  16277. function extend() {
  16278. var target = {}
  16279. for (var i = 0; i < arguments.length; i++) {
  16280. var source = arguments[i]
  16281. for (var key in source) {
  16282. if (hasOwnProperty.call(source, key)) {
  16283. target[key] = source[key]
  16284. }
  16285. }
  16286. }
  16287. return target
  16288. }
  16289. },{}],82:[function(require,module,exports){
  16290. 'use strict'
  16291. module.exports = function (Yallist) {
  16292. Yallist.prototype[Symbol.iterator] = function* () {
  16293. for (let walker = this.head; walker; walker = walker.next) {
  16294. yield walker.value
  16295. }
  16296. }
  16297. }
  16298. },{}],83:[function(require,module,exports){
  16299. 'use strict'
  16300. module.exports = Yallist
  16301. Yallist.Node = Node
  16302. Yallist.create = Yallist
  16303. function Yallist (list) {
  16304. var self = this
  16305. if (!(self instanceof Yallist)) {
  16306. self = new Yallist()
  16307. }
  16308. self.tail = null
  16309. self.head = null
  16310. self.length = 0
  16311. if (list && typeof list.forEach === 'function') {
  16312. list.forEach(function (item) {
  16313. self.push(item)
  16314. })
  16315. } else if (arguments.length > 0) {
  16316. for (var i = 0, l = arguments.length; i < l; i++) {
  16317. self.push(arguments[i])
  16318. }
  16319. }
  16320. return self
  16321. }
  16322. Yallist.prototype.removeNode = function (node) {
  16323. if (node.list !== this) {
  16324. throw new Error('removing node which does not belong to this list')
  16325. }
  16326. var next = node.next
  16327. var prev = node.prev
  16328. if (next) {
  16329. next.prev = prev
  16330. }
  16331. if (prev) {
  16332. prev.next = next
  16333. }
  16334. if (node === this.head) {
  16335. this.head = next
  16336. }
  16337. if (node === this.tail) {
  16338. this.tail = prev
  16339. }
  16340. node.list.length--
  16341. node.next = null
  16342. node.prev = null
  16343. node.list = null
  16344. return next
  16345. }
  16346. Yallist.prototype.unshiftNode = function (node) {
  16347. if (node === this.head) {
  16348. return
  16349. }
  16350. if (node.list) {
  16351. node.list.removeNode(node)
  16352. }
  16353. var head = this.head
  16354. node.list = this
  16355. node.next = head
  16356. if (head) {
  16357. head.prev = node
  16358. }
  16359. this.head = node
  16360. if (!this.tail) {
  16361. this.tail = node
  16362. }
  16363. this.length++
  16364. }
  16365. Yallist.prototype.pushNode = function (node) {
  16366. if (node === this.tail) {
  16367. return
  16368. }
  16369. if (node.list) {
  16370. node.list.removeNode(node)
  16371. }
  16372. var tail = this.tail
  16373. node.list = this
  16374. node.prev = tail
  16375. if (tail) {
  16376. tail.next = node
  16377. }
  16378. this.tail = node
  16379. if (!this.head) {
  16380. this.head = node
  16381. }
  16382. this.length++
  16383. }
  16384. Yallist.prototype.push = function () {
  16385. for (var i = 0, l = arguments.length; i < l; i++) {
  16386. push(this, arguments[i])
  16387. }
  16388. return this.length
  16389. }
  16390. Yallist.prototype.unshift = function () {
  16391. for (var i = 0, l = arguments.length; i < l; i++) {
  16392. unshift(this, arguments[i])
  16393. }
  16394. return this.length
  16395. }
  16396. Yallist.prototype.pop = function () {
  16397. if (!this.tail) {
  16398. return undefined
  16399. }
  16400. var res = this.tail.value
  16401. this.tail = this.tail.prev
  16402. if (this.tail) {
  16403. this.tail.next = null
  16404. } else {
  16405. this.head = null
  16406. }
  16407. this.length--
  16408. return res
  16409. }
  16410. Yallist.prototype.shift = function () {
  16411. if (!this.head) {
  16412. return undefined
  16413. }
  16414. var res = this.head.value
  16415. this.head = this.head.next
  16416. if (this.head) {
  16417. this.head.prev = null
  16418. } else {
  16419. this.tail = null
  16420. }
  16421. this.length--
  16422. return res
  16423. }
  16424. Yallist.prototype.forEach = function (fn, thisp) {
  16425. thisp = thisp || this
  16426. for (var walker = this.head, i = 0; walker !== null; i++) {
  16427. fn.call(thisp, walker.value, i, this)
  16428. walker = walker.next
  16429. }
  16430. }
  16431. Yallist.prototype.forEachReverse = function (fn, thisp) {
  16432. thisp = thisp || this
  16433. for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
  16434. fn.call(thisp, walker.value, i, this)
  16435. walker = walker.prev
  16436. }
  16437. }
  16438. Yallist.prototype.get = function (n) {
  16439. for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
  16440. // abort out of the list early if we hit a cycle
  16441. walker = walker.next
  16442. }
  16443. if (i === n && walker !== null) {
  16444. return walker.value
  16445. }
  16446. }
  16447. Yallist.prototype.getReverse = function (n) {
  16448. for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
  16449. // abort out of the list early if we hit a cycle
  16450. walker = walker.prev
  16451. }
  16452. if (i === n && walker !== null) {
  16453. return walker.value
  16454. }
  16455. }
  16456. Yallist.prototype.map = function (fn, thisp) {
  16457. thisp = thisp || this
  16458. var res = new Yallist()
  16459. for (var walker = this.head; walker !== null;) {
  16460. res.push(fn.call(thisp, walker.value, this))
  16461. walker = walker.next
  16462. }
  16463. return res
  16464. }
  16465. Yallist.prototype.mapReverse = function (fn, thisp) {
  16466. thisp = thisp || this
  16467. var res = new Yallist()
  16468. for (var walker = this.tail; walker !== null;) {
  16469. res.push(fn.call(thisp, walker.value, this))
  16470. walker = walker.prev
  16471. }
  16472. return res
  16473. }
  16474. Yallist.prototype.reduce = function (fn, initial) {
  16475. var acc
  16476. var walker = this.head
  16477. if (arguments.length > 1) {
  16478. acc = initial
  16479. } else if (this.head) {
  16480. walker = this.head.next
  16481. acc = this.head.value
  16482. } else {
  16483. throw new TypeError('Reduce of empty list with no initial value')
  16484. }
  16485. for (var i = 0; walker !== null; i++) {
  16486. acc = fn(acc, walker.value, i)
  16487. walker = walker.next
  16488. }
  16489. return acc
  16490. }
  16491. Yallist.prototype.reduceReverse = function (fn, initial) {
  16492. var acc
  16493. var walker = this.tail
  16494. if (arguments.length > 1) {
  16495. acc = initial
  16496. } else if (this.tail) {
  16497. walker = this.tail.prev
  16498. acc = this.tail.value
  16499. } else {
  16500. throw new TypeError('Reduce of empty list with no initial value')
  16501. }
  16502. for (var i = this.length - 1; walker !== null; i--) {
  16503. acc = fn(acc, walker.value, i)
  16504. walker = walker.prev
  16505. }
  16506. return acc
  16507. }
  16508. Yallist.prototype.toArray = function () {
  16509. var arr = new Array(this.length)
  16510. for (var i = 0, walker = this.head; walker !== null; i++) {
  16511. arr[i] = walker.value
  16512. walker = walker.next
  16513. }
  16514. return arr
  16515. }
  16516. Yallist.prototype.toArrayReverse = function () {
  16517. var arr = new Array(this.length)
  16518. for (var i = 0, walker = this.tail; walker !== null; i++) {
  16519. arr[i] = walker.value
  16520. walker = walker.prev
  16521. }
  16522. return arr
  16523. }
  16524. Yallist.prototype.slice = function (from, to) {
  16525. to = to || this.length
  16526. if (to < 0) {
  16527. to += this.length
  16528. }
  16529. from = from || 0
  16530. if (from < 0) {
  16531. from += this.length
  16532. }
  16533. var ret = new Yallist()
  16534. if (to < from || to < 0) {
  16535. return ret
  16536. }
  16537. if (from < 0) {
  16538. from = 0
  16539. }
  16540. if (to > this.length) {
  16541. to = this.length
  16542. }
  16543. for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
  16544. walker = walker.next
  16545. }
  16546. for (; walker !== null && i < to; i++, walker = walker.next) {
  16547. ret.push(walker.value)
  16548. }
  16549. return ret
  16550. }
  16551. Yallist.prototype.sliceReverse = function (from, to) {
  16552. to = to || this.length
  16553. if (to < 0) {
  16554. to += this.length
  16555. }
  16556. from = from || 0
  16557. if (from < 0) {
  16558. from += this.length
  16559. }
  16560. var ret = new Yallist()
  16561. if (to < from || to < 0) {
  16562. return ret
  16563. }
  16564. if (from < 0) {
  16565. from = 0
  16566. }
  16567. if (to > this.length) {
  16568. to = this.length
  16569. }
  16570. for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
  16571. walker = walker.prev
  16572. }
  16573. for (; walker !== null && i > from; i--, walker = walker.prev) {
  16574. ret.push(walker.value)
  16575. }
  16576. return ret
  16577. }
  16578. Yallist.prototype.splice = function (start, deleteCount, ...nodes) {
  16579. if (start > this.length) {
  16580. start = this.length - 1
  16581. }
  16582. if (start < 0) {
  16583. start = this.length + start;
  16584. }
  16585. for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
  16586. walker = walker.next
  16587. }
  16588. var ret = []
  16589. for (var i = 0; walker && i < deleteCount; i++) {
  16590. ret.push(walker.value)
  16591. walker = this.removeNode(walker)
  16592. }
  16593. if (walker === null) {
  16594. walker = this.tail
  16595. }
  16596. if (walker !== this.head && walker !== this.tail) {
  16597. walker = walker.prev
  16598. }
  16599. for (var i = 0; i < nodes.length; i++) {
  16600. walker = insert(this, walker, nodes[i])
  16601. }
  16602. return ret;
  16603. }
  16604. Yallist.prototype.reverse = function () {
  16605. var head = this.head
  16606. var tail = this.tail
  16607. for (var walker = head; walker !== null; walker = walker.prev) {
  16608. var p = walker.prev
  16609. walker.prev = walker.next
  16610. walker.next = p
  16611. }
  16612. this.head = tail
  16613. this.tail = head
  16614. return this
  16615. }
  16616. function insert (self, node, value) {
  16617. var inserted = node === self.head ?
  16618. new Node(value, null, node, self) :
  16619. new Node(value, node, node.next, self)
  16620. if (inserted.next === null) {
  16621. self.tail = inserted
  16622. }
  16623. if (inserted.prev === null) {
  16624. self.head = inserted
  16625. }
  16626. self.length++
  16627. return inserted
  16628. }
  16629. function push (self, item) {
  16630. self.tail = new Node(item, self.tail, null, self)
  16631. if (!self.head) {
  16632. self.head = self.tail
  16633. }
  16634. self.length++
  16635. }
  16636. function unshift (self, item) {
  16637. self.head = new Node(item, null, self.head, self)
  16638. if (!self.tail) {
  16639. self.tail = self.head
  16640. }
  16641. self.length++
  16642. }
  16643. function Node (value, prev, next, list) {
  16644. if (!(this instanceof Node)) {
  16645. return new Node(value, prev, next, list)
  16646. }
  16647. this.list = list
  16648. this.value = value
  16649. if (prev) {
  16650. prev.next = this
  16651. this.prev = prev
  16652. } else {
  16653. this.prev = null
  16654. }
  16655. if (next) {
  16656. next.prev = this
  16657. this.next = next
  16658. } else {
  16659. this.next = null
  16660. }
  16661. }
  16662. try {
  16663. // add if support for Symbol.iterator is present
  16664. require('./iterator.js')(Yallist)
  16665. } catch (er) {}
  16666. },{"./iterator.js":82}]},{},[12])(12)
  16667. });