|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644 |
- (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.LessPass = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
- var v1 = require('./src/v1');
- var v2 = require('./src/v2');
-
- module.exports = {
- encryptLogin: v1.encryptLogin,
- renderPassword: v1.renderPassword,
- createFingerprint: v1.createFingerprint,
- _deriveEncryptedLogin: v1._deriveEncryptedLogin,
- _getPasswordTemplate: v1._getPasswordTemplate,
- _prettyPrint: v1._prettyPrint,
- _string2charCodes: v1._string2charCodes,
- _getCharType: v1._getCharType,
- _getPasswordChar: v1._getPasswordChar,
- _createHmac: v1._createHmac,
-
- generatePassword: v2.generatePassword,
- _calcEntropy: v2._calcEntropy,
- _getSetOfCharacters: v2._getSetOfCharacters,
- _renderPassword: v2._renderPassword,
- };
- },{"./src/v1":46,"./src/v2":47}],2:[function(require,module,exports){
- 'use strict'
-
- exports.byteLength = byteLength
- exports.toByteArray = toByteArray
- exports.fromByteArray = fromByteArray
-
- var lookup = []
- var revLookup = []
- var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
-
- var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
- for (var i = 0, len = code.length; i < len; ++i) {
- lookup[i] = code[i]
- revLookup[code.charCodeAt(i)] = i
- }
-
- revLookup['-'.charCodeAt(0)] = 62
- revLookup['_'.charCodeAt(0)] = 63
-
- function placeHoldersCount (b64) {
- var len = b64.length
- if (len % 4 > 0) {
- throw new Error('Invalid string. Length must be a multiple of 4')
- }
-
- // the number of equal signs (place holders)
- // if there are two placeholders, than the two characters before it
- // represent one byte
- // if there is only one, then the three characters before it represent 2 bytes
- // this is just a cheap hack to not do indexOf twice
- return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
- }
-
- function byteLength (b64) {
- // base64 is 4/3 + up to two characters of the original data
- return b64.length * 3 / 4 - placeHoldersCount(b64)
- }
-
- function toByteArray (b64) {
- var i, j, l, tmp, placeHolders, arr
- var len = b64.length
- placeHolders = placeHoldersCount(b64)
-
- arr = new Arr(len * 3 / 4 - placeHolders)
-
- // if there are placeholders, only get up to the last complete 4 chars
- l = placeHolders > 0 ? len - 4 : len
-
- var L = 0
-
- for (i = 0, j = 0; i < l; i += 4, j += 3) {
- tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
- arr[L++] = (tmp >> 16) & 0xFF
- arr[L++] = (tmp >> 8) & 0xFF
- arr[L++] = tmp & 0xFF
- }
-
- if (placeHolders === 2) {
- tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
- arr[L++] = tmp & 0xFF
- } else if (placeHolders === 1) {
- tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
- arr[L++] = (tmp >> 8) & 0xFF
- arr[L++] = tmp & 0xFF
- }
-
- return arr
- }
-
- function tripletToBase64 (num) {
- return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
- }
-
- function encodeChunk (uint8, start, end) {
- var tmp
- var output = []
- for (var i = start; i < end; i += 3) {
- tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
- output.push(tripletToBase64(tmp))
- }
- return output.join('')
- }
-
- function fromByteArray (uint8) {
- var tmp
- var len = uint8.length
- var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
- var output = ''
- var parts = []
- var maxChunkLength = 16383 // must be multiple of 3
-
- // go through the array every three bytes, we'll deal with trailing stuff later
- for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
- parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
- }
-
- // pad the end with zeros, but make sure to not forget the extra bytes
- if (extraBytes === 1) {
- tmp = uint8[len - 1]
- output += lookup[tmp >> 2]
- output += lookup[(tmp << 4) & 0x3F]
- output += '=='
- } else if (extraBytes === 2) {
- tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
- output += lookup[tmp >> 10]
- output += lookup[(tmp >> 4) & 0x3F]
- output += lookup[(tmp << 2) & 0x3F]
- output += '='
- }
-
- parts.push(output)
-
- return parts.join('')
- }
-
- },{}],3:[function(require,module,exports){
- var bigInt = (function (undefined) {
- "use strict";
-
- var BASE = 1e7,
- LOG_BASE = 7,
- MAX_INT = 9007199254740992,
- MAX_INT_ARR = smallToArray(MAX_INT),
- LOG_MAX_INT = Math.log(MAX_INT);
-
- function Integer(v, radix) {
- if (typeof v === "undefined") return Integer[0];
- if (typeof radix !== "undefined") return +radix === 10 ? parseValue(v) : parseBase(v, radix);
- return parseValue(v);
- }
-
- function BigInteger(value, sign) {
- this.value = value;
- this.sign = sign;
- this.isSmall = false;
- }
- BigInteger.prototype = Object.create(Integer.prototype);
-
- function SmallInteger(value) {
- this.value = value;
- this.sign = value < 0;
- this.isSmall = true;
- }
- SmallInteger.prototype = Object.create(Integer.prototype);
-
- function isPrecise(n) {
- return -MAX_INT < n && n < MAX_INT;
- }
-
- function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes
- if (n < 1e7)
- return [n];
- if (n < 1e14)
- return [n % 1e7, Math.floor(n / 1e7)];
- return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
- }
-
- function arrayToSmall(arr) { // If BASE changes this function may need to change
- trim(arr);
- var length = arr.length;
- if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
- switch (length) {
- case 0: return 0;
- case 1: return arr[0];
- case 2: return arr[0] + arr[1] * BASE;
- default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
- }
- }
- return arr;
- }
-
- function trim(v) {
- var i = v.length;
- while (v[--i] === 0);
- v.length = i + 1;
- }
-
- function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger
- var x = new Array(length);
- var i = -1;
- while (++i < length) {
- x[i] = 0;
- }
- return x;
- }
-
- function truncate(n) {
- if (n > 0) return Math.floor(n);
- return Math.ceil(n);
- }
-
- function add(a, b) { // assumes a and b are arrays with a.length >= b.length
- var l_a = a.length,
- l_b = b.length,
- r = new Array(l_a),
- carry = 0,
- base = BASE,
- sum, i;
- for (i = 0; i < l_b; i++) {
- sum = a[i] + b[i] + carry;
- carry = sum >= base ? 1 : 0;
- r[i] = sum - carry * base;
- }
- while (i < l_a) {
- sum = a[i] + carry;
- carry = sum === base ? 1 : 0;
- r[i++] = sum - carry * base;
- }
- if (carry > 0) r.push(carry);
- return r;
- }
-
- function addAny(a, b) {
- if (a.length >= b.length) return add(a, b);
- return add(b, a);
- }
-
- function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT
- var l = a.length,
- r = new Array(l),
- base = BASE,
- sum, i;
- for (i = 0; i < l; i++) {
- sum = a[i] - base + carry;
- carry = Math.floor(sum / base);
- r[i] = sum - carry * base;
- carry += 1;
- }
- while (carry > 0) {
- r[i++] = carry % base;
- carry = Math.floor(carry / base);
- }
- return r;
- }
-
- BigInteger.prototype.add = function (v) {
- var value, n = parseValue(v);
- if (this.sign !== n.sign) {
- return this.subtract(n.negate());
- }
- var a = this.value, b = n.value;
- if (n.isSmall) {
- return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
- }
- return new BigInteger(addAny(a, b), this.sign);
- };
- BigInteger.prototype.plus = BigInteger.prototype.add;
-
- SmallInteger.prototype.add = function (v) {
- var n = parseValue(v);
- var a = this.value;
- if (a < 0 !== n.sign) {
- return this.subtract(n.negate());
- }
- var b = n.value;
- if (n.isSmall) {
- if (isPrecise(a + b)) return new SmallInteger(a + b);
- b = smallToArray(Math.abs(b));
- }
- return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
- };
- SmallInteger.prototype.plus = SmallInteger.prototype.add;
-
- function subtract(a, b) { // assumes a and b are arrays with a >= b
- var a_l = a.length,
- b_l = b.length,
- r = new Array(a_l),
- borrow = 0,
- base = BASE,
- i, difference;
- for (i = 0; i < b_l; i++) {
- difference = a[i] - borrow - b[i];
- if (difference < 0) {
- difference += base;
- borrow = 1;
- } else borrow = 0;
- r[i] = difference;
- }
- for (i = b_l; i < a_l; i++) {
- difference = a[i] - borrow;
- if (difference < 0) difference += base;
- else {
- r[i++] = difference;
- break;
- }
- r[i] = difference;
- }
- for (; i < a_l; i++) {
- r[i] = a[i];
- }
- trim(r);
- return r;
- }
-
- function subtractAny(a, b, sign) {
- var value, isSmall;
- if (compareAbs(a, b) >= 0) {
- value = subtract(a,b);
- } else {
- value = subtract(b, a);
- sign = !sign;
- }
- value = arrayToSmall(value);
- if (typeof value === "number") {
- if (sign) value = -value;
- return new SmallInteger(value);
- }
- return new BigInteger(value, sign);
- }
-
- function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT
- var l = a.length,
- r = new Array(l),
- carry = -b,
- base = BASE,
- i, difference;
- for (i = 0; i < l; i++) {
- difference = a[i] + carry;
- carry = Math.floor(difference / base);
- difference %= base;
- r[i] = difference < 0 ? difference + base : difference;
- }
- r = arrayToSmall(r);
- if (typeof r === "number") {
- if (sign) r = -r;
- return new SmallInteger(r);
- } return new BigInteger(r, sign);
- }
-
- BigInteger.prototype.subtract = function (v) {
- var n = parseValue(v);
- if (this.sign !== n.sign) {
- return this.add(n.negate());
- }
- var a = this.value, b = n.value;
- if (n.isSmall)
- return subtractSmall(a, Math.abs(b), this.sign);
- return subtractAny(a, b, this.sign);
- };
- BigInteger.prototype.minus = BigInteger.prototype.subtract;
-
- SmallInteger.prototype.subtract = function (v) {
- var n = parseValue(v);
- var a = this.value;
- if (a < 0 !== n.sign) {
- return this.add(n.negate());
- }
- var b = n.value;
- if (n.isSmall) {
- return new SmallInteger(a - b);
- }
- return subtractSmall(b, Math.abs(a), a >= 0);
- };
- SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
-
- BigInteger.prototype.negate = function () {
- return new BigInteger(this.value, !this.sign);
- };
- SmallInteger.prototype.negate = function () {
- var sign = this.sign;
- var small = new SmallInteger(-this.value);
- small.sign = !sign;
- return small;
- };
-
- BigInteger.prototype.abs = function () {
- return new BigInteger(this.value, false);
- };
- SmallInteger.prototype.abs = function () {
- return new SmallInteger(Math.abs(this.value));
- };
-
- function multiplyLong(a, b) {
- var a_l = a.length,
- b_l = b.length,
- l = a_l + b_l,
- r = createArray(l),
- base = BASE,
- product, carry, i, a_i, b_j;
- for (i = 0; i < a_l; ++i) {
- a_i = a[i];
- for (var j = 0; j < b_l; ++j) {
- b_j = b[j];
- product = a_i * b_j + r[i + j];
- carry = Math.floor(product / base);
- r[i + j] = product - carry * base;
- r[i + j + 1] += carry;
- }
- }
- trim(r);
- return r;
- }
-
- function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE
- var l = a.length,
- r = new Array(l),
- base = BASE,
- carry = 0,
- product, i;
- for (i = 0; i < l; i++) {
- product = a[i] * b + carry;
- carry = Math.floor(product / base);
- r[i] = product - carry * base;
- }
- while (carry > 0) {
- r[i++] = carry % base;
- carry = Math.floor(carry / base);
- }
- return r;
- }
-
- function shiftLeft(x, n) {
- var r = [];
- while (n-- > 0) r.push(0);
- return r.concat(x);
- }
-
- function multiplyKaratsuba(x, y) {
- var n = Math.max(x.length, y.length);
-
- if (n <= 30) return multiplyLong(x, y);
- n = Math.ceil(n / 2);
-
- var b = x.slice(n),
- a = x.slice(0, n),
- d = y.slice(n),
- c = y.slice(0, n);
-
- var ac = multiplyKaratsuba(a, c),
- bd = multiplyKaratsuba(b, d),
- abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
-
- var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
- trim(product);
- return product;
- }
-
- // The following function is derived from a surface fit of a graph plotting the performance difference
- // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.
- function useKaratsuba(l1, l2) {
- return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;
- }
-
- BigInteger.prototype.multiply = function (v) {
- var value, n = parseValue(v),
- a = this.value, b = n.value,
- sign = this.sign !== n.sign,
- abs;
- if (n.isSmall) {
- if (b === 0) return Integer[0];
- if (b === 1) return this;
- if (b === -1) return this.negate();
- abs = Math.abs(b);
- if (abs < BASE) {
- return new BigInteger(multiplySmall(a, abs), sign);
- }
- b = smallToArray(abs);
- }
- if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes
- return new BigInteger(multiplyKaratsuba(a, b), sign);
- return new BigInteger(multiplyLong(a, b), sign);
- };
-
- BigInteger.prototype.times = BigInteger.prototype.multiply;
-
- function multiplySmallAndArray(a, b, sign) { // a >= 0
- if (a < BASE) {
- return new BigInteger(multiplySmall(b, a), sign);
- }
- return new BigInteger(multiplyLong(b, smallToArray(a)), sign);
- }
- SmallInteger.prototype._multiplyBySmall = function (a) {
- if (isPrecise(a.value * this.value)) {
- return new SmallInteger(a.value * this.value);
- }
- return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
- };
- BigInteger.prototype._multiplyBySmall = function (a) {
- if (a.value === 0) return Integer[0];
- if (a.value === 1) return this;
- if (a.value === -1) return this.negate();
- return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
- };
- SmallInteger.prototype.multiply = function (v) {
- return parseValue(v)._multiplyBySmall(this);
- };
- SmallInteger.prototype.times = SmallInteger.prototype.multiply;
-
- function square(a) {
- var l = a.length,
- r = createArray(l + l),
- base = BASE,
- product, carry, i, a_i, a_j;
- for (i = 0; i < l; i++) {
- a_i = a[i];
- for (var j = 0; j < l; j++) {
- a_j = a[j];
- product = a_i * a_j + r[i + j];
- carry = Math.floor(product / base);
- r[i + j] = product - carry * base;
- r[i + j + 1] += carry;
- }
- }
- trim(r);
- return r;
- }
-
- BigInteger.prototype.square = function () {
- return new BigInteger(square(this.value), false);
- };
-
- SmallInteger.prototype.square = function () {
- var value = this.value * this.value;
- if (isPrecise(value)) return new SmallInteger(value);
- return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
- };
-
- function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.
- var a_l = a.length,
- b_l = b.length,
- base = BASE,
- result = createArray(b.length),
- divisorMostSignificantDigit = b[b_l - 1],
- // normalization
- lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),
- remainder = multiplySmall(a, lambda),
- divisor = multiplySmall(b, lambda),
- quotientDigit, shift, carry, borrow, i, l, q;
- if (remainder.length <= a_l) remainder.push(0);
- divisor.push(0);
- divisorMostSignificantDigit = divisor[b_l - 1];
- for (shift = a_l - b_l; shift >= 0; shift--) {
- quotientDigit = base - 1;
- if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
- quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
- }
- // quotientDigit <= base - 1
- carry = 0;
- borrow = 0;
- l = divisor.length;
- for (i = 0; i < l; i++) {
- carry += quotientDigit * divisor[i];
- q = Math.floor(carry / base);
- borrow += remainder[shift + i] - (carry - q * base);
- carry = q;
- if (borrow < 0) {
- remainder[shift + i] = borrow + base;
- borrow = -1;
- } else {
- remainder[shift + i] = borrow;
- borrow = 0;
- }
- }
- while (borrow !== 0) {
- quotientDigit -= 1;
- carry = 0;
- for (i = 0; i < l; i++) {
- carry += remainder[shift + i] - base + divisor[i];
- if (carry < 0) {
- remainder[shift + i] = carry + base;
- carry = 0;
- } else {
- remainder[shift + i] = carry;
- carry = 1;
- }
- }
- borrow += carry;
- }
- result[shift] = quotientDigit;
- }
- // denormalization
- remainder = divModSmall(remainder, lambda)[0];
- return [arrayToSmall(result), arrayToSmall(remainder)];
- }
-
- function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/
- // Performs faster than divMod1 on larger input sizes.
- var a_l = a.length,
- b_l = b.length,
- result = [],
- part = [],
- base = BASE,
- guess, xlen, highx, highy, check;
- while (a_l) {
- part.unshift(a[--a_l]);
- if (compareAbs(part, b) < 0) {
- result.push(0);
- continue;
- }
- xlen = part.length;
- highx = part[xlen - 1] * base + part[xlen - 2];
- highy = b[b_l - 1] * base + b[b_l - 2];
- if (xlen > b_l) {
- highx = (highx + 1) * base;
- }
- guess = Math.ceil(highx / highy);
- do {
- check = multiplySmall(b, guess);
- if (compareAbs(check, part) <= 0) break;
- guess--;
- } while (guess);
- result.push(guess);
- part = subtract(part, check);
- }
- result.reverse();
- return [arrayToSmall(result), arrayToSmall(part)];
- }
-
- function divModSmall(value, lambda) {
- var length = value.length,
- quotient = createArray(length),
- base = BASE,
- i, q, remainder, divisor;
- remainder = 0;
- for (i = length - 1; i >= 0; --i) {
- divisor = remainder * base + value[i];
- q = truncate(divisor / lambda);
- remainder = divisor - q * lambda;
- quotient[i] = q | 0;
- }
- return [quotient, remainder | 0];
- }
-
- function divModAny(self, v) {
- var value, n = parseValue(v);
- var a = self.value, b = n.value;
- var quotient;
- if (b === 0) throw new Error("Cannot divide by zero");
- if (self.isSmall) {
- if (n.isSmall) {
- return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
- }
- return [Integer[0], self];
- }
- if (n.isSmall) {
- if (b === 1) return [self, Integer[0]];
- if (b == -1) return [self.negate(), Integer[0]];
- var abs = Math.abs(b);
- if (abs < BASE) {
- value = divModSmall(a, abs);
- quotient = arrayToSmall(value[0]);
- var remainder = value[1];
- if (self.sign) remainder = -remainder;
- if (typeof quotient === "number") {
- if (self.sign !== n.sign) quotient = -quotient;
- return [new SmallInteger(quotient), new SmallInteger(remainder)];
- }
- return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];
- }
- b = smallToArray(abs);
- }
- var comparison = compareAbs(a, b);
- if (comparison === -1) return [Integer[0], self];
- if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];
-
- // divMod1 is faster on smaller input sizes
- if (a.length + b.length <= 200)
- value = divMod1(a, b);
- else value = divMod2(a, b);
-
- quotient = value[0];
- var qSign = self.sign !== n.sign,
- mod = value[1],
- mSign = self.sign;
- if (typeof quotient === "number") {
- if (qSign) quotient = -quotient;
- quotient = new SmallInteger(quotient);
- } else quotient = new BigInteger(quotient, qSign);
- if (typeof mod === "number") {
- if (mSign) mod = -mod;
- mod = new SmallInteger(mod);
- } else mod = new BigInteger(mod, mSign);
- return [quotient, mod];
- }
-
- BigInteger.prototype.divmod = function (v) {
- var result = divModAny(this, v);
- return {
- quotient: result[0],
- remainder: result[1]
- };
- };
- SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
-
- BigInteger.prototype.divide = function (v) {
- return divModAny(this, v)[0];
- };
- SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
-
- BigInteger.prototype.mod = function (v) {
- return divModAny(this, v)[1];
- };
- SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
-
- BigInteger.prototype.pow = function (v) {
- var n = parseValue(v),
- a = this.value,
- b = n.value,
- value, x, y;
- if (b === 0) return Integer[1];
- if (a === 0) return Integer[0];
- if (a === 1) return Integer[1];
- if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];
- if (n.sign) {
- return Integer[0];
- }
- if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");
- if (this.isSmall) {
- if (isPrecise(value = Math.pow(a, b)))
- return new SmallInteger(truncate(value));
- }
- x = this;
- y = Integer[1];
- while (true) {
- if (b & 1 === 1) {
- y = y.times(x);
- --b;
- }
- if (b === 0) break;
- b /= 2;
- x = x.square();
- }
- return y;
- };
- SmallInteger.prototype.pow = BigInteger.prototype.pow;
-
- BigInteger.prototype.modPow = function (exp, mod) {
- exp = parseValue(exp);
- mod = parseValue(mod);
- if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");
- var r = Integer[1],
- base = this.mod(mod);
- while (exp.isPositive()) {
- if (base.isZero()) return Integer[0];
- if (exp.isOdd()) r = r.multiply(base).mod(mod);
- exp = exp.divide(2);
- base = base.square().mod(mod);
- }
- return r;
- };
- SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
-
- function compareAbs(a, b) {
- if (a.length !== b.length) {
- return a.length > b.length ? 1 : -1;
- }
- for (var i = a.length - 1; i >= 0; i--) {
- if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
- }
- return 0;
- }
-
- BigInteger.prototype.compareAbs = function (v) {
- var n = parseValue(v),
- a = this.value,
- b = n.value;
- if (n.isSmall) return 1;
- return compareAbs(a, b);
- };
- SmallInteger.prototype.compareAbs = function (v) {
- var n = parseValue(v),
- a = Math.abs(this.value),
- b = n.value;
- if (n.isSmall) {
- b = Math.abs(b);
- return a === b ? 0 : a > b ? 1 : -1;
- }
- return -1;
- };
-
- BigInteger.prototype.compare = function (v) {
- // See discussion about comparison with Infinity:
- // https://github.com/peterolson/BigInteger.js/issues/61
- if (v === Infinity) {
- return -1;
- }
- if (v === -Infinity) {
- return 1;
- }
-
- var n = parseValue(v),
- a = this.value,
- b = n.value;
- if (this.sign !== n.sign) {
- return n.sign ? 1 : -1;
- }
- if (n.isSmall) {
- return this.sign ? -1 : 1;
- }
- return compareAbs(a, b) * (this.sign ? -1 : 1);
- };
- BigInteger.prototype.compareTo = BigInteger.prototype.compare;
-
- SmallInteger.prototype.compare = function (v) {
- if (v === Infinity) {
- return -1;
- }
- if (v === -Infinity) {
- return 1;
- }
-
- var n = parseValue(v),
- a = this.value,
- b = n.value;
- if (n.isSmall) {
- return a == b ? 0 : a > b ? 1 : -1;
- }
- if (a < 0 !== n.sign) {
- return a < 0 ? -1 : 1;
- }
- return a < 0 ? 1 : -1;
- };
- SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
-
- BigInteger.prototype.equals = function (v) {
- return this.compare(v) === 0;
- };
- SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
-
- BigInteger.prototype.notEquals = function (v) {
- return this.compare(v) !== 0;
- };
- SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
-
- BigInteger.prototype.greater = function (v) {
- return this.compare(v) > 0;
- };
- SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
-
- BigInteger.prototype.lesser = function (v) {
- return this.compare(v) < 0;
- };
- SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
-
- BigInteger.prototype.greaterOrEquals = function (v) {
- return this.compare(v) >= 0;
- };
- SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
-
- BigInteger.prototype.lesserOrEquals = function (v) {
- return this.compare(v) <= 0;
- };
- SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
-
- BigInteger.prototype.isEven = function () {
- return (this.value[0] & 1) === 0;
- };
- SmallInteger.prototype.isEven = function () {
- return (this.value & 1) === 0;
- };
-
- BigInteger.prototype.isOdd = function () {
- return (this.value[0] & 1) === 1;
- };
- SmallInteger.prototype.isOdd = function () {
- return (this.value & 1) === 1;
- };
-
- BigInteger.prototype.isPositive = function () {
- return !this.sign;
- };
- SmallInteger.prototype.isPositive = function () {
- return this.value > 0;
- };
-
- BigInteger.prototype.isNegative = function () {
- return this.sign;
- };
- SmallInteger.prototype.isNegative = function () {
- return this.value < 0;
- };
-
- BigInteger.prototype.isUnit = function () {
- return false;
- };
- SmallInteger.prototype.isUnit = function () {
- return Math.abs(this.value) === 1;
- };
-
- BigInteger.prototype.isZero = function () {
- return false;
- };
- SmallInteger.prototype.isZero = function () {
- return this.value === 0;
- };
- BigInteger.prototype.isDivisibleBy = function (v) {
- var n = parseValue(v);
- var value = n.value;
- if (value === 0) return false;
- if (value === 1) return true;
- if (value === 2) return this.isEven();
- return this.mod(n).equals(Integer[0]);
- };
- SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
-
- function isBasicPrime(v) {
- var n = v.abs();
- if (n.isUnit()) return false;
- if (n.equals(2) || n.equals(3) || n.equals(5)) return true;
- if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;
- if (n.lesser(25)) return true;
- // we don't know if it's prime: let the other functions figure it out
- }
-
- BigInteger.prototype.isPrime = function () {
- var isPrime = isBasicPrime(this);
- if (isPrime !== undefined) return isPrime;
- var n = this.abs(),
- nPrev = n.prev();
- var a = [2, 3, 5, 7, 11, 13, 17, 19],
- b = nPrev,
- d, t, i, x;
- while (b.isEven()) b = b.divide(2);
- for (i = 0; i < a.length; i++) {
- x = bigInt(a[i]).modPow(b, n);
- if (x.equals(Integer[1]) || x.equals(nPrev)) continue;
- for (t = true, d = b; t && d.lesser(nPrev) ; d = d.multiply(2)) {
- x = x.square().mod(n);
- if (x.equals(nPrev)) t = false;
- }
- if (t) return false;
- }
- return true;
- };
- SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
-
- BigInteger.prototype.isProbablePrime = function (iterations) {
- var isPrime = isBasicPrime(this);
- if (isPrime !== undefined) return isPrime;
- var n = this.abs();
- var t = iterations === undefined ? 5 : iterations;
- // use the Fermat primality test
- for (var i = 0; i < t; i++) {
- var a = bigInt.randBetween(2, n.minus(2));
- if (!a.modPow(n.prev(), n).isUnit()) return false; // definitely composite
- }
- return true; // large chance of being prime
- };
- SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
-
- BigInteger.prototype.modInv = function (n) {
- var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;
- while (!newR.equals(bigInt.zero)) {
- q = r.divide(newR);
- lastT = t;
- lastR = r;
- t = newT;
- r = newR;
- newT = lastT.subtract(q.multiply(newT));
- newR = lastR.subtract(q.multiply(newR));
- }
- if (!r.equals(1)) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");
- if (t.compare(0) === -1) {
- t = t.add(n);
- }
- return t;
- }
- SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
-
- BigInteger.prototype.next = function () {
- var value = this.value;
- if (this.sign) {
- return subtractSmall(value, 1, this.sign);
- }
- return new BigInteger(addSmall(value, 1), this.sign);
- };
- SmallInteger.prototype.next = function () {
- var value = this.value;
- if (value + 1 < MAX_INT) return new SmallInteger(value + 1);
- return new BigInteger(MAX_INT_ARR, false);
- };
-
- BigInteger.prototype.prev = function () {
- var value = this.value;
- if (this.sign) {
- return new BigInteger(addSmall(value, 1), true);
- }
- return subtractSmall(value, 1, this.sign);
- };
- SmallInteger.prototype.prev = function () {
- var value = this.value;
- if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);
- return new BigInteger(MAX_INT_ARR, true);
- };
-
- var powersOfTwo = [1];
- while (powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
- var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
-
- function shift_isSmall(n) {
- return ((typeof n === "number" || typeof n === "string") && +Math.abs(n) <= BASE) ||
- (n instanceof BigInteger && n.value.length <= 1);
- }
-
- BigInteger.prototype.shiftLeft = function (n) {
- if (!shift_isSmall(n)) {
- throw new Error(String(n) + " is too large for shifting.");
- }
- n = +n;
- if (n < 0) return this.shiftRight(-n);
- var result = this;
- while (n >= powers2Length) {
- result = result.multiply(highestPower2);
- n -= powers2Length - 1;
- }
- return result.multiply(powersOfTwo[n]);
- };
- SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
-
- BigInteger.prototype.shiftRight = function (n) {
- var remQuo;
- if (!shift_isSmall(n)) {
- throw new Error(String(n) + " is too large for shifting.");
- }
- n = +n;
- if (n < 0) return this.shiftLeft(-n);
- var result = this;
- while (n >= powers2Length) {
- if (result.isZero()) return result;
- remQuo = divModAny(result, highestPower2);
- result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
- n -= powers2Length - 1;
- }
- remQuo = divModAny(result, powersOfTwo[n]);
- return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
- };
- SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
-
- function bitwise(x, y, fn) {
- y = parseValue(y);
- var xSign = x.isNegative(), ySign = y.isNegative();
- var xRem = xSign ? x.not() : x,
- yRem = ySign ? y.not() : y;
- var xBits = [], yBits = [];
- var xStop = false, yStop = false;
- while (!xStop || !yStop) {
- if (xRem.isZero()) { // virtual sign extension for simulating two's complement
- xStop = true;
- xBits.push(xSign ? 1 : 0);
- }
- else if (xSign) xBits.push(xRem.isEven() ? 1 : 0); // two's complement for negative numbers
- else xBits.push(xRem.isEven() ? 0 : 1);
-
- if (yRem.isZero()) {
- yStop = true;
- yBits.push(ySign ? 1 : 0);
- }
- else if (ySign) yBits.push(yRem.isEven() ? 1 : 0);
- else yBits.push(yRem.isEven() ? 0 : 1);
-
- xRem = xRem.over(2);
- yRem = yRem.over(2);
- }
- var result = [];
- for (var i = 0; i < xBits.length; i++) result.push(fn(xBits[i], yBits[i]));
- var sum = bigInt(result.pop()).negate().times(bigInt(2).pow(result.length));
- while (result.length) {
- sum = sum.add(bigInt(result.pop()).times(bigInt(2).pow(result.length)));
- }
- return sum;
- }
-
- BigInteger.prototype.not = function () {
- return this.negate().prev();
- };
- SmallInteger.prototype.not = BigInteger.prototype.not;
-
- BigInteger.prototype.and = function (n) {
- return bitwise(this, n, function (a, b) { return a & b; });
- };
- SmallInteger.prototype.and = BigInteger.prototype.and;
-
- BigInteger.prototype.or = function (n) {
- return bitwise(this, n, function (a, b) { return a | b; });
- };
- SmallInteger.prototype.or = BigInteger.prototype.or;
-
- BigInteger.prototype.xor = function (n) {
- return bitwise(this, n, function (a, b) { return a ^ b; });
- };
- SmallInteger.prototype.xor = BigInteger.prototype.xor;
-
- var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
- function roughLOB(n) { // get lowestOneBit (rough)
- // SmallInteger: return Min(lowestOneBit(n), 1 << 30)
- // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]
- var v = n.value, x = typeof v === "number" ? v | LOBMASK_I : v[0] + v[1] * BASE | LOBMASK_BI;
- return x & -x;
- }
-
- function max(a, b) {
- a = parseValue(a);
- b = parseValue(b);
- return a.greater(b) ? a : b;
- }
- function min(a,b) {
- a = parseValue(a);
- b = parseValue(b);
- return a.lesser(b) ? a : b;
- }
- function gcd(a, b) {
- a = parseValue(a).abs();
- b = parseValue(b).abs();
- if (a.equals(b)) return a;
- if (a.isZero()) return b;
- if (b.isZero()) return a;
- var c = Integer[1], d, t;
- while (a.isEven() && b.isEven()) {
- d = Math.min(roughLOB(a), roughLOB(b));
- a = a.divide(d);
- b = b.divide(d);
- c = c.multiply(d);
- }
- while (a.isEven()) {
- a = a.divide(roughLOB(a));
- }
- do {
- while (b.isEven()) {
- b = b.divide(roughLOB(b));
- }
- if (a.greater(b)) {
- t = b; b = a; a = t;
- }
- b = b.subtract(a);
- } while (!b.isZero());
- return c.isUnit() ? a : a.multiply(c);
- }
- function lcm(a, b) {
- a = parseValue(a).abs();
- b = parseValue(b).abs();
- return a.divide(gcd(a, b)).multiply(b);
- }
- function randBetween(a, b) {
- a = parseValue(a);
- b = parseValue(b);
- var low = min(a, b), high = max(a, b);
- var range = high.subtract(low);
- if (range.isSmall) return low.add(Math.round(Math.random() * range));
- var length = range.value.length - 1;
- var result = [], restricted = true;
- for (var i = length; i >= 0; i--) {
- var top = restricted ? range.value[i] : BASE;
- var digit = truncate(Math.random() * top);
- result.unshift(digit);
- if (digit < top) restricted = false;
- }
- result = arrayToSmall(result);
- return low.add(typeof result === "number" ? new SmallInteger(result) : new BigInteger(result, false));
- }
- var parseBase = function (text, base) {
- var val = Integer[0], pow = Integer[1],
- length = text.length;
- if (2 <= base && base <= 36) {
- if (length <= LOG_MAX_INT / Math.log(base)) {
- return new SmallInteger(parseInt(text, base));
- }
- }
- base = parseValue(base);
- var digits = [];
- var i;
- var isNegative = text[0] === "-";
- for (i = isNegative ? 1 : 0; i < text.length; i++) {
- var c = text[i].toLowerCase(),
- charCode = c.charCodeAt(0);
- if (48 <= charCode && charCode <= 57) digits.push(parseValue(c));
- else if (97 <= charCode && charCode <= 122) digits.push(parseValue(c.charCodeAt(0) - 87));
- else if (c === "<") {
- var start = i;
- do { i++; } while (text[i] !== ">");
- digits.push(parseValue(text.slice(start + 1, i)));
- }
- else throw new Error(c + " is not a valid character");
- }
- digits.reverse();
- for (i = 0; i < digits.length; i++) {
- val = val.add(digits[i].times(pow));
- pow = pow.times(base);
- }
- return isNegative ? val.negate() : val;
- };
-
- function stringify(digit) {
- var v = digit.value;
- if (typeof v === "number") v = [v];
- if (v.length === 1 && v[0] <= 35) {
- return "0123456789abcdefghijklmnopqrstuvwxyz".charAt(v[0]);
- }
- return "<" + v + ">";
- }
- function toBase(n, base) {
- base = bigInt(base);
- if (base.isZero()) {
- if (n.isZero()) return "0";
- throw new Error("Cannot convert nonzero numbers to base 0.");
- }
- if (base.equals(-1)) {
- if (n.isZero()) return "0";
- if (n.isNegative()) return new Array(1 - n).join("10");
- return "1" + new Array(+n).join("01");
- }
- var minusSign = "";
- if (n.isNegative() && base.isPositive()) {
- minusSign = "-";
- n = n.abs();
- }
- if (base.equals(1)) {
- if (n.isZero()) return "0";
- return minusSign + new Array(+n + 1).join(1);
- }
- var out = [];
- var left = n, divmod;
- while (left.isNegative() || left.compareAbs(base) >= 0) {
- divmod = left.divmod(base);
- left = divmod.quotient;
- var digit = divmod.remainder;
- if (digit.isNegative()) {
- digit = base.minus(digit).abs();
- left = left.next();
- }
- out.push(stringify(digit));
- }
- out.push(stringify(left));
- return minusSign + out.reverse().join("");
- }
-
- BigInteger.prototype.toString = function (radix) {
- if (radix === undefined) radix = 10;
- if (radix !== 10) return toBase(this, radix);
- var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
- while (--l >= 0) {
- digit = String(v[l]);
- str += zeros.slice(digit.length) + digit;
- }
- var sign = this.sign ? "-" : "";
- return sign + str;
- };
- SmallInteger.prototype.toString = function (radix) {
- if (radix === undefined) radix = 10;
- if (radix != 10) return toBase(this, radix);
- return String(this.value);
- };
-
- BigInteger.prototype.valueOf = function () {
- return +this.toString();
- };
- BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
-
- SmallInteger.prototype.valueOf = function () {
- return this.value;
- };
- SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
-
- function parseStringValue(v) {
- if (isPrecise(+v)) {
- var x = +v;
- if (x === truncate(x))
- return new SmallInteger(x);
- throw "Invalid integer: " + v;
- }
- var sign = v[0] === "-";
- if (sign) v = v.slice(1);
- var split = v.split(/e/i);
- if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));
- if (split.length === 2) {
- var exp = split[1];
- if (exp[0] === "+") exp = exp.slice(1);
- exp = +exp;
- if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
- var text = split[0];
- var decimalPlace = text.indexOf(".");
- if (decimalPlace >= 0) {
- exp -= text.length - decimalPlace - 1;
- text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
- }
- if (exp < 0) throw new Error("Cannot include negative exponent part for integers");
- text += (new Array(exp + 1)).join("0");
- v = text;
- }
- var isValid = /^([0-9][0-9]*)$/.test(v);
- if (!isValid) throw new Error("Invalid integer: " + v);
- var r = [], max = v.length, l = LOG_BASE, min = max - l;
- while (max > 0) {
- r.push(+v.slice(min, max));
- min -= l;
- if (min < 0) min = 0;
- max -= l;
- }
- trim(r);
- return new BigInteger(r, sign);
- }
-
- function parseNumberValue(v) {
- if (isPrecise(v)) {
- if (v !== truncate(v)) throw new Error(v + " is not an integer.");
- return new SmallInteger(v);
- }
- return parseStringValue(v.toString());
- }
-
- function parseValue(v) {
- if (typeof v === "number") {
- return parseNumberValue(v);
- }
- if (typeof v === "string") {
- return parseStringValue(v);
- }
- return v;
- }
- // Pre-define numbers in range [-999,999]
- for (var i = 0; i < 1000; i++) {
- Integer[i] = new SmallInteger(i);
- if (i > 0) Integer[-i] = new SmallInteger(-i);
- }
- // Backwards compatibility
- Integer.one = Integer[1];
- Integer.zero = Integer[0];
- Integer.minusOne = Integer[-1];
- Integer.max = max;
- Integer.min = min;
- Integer.gcd = gcd;
- Integer.lcm = lcm;
- Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger; };
- Integer.randBetween = randBetween;
- return Integer;
- })();
-
- // Node.js check
- if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
- module.exports = bigInt;
- }
-
- },{}],4:[function(require,module,exports){
- (function (process,global){
- /* @preserve
- * The MIT License (MIT)
- *
- * Copyright (c) 2013-2015 Petka Antonov
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- */
- /**
- * bluebird build version 3.4.6
- * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
- */
- !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise) {
- var SomePromiseArray = Promise._SomePromiseArray;
- function any(promises) {
- var ret = new SomePromiseArray(promises);
- var promise = ret.promise();
- ret.setHowMany(1);
- ret.setUnwrap();
- ret.init();
- return promise;
- }
-
- Promise.any = function (promises) {
- return any(promises);
- };
-
- Promise.prototype.any = function () {
- return any(this);
- };
-
- };
-
- },{}],2:[function(_dereq_,module,exports){
- "use strict";
- var firstLineError;
- try {throw new Error(); } catch (e) {firstLineError = e;}
- var schedule = _dereq_("./schedule");
- var Queue = _dereq_("./queue");
- var util = _dereq_("./util");
-
- function Async() {
- this._customScheduler = false;
- this._isTickUsed = false;
- this._lateQueue = new Queue(16);
- this._normalQueue = new Queue(16);
- this._haveDrainedQueues = false;
- this._trampolineEnabled = true;
- var self = this;
- this.drainQueues = function () {
- self._drainQueues();
- };
- this._schedule = schedule;
- }
-
- Async.prototype.setScheduler = function(fn) {
- var prev = this._schedule;
- this._schedule = fn;
- this._customScheduler = true;
- return prev;
- };
-
- Async.prototype.hasCustomScheduler = function() {
- return this._customScheduler;
- };
-
- Async.prototype.enableTrampoline = function() {
- this._trampolineEnabled = true;
- };
-
- Async.prototype.disableTrampolineIfNecessary = function() {
- if (util.hasDevTools) {
- this._trampolineEnabled = false;
- }
- };
-
- Async.prototype.haveItemsQueued = function () {
- return this._isTickUsed || this._haveDrainedQueues;
- };
-
-
- Async.prototype.fatalError = function(e, isNode) {
- if (isNode) {
- process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
- "\n");
- process.exit(2);
- } else {
- this.throwLater(e);
- }
- };
-
- Async.prototype.throwLater = function(fn, arg) {
- if (arguments.length === 1) {
- arg = fn;
- fn = function () { throw arg; };
- }
- if (typeof setTimeout !== "undefined") {
- setTimeout(function() {
- fn(arg);
- }, 0);
- } else try {
- this._schedule(function() {
- fn(arg);
- });
- } catch (e) {
- throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- };
-
- function AsyncInvokeLater(fn, receiver, arg) {
- this._lateQueue.push(fn, receiver, arg);
- this._queueTick();
- }
-
- function AsyncInvoke(fn, receiver, arg) {
- this._normalQueue.push(fn, receiver, arg);
- this._queueTick();
- }
-
- function AsyncSettlePromises(promise) {
- this._normalQueue._pushOne(promise);
- this._queueTick();
- }
-
- if (!util.hasDevTools) {
- Async.prototype.invokeLater = AsyncInvokeLater;
- Async.prototype.invoke = AsyncInvoke;
- Async.prototype.settlePromises = AsyncSettlePromises;
- } else {
- Async.prototype.invokeLater = function (fn, receiver, arg) {
- if (this._trampolineEnabled) {
- AsyncInvokeLater.call(this, fn, receiver, arg);
- } else {
- this._schedule(function() {
- setTimeout(function() {
- fn.call(receiver, arg);
- }, 100);
- });
- }
- };
-
- Async.prototype.invoke = function (fn, receiver, arg) {
- if (this._trampolineEnabled) {
- AsyncInvoke.call(this, fn, receiver, arg);
- } else {
- this._schedule(function() {
- fn.call(receiver, arg);
- });
- }
- };
-
- Async.prototype.settlePromises = function(promise) {
- if (this._trampolineEnabled) {
- AsyncSettlePromises.call(this, promise);
- } else {
- this._schedule(function() {
- promise._settlePromises();
- });
- }
- };
- }
-
- Async.prototype.invokeFirst = function (fn, receiver, arg) {
- this._normalQueue.unshift(fn, receiver, arg);
- this._queueTick();
- };
-
- Async.prototype._drainQueue = function(queue) {
- while (queue.length() > 0) {
- var fn = queue.shift();
- if (typeof fn !== "function") {
- fn._settlePromises();
- continue;
- }
- var receiver = queue.shift();
- var arg = queue.shift();
- fn.call(receiver, arg);
- }
- };
-
- Async.prototype._drainQueues = function () {
- this._drainQueue(this._normalQueue);
- this._reset();
- this._haveDrainedQueues = true;
- this._drainQueue(this._lateQueue);
- };
-
- Async.prototype._queueTick = function () {
- if (!this._isTickUsed) {
- this._isTickUsed = true;
- this._schedule(this.drainQueues);
- }
- };
-
- Async.prototype._reset = function () {
- this._isTickUsed = false;
- };
-
- module.exports = Async;
- module.exports.firstLineError = firstLineError;
-
- },{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
- var calledBind = false;
- var rejectThis = function(_, e) {
- this._reject(e);
- };
-
- var targetRejected = function(e, context) {
- context.promiseRejectionQueued = true;
- context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
- };
-
- var bindingResolved = function(thisArg, context) {
- if (((this._bitField & 50397184) === 0)) {
- this._resolveCallback(context.target);
- }
- };
-
- var bindingRejected = function(e, context) {
- if (!context.promiseRejectionQueued) this._reject(e);
- };
-
- Promise.prototype.bind = function (thisArg) {
- if (!calledBind) {
- calledBind = true;
- Promise.prototype._propagateFrom = debug.propagateFromFunction();
- Promise.prototype._boundValue = debug.boundValueFunction();
- }
- var maybePromise = tryConvertToPromise(thisArg);
- var ret = new Promise(INTERNAL);
- ret._propagateFrom(this, 1);
- var target = this._target();
- ret._setBoundTo(maybePromise);
- if (maybePromise instanceof Promise) {
- var context = {
- promiseRejectionQueued: false,
- promise: ret,
- target: target,
- bindingPromise: maybePromise
- };
- target._then(INTERNAL, targetRejected, undefined, ret, context);
- maybePromise._then(
- bindingResolved, bindingRejected, undefined, ret, context);
- ret._setOnCancel(maybePromise);
- } else {
- ret._resolveCallback(target);
- }
- return ret;
- };
-
- Promise.prototype._setBoundTo = function (obj) {
- if (obj !== undefined) {
- this._bitField = this._bitField | 2097152;
- this._boundTo = obj;
- } else {
- this._bitField = this._bitField & (~2097152);
- }
- };
-
- Promise.prototype._isBound = function () {
- return (this._bitField & 2097152) === 2097152;
- };
-
- Promise.bind = function (thisArg, value) {
- return Promise.resolve(value).bind(thisArg);
- };
- };
-
- },{}],4:[function(_dereq_,module,exports){
- "use strict";
- var old;
- if (typeof Promise !== "undefined") old = Promise;
- function noConflict() {
- try { if (Promise === bluebird) Promise = old; }
- catch (e) {}
- return bluebird;
- }
- var bluebird = _dereq_("./promise")();
- bluebird.noConflict = noConflict;
- module.exports = bluebird;
-
- },{"./promise":22}],5:[function(_dereq_,module,exports){
- "use strict";
- var cr = Object.create;
- if (cr) {
- var callerCache = cr(null);
- var getterCache = cr(null);
- callerCache[" size"] = getterCache[" size"] = 0;
- }
-
- module.exports = function(Promise) {
- var util = _dereq_("./util");
- var canEvaluate = util.canEvaluate;
- var isIdentifier = util.isIdentifier;
-
- var getMethodCaller;
- var getGetter;
- if (!true) {
- var makeMethodCaller = function (methodName) {
- return new Function("ensureMethod", " \n\
- return function(obj) { \n\
- 'use strict' \n\
- var len = this.length; \n\
- ensureMethod(obj, 'methodName'); \n\
- switch(len) { \n\
- case 1: return obj.methodName(this[0]); \n\
- case 2: return obj.methodName(this[0], this[1]); \n\
- case 3: return obj.methodName(this[0], this[1], this[2]); \n\
- case 0: return obj.methodName(); \n\
- default: \n\
- return obj.methodName.apply(obj, this); \n\
- } \n\
- }; \n\
- ".replace(/methodName/g, methodName))(ensureMethod);
- };
-
- var makeGetter = function (propertyName) {
- return new Function("obj", " \n\
- 'use strict'; \n\
- return obj.propertyName; \n\
- ".replace("propertyName", propertyName));
- };
-
- var getCompiled = function(name, compiler, cache) {
- var ret = cache[name];
- if (typeof ret !== "function") {
- if (!isIdentifier(name)) {
- return null;
- }
- ret = compiler(name);
- cache[name] = ret;
- cache[" size"]++;
- if (cache[" size"] > 512) {
- var keys = Object.keys(cache);
- for (var i = 0; i < 256; ++i) delete cache[keys[i]];
- cache[" size"] = keys.length - 256;
- }
- }
- return ret;
- };
-
- getMethodCaller = function(name) {
- return getCompiled(name, makeMethodCaller, callerCache);
- };
-
- getGetter = function(name) {
- return getCompiled(name, makeGetter, getterCache);
- };
- }
-
- function ensureMethod(obj, methodName) {
- var fn;
- if (obj != null) fn = obj[methodName];
- if (typeof fn !== "function") {
- var message = "Object " + util.classString(obj) + " has no method '" +
- util.toString(methodName) + "'";
- throw new Promise.TypeError(message);
- }
- return fn;
- }
-
- function caller(obj) {
- var methodName = this.pop();
- var fn = ensureMethod(obj, methodName);
- return fn.apply(obj, this);
- }
- Promise.prototype.call = function (methodName) {
- var args = [].slice.call(arguments, 1);;
- if (!true) {
- if (canEvaluate) {
- var maybeCaller = getMethodCaller(methodName);
- if (maybeCaller !== null) {
- return this._then(
- maybeCaller, undefined, undefined, args, undefined);
- }
- }
- }
- args.push(methodName);
- return this._then(caller, undefined, undefined, args, undefined);
- };
-
- function namedGetter(obj) {
- return obj[this];
- }
- function indexedGetter(obj) {
- var index = +this;
- if (index < 0) index = Math.max(0, index + obj.length);
- return obj[index];
- }
- Promise.prototype.get = function (propertyName) {
- var isIndex = (typeof propertyName === "number");
- var getter;
- if (!isIndex) {
- if (canEvaluate) {
- var maybeGetter = getGetter(propertyName);
- getter = maybeGetter !== null ? maybeGetter : namedGetter;
- } else {
- getter = namedGetter;
- }
- } else {
- getter = indexedGetter;
- }
- return this._then(getter, undefined, undefined, propertyName, undefined);
- };
- };
-
- },{"./util":36}],6:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, PromiseArray, apiRejection, debug) {
- var util = _dereq_("./util");
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- var async = Promise._async;
-
- Promise.prototype["break"] = Promise.prototype.cancel = function() {
- if (!debug.cancellation()) return this._warn("cancellation is disabled");
-
- var promise = this;
- var child = promise;
- while (promise._isCancellable()) {
- if (!promise._cancelBy(child)) {
- if (child._isFollowing()) {
- child._followee().cancel();
- } else {
- child._cancelBranched();
- }
- break;
- }
-
- var parent = promise._cancellationParent;
- if (parent == null || !parent._isCancellable()) {
- if (promise._isFollowing()) {
- promise._followee().cancel();
- } else {
- promise._cancelBranched();
- }
- break;
- } else {
- if (promise._isFollowing()) promise._followee().cancel();
- promise._setWillBeCancelled();
- child = promise;
- promise = parent;
- }
- }
- };
-
- Promise.prototype._branchHasCancelled = function() {
- this._branchesRemainingToCancel--;
- };
-
- Promise.prototype._enoughBranchesHaveCancelled = function() {
- return this._branchesRemainingToCancel === undefined ||
- this._branchesRemainingToCancel <= 0;
- };
-
- Promise.prototype._cancelBy = function(canceller) {
- if (canceller === this) {
- this._branchesRemainingToCancel = 0;
- this._invokeOnCancel();
- return true;
- } else {
- this._branchHasCancelled();
- if (this._enoughBranchesHaveCancelled()) {
- this._invokeOnCancel();
- return true;
- }
- }
- return false;
- };
-
- Promise.prototype._cancelBranched = function() {
- if (this._enoughBranchesHaveCancelled()) {
- this._cancel();
- }
- };
-
- Promise.prototype._cancel = function() {
- if (!this._isCancellable()) return;
- this._setCancelled();
- async.invoke(this._cancelPromises, this, undefined);
- };
-
- Promise.prototype._cancelPromises = function() {
- if (this._length() > 0) this._settlePromises();
- };
-
- Promise.prototype._unsetOnCancel = function() {
- this._onCancelField = undefined;
- };
-
- Promise.prototype._isCancellable = function() {
- return this.isPending() && !this._isCancelled();
- };
-
- Promise.prototype.isCancellable = function() {
- return this.isPending() && !this.isCancelled();
- };
-
- Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
- if (util.isArray(onCancelCallback)) {
- for (var i = 0; i < onCancelCallback.length; ++i) {
- this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
- }
- } else if (onCancelCallback !== undefined) {
- if (typeof onCancelCallback === "function") {
- if (!internalOnly) {
- var e = tryCatch(onCancelCallback).call(this._boundValue());
- if (e === errorObj) {
- this._attachExtraTrace(e.e);
- async.throwLater(e.e);
- }
- }
- } else {
- onCancelCallback._resultCancelled(this);
- }
- }
- };
-
- Promise.prototype._invokeOnCancel = function() {
- var onCancelCallback = this._onCancel();
- this._unsetOnCancel();
- async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
- };
-
- Promise.prototype._invokeInternalOnCancel = function() {
- if (this._isCancellable()) {
- this._doInvokeOnCancel(this._onCancel(), true);
- this._unsetOnCancel();
- }
- };
-
- Promise.prototype._resultCancelled = function() {
- this.cancel();
- };
-
- };
-
- },{"./util":36}],7:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(NEXT_FILTER) {
- var util = _dereq_("./util");
- var getKeys = _dereq_("./es5").keys;
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
-
- function catchFilter(instances, cb, promise) {
- return function(e) {
- var boundTo = promise._boundValue();
- predicateLoop: for (var i = 0; i < instances.length; ++i) {
- var item = instances[i];
-
- if (item === Error ||
- (item != null && item.prototype instanceof Error)) {
- if (e instanceof item) {
- return tryCatch(cb).call(boundTo, e);
- }
- } else if (typeof item === "function") {
- var matchesPredicate = tryCatch(item).call(boundTo, e);
- if (matchesPredicate === errorObj) {
- return matchesPredicate;
- } else if (matchesPredicate) {
- return tryCatch(cb).call(boundTo, e);
- }
- } else if (util.isObject(e)) {
- var keys = getKeys(item);
- for (var j = 0; j < keys.length; ++j) {
- var key = keys[j];
- if (item[key] != e[key]) {
- continue predicateLoop;
- }
- }
- return tryCatch(cb).call(boundTo, e);
- }
- }
- return NEXT_FILTER;
- };
- }
-
- return catchFilter;
- };
-
- },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise) {
- var longStackTraces = false;
- var contextStack = [];
-
- Promise.prototype._promiseCreated = function() {};
- Promise.prototype._pushContext = function() {};
- Promise.prototype._popContext = function() {return null;};
- Promise._peekContext = Promise.prototype._peekContext = function() {};
-
- function Context() {
- this._trace = new Context.CapturedTrace(peekContext());
- }
- Context.prototype._pushContext = function () {
- if (this._trace !== undefined) {
- this._trace._promiseCreated = null;
- contextStack.push(this._trace);
- }
- };
-
- Context.prototype._popContext = function () {
- if (this._trace !== undefined) {
- var trace = contextStack.pop();
- var ret = trace._promiseCreated;
- trace._promiseCreated = null;
- return ret;
- }
- return null;
- };
-
- function createContext() {
- if (longStackTraces) return new Context();
- }
-
- function peekContext() {
- var lastIndex = contextStack.length - 1;
- if (lastIndex >= 0) {
- return contextStack[lastIndex];
- }
- return undefined;
- }
- Context.CapturedTrace = null;
- Context.create = createContext;
- Context.deactivateLongStackTraces = function() {};
- Context.activateLongStackTraces = function() {
- var Promise_pushContext = Promise.prototype._pushContext;
- var Promise_popContext = Promise.prototype._popContext;
- var Promise_PeekContext = Promise._peekContext;
- var Promise_peekContext = Promise.prototype._peekContext;
- var Promise_promiseCreated = Promise.prototype._promiseCreated;
- Context.deactivateLongStackTraces = function() {
- Promise.prototype._pushContext = Promise_pushContext;
- Promise.prototype._popContext = Promise_popContext;
- Promise._peekContext = Promise_PeekContext;
- Promise.prototype._peekContext = Promise_peekContext;
- Promise.prototype._promiseCreated = Promise_promiseCreated;
- longStackTraces = false;
- };
- longStackTraces = true;
- Promise.prototype._pushContext = Context.prototype._pushContext;
- Promise.prototype._popContext = Context.prototype._popContext;
- Promise._peekContext = Promise.prototype._peekContext = peekContext;
- Promise.prototype._promiseCreated = function() {
- var ctx = this._peekContext();
- if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
- };
- };
- return Context;
- };
-
- },{}],9:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, Context) {
- var getDomain = Promise._getDomain;
- var async = Promise._async;
- var Warning = _dereq_("./errors").Warning;
- var util = _dereq_("./util");
- var canAttachTrace = util.canAttachTrace;
- var unhandledRejectionHandled;
- var possiblyUnhandledRejection;
- var bluebirdFramePattern =
- /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
- var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
- var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
- var stackFramePattern = null;
- var formatStack = null;
- var indentStackFrames = false;
- var printWarning;
- var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
- (true ||
- util.env("BLUEBIRD_DEBUG") ||
- util.env("NODE_ENV") === "development"));
-
- var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
- (debugging || util.env("BLUEBIRD_WARNINGS")));
-
- var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
- (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
-
- var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
- (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
-
- Promise.prototype.suppressUnhandledRejections = function() {
- var target = this._target();
- target._bitField = ((target._bitField & (~1048576)) |
- 524288);
- };
-
- Promise.prototype._ensurePossibleRejectionHandled = function () {
- if ((this._bitField & 524288) !== 0) return;
- this._setRejectionIsUnhandled();
- async.invokeLater(this._notifyUnhandledRejection, this, undefined);
- };
-
- Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
- fireRejectionEvent("rejectionHandled",
- unhandledRejectionHandled, undefined, this);
- };
-
- Promise.prototype._setReturnedNonUndefined = function() {
- this._bitField = this._bitField | 268435456;
- };
-
- Promise.prototype._returnedNonUndefined = function() {
- return (this._bitField & 268435456) !== 0;
- };
-
- Promise.prototype._notifyUnhandledRejection = function () {
- if (this._isRejectionUnhandled()) {
- var reason = this._settledValue();
- this._setUnhandledRejectionIsNotified();
- fireRejectionEvent("unhandledRejection",
- possiblyUnhandledRejection, reason, this);
- }
- };
-
- Promise.prototype._setUnhandledRejectionIsNotified = function () {
- this._bitField = this._bitField | 262144;
- };
-
- Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
- this._bitField = this._bitField & (~262144);
- };
-
- Promise.prototype._isUnhandledRejectionNotified = function () {
- return (this._bitField & 262144) > 0;
- };
-
- Promise.prototype._setRejectionIsUnhandled = function () {
- this._bitField = this._bitField | 1048576;
- };
-
- Promise.prototype._unsetRejectionIsUnhandled = function () {
- this._bitField = this._bitField & (~1048576);
- if (this._isUnhandledRejectionNotified()) {
- this._unsetUnhandledRejectionIsNotified();
- this._notifyUnhandledRejectionIsHandled();
- }
- };
-
- Promise.prototype._isRejectionUnhandled = function () {
- return (this._bitField & 1048576) > 0;
- };
-
- Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
- return warn(message, shouldUseOwnTrace, promise || this);
- };
-
- Promise.onPossiblyUnhandledRejection = function (fn) {
- var domain = getDomain();
- possiblyUnhandledRejection =
- typeof fn === "function" ? (domain === null ?
- fn : util.domainBind(domain, fn))
- : undefined;
- };
-
- Promise.onUnhandledRejectionHandled = function (fn) {
- var domain = getDomain();
- unhandledRejectionHandled =
- typeof fn === "function" ? (domain === null ?
- fn : util.domainBind(domain, fn))
- : undefined;
- };
-
- var disableLongStackTraces = function() {};
- Promise.longStackTraces = function () {
- if (async.haveItemsQueued() && !config.longStackTraces) {
- throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- if (!config.longStackTraces && longStackTracesIsSupported()) {
- var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
- var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
- config.longStackTraces = true;
- disableLongStackTraces = function() {
- if (async.haveItemsQueued() && !config.longStackTraces) {
- throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- Promise.prototype._captureStackTrace = Promise_captureStackTrace;
- Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
- Context.deactivateLongStackTraces();
- async.enableTrampoline();
- config.longStackTraces = false;
- };
- Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
- Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
- Context.activateLongStackTraces();
- async.disableTrampolineIfNecessary();
- }
- };
-
- Promise.hasLongStackTraces = function () {
- return config.longStackTraces && longStackTracesIsSupported();
- };
-
- var fireDomEvent = (function() {
- try {
- if (typeof CustomEvent === "function") {
- var event = new CustomEvent("CustomEvent");
- util.global.dispatchEvent(event);
- return function(name, event) {
- var domEvent = new CustomEvent(name.toLowerCase(), {
- detail: event,
- cancelable: true
- });
- return !util.global.dispatchEvent(domEvent);
- };
- } else if (typeof Event === "function") {
- var event = new Event("CustomEvent");
- util.global.dispatchEvent(event);
- return function(name, event) {
- var domEvent = new Event(name.toLowerCase(), {
- cancelable: true
- });
- domEvent.detail = event;
- return !util.global.dispatchEvent(domEvent);
- };
- } else {
- var event = document.createEvent("CustomEvent");
- event.initCustomEvent("testingtheevent", false, true, {});
- util.global.dispatchEvent(event);
- return function(name, event) {
- var domEvent = document.createEvent("CustomEvent");
- domEvent.initCustomEvent(name.toLowerCase(), false, true,
- event);
- return !util.global.dispatchEvent(domEvent);
- };
- }
- } catch (e) {}
- return function() {
- return false;
- };
- })();
-
- var fireGlobalEvent = (function() {
- if (util.isNode) {
- return function() {
- return process.emit.apply(process, arguments);
- };
- } else {
- if (!util.global) {
- return function() {
- return false;
- };
- }
- return function(name) {
- var methodName = "on" + name.toLowerCase();
- var method = util.global[methodName];
- if (!method) return false;
- method.apply(util.global, [].slice.call(arguments, 1));
- return true;
- };
- }
- })();
-
- function generatePromiseLifecycleEventObject(name, promise) {
- return {promise: promise};
- }
-
- var eventToObjectGenerator = {
- promiseCreated: generatePromiseLifecycleEventObject,
- promiseFulfilled: generatePromiseLifecycleEventObject,
- promiseRejected: generatePromiseLifecycleEventObject,
- promiseResolved: generatePromiseLifecycleEventObject,
- promiseCancelled: generatePromiseLifecycleEventObject,
- promiseChained: function(name, promise, child) {
- return {promise: promise, child: child};
- },
- warning: function(name, warning) {
- return {warning: warning};
- },
- unhandledRejection: function (name, reason, promise) {
- return {reason: reason, promise: promise};
- },
- rejectionHandled: generatePromiseLifecycleEventObject
- };
-
- var activeFireEvent = function (name) {
- var globalEventFired = false;
- try {
- globalEventFired = fireGlobalEvent.apply(null, arguments);
- } catch (e) {
- async.throwLater(e);
- globalEventFired = true;
- }
-
- var domEventFired = false;
- try {
- domEventFired = fireDomEvent(name,
- eventToObjectGenerator[name].apply(null, arguments));
- } catch (e) {
- async.throwLater(e);
- domEventFired = true;
- }
-
- return domEventFired || globalEventFired;
- };
-
- Promise.config = function(opts) {
- opts = Object(opts);
- if ("longStackTraces" in opts) {
- if (opts.longStackTraces) {
- Promise.longStackTraces();
- } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
- disableLongStackTraces();
- }
- }
- if ("warnings" in opts) {
- var warningsOption = opts.warnings;
- config.warnings = !!warningsOption;
- wForgottenReturn = config.warnings;
-
- if (util.isObject(warningsOption)) {
- if ("wForgottenReturn" in warningsOption) {
- wForgottenReturn = !!warningsOption.wForgottenReturn;
- }
- }
- }
- if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
- if (async.haveItemsQueued()) {
- throw new Error(
- "cannot enable cancellation after promises are in use");
- }
- Promise.prototype._clearCancellationData =
- cancellationClearCancellationData;
- Promise.prototype._propagateFrom = cancellationPropagateFrom;
- Promise.prototype._onCancel = cancellationOnCancel;
- Promise.prototype._setOnCancel = cancellationSetOnCancel;
- Promise.prototype._attachCancellationCallback =
- cancellationAttachCancellationCallback;
- Promise.prototype._execute = cancellationExecute;
- propagateFromFunction = cancellationPropagateFrom;
- config.cancellation = true;
- }
- if ("monitoring" in opts) {
- if (opts.monitoring && !config.monitoring) {
- config.monitoring = true;
- Promise.prototype._fireEvent = activeFireEvent;
- } else if (!opts.monitoring && config.monitoring) {
- config.monitoring = false;
- Promise.prototype._fireEvent = defaultFireEvent;
- }
- }
- };
-
- function defaultFireEvent() { return false; }
-
- Promise.prototype._fireEvent = defaultFireEvent;
- Promise.prototype._execute = function(executor, resolve, reject) {
- try {
- executor(resolve, reject);
- } catch (e) {
- return e;
- }
- };
- Promise.prototype._onCancel = function () {};
- Promise.prototype._setOnCancel = function (handler) { ; };
- Promise.prototype._attachCancellationCallback = function(onCancel) {
- ;
- };
- Promise.prototype._captureStackTrace = function () {};
- Promise.prototype._attachExtraTrace = function () {};
- Promise.prototype._clearCancellationData = function() {};
- Promise.prototype._propagateFrom = function (parent, flags) {
- ;
- ;
- };
-
- function cancellationExecute(executor, resolve, reject) {
- var promise = this;
- try {
- executor(resolve, reject, function(onCancel) {
- if (typeof onCancel !== "function") {
- throw new TypeError("onCancel must be a function, got: " +
- util.toString(onCancel));
- }
- promise._attachCancellationCallback(onCancel);
- });
- } catch (e) {
- return e;
- }
- }
-
- function cancellationAttachCancellationCallback(onCancel) {
- if (!this._isCancellable()) return this;
-
- var previousOnCancel = this._onCancel();
- if (previousOnCancel !== undefined) {
- if (util.isArray(previousOnCancel)) {
- previousOnCancel.push(onCancel);
- } else {
- this._setOnCancel([previousOnCancel, onCancel]);
- }
- } else {
- this._setOnCancel(onCancel);
- }
- }
-
- function cancellationOnCancel() {
- return this._onCancelField;
- }
-
- function cancellationSetOnCancel(onCancel) {
- this._onCancelField = onCancel;
- }
-
- function cancellationClearCancellationData() {
- this._cancellationParent = undefined;
- this._onCancelField = undefined;
- }
-
- function cancellationPropagateFrom(parent, flags) {
- if ((flags & 1) !== 0) {
- this._cancellationParent = parent;
- var branchesRemainingToCancel = parent._branchesRemainingToCancel;
- if (branchesRemainingToCancel === undefined) {
- branchesRemainingToCancel = 0;
- }
- parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
- }
- if ((flags & 2) !== 0 && parent._isBound()) {
- this._setBoundTo(parent._boundTo);
- }
- }
-
- function bindingPropagateFrom(parent, flags) {
- if ((flags & 2) !== 0 && parent._isBound()) {
- this._setBoundTo(parent._boundTo);
- }
- }
- var propagateFromFunction = bindingPropagateFrom;
-
- function boundValueFunction() {
- var ret = this._boundTo;
- if (ret !== undefined) {
- if (ret instanceof Promise) {
- if (ret.isFulfilled()) {
- return ret.value();
- } else {
- return undefined;
- }
- }
- }
- return ret;
- }
-
- function longStackTracesCaptureStackTrace() {
- this._trace = new CapturedTrace(this._peekContext());
- }
-
- function longStackTracesAttachExtraTrace(error, ignoreSelf) {
- if (canAttachTrace(error)) {
- var trace = this._trace;
- if (trace !== undefined) {
- if (ignoreSelf) trace = trace._parent;
- }
- if (trace !== undefined) {
- trace.attachExtraTrace(error);
- } else if (!error.__stackCleaned__) {
- var parsed = parseStackAndMessage(error);
- util.notEnumerableProp(error, "stack",
- parsed.message + "\n" + parsed.stack.join("\n"));
- util.notEnumerableProp(error, "__stackCleaned__", true);
- }
- }
- }
-
- function checkForgottenReturns(returnValue, promiseCreated, name, promise,
- parent) {
- if (returnValue === undefined && promiseCreated !== null &&
- wForgottenReturn) {
- if (parent !== undefined && parent._returnedNonUndefined()) return;
- if ((promise._bitField & 65535) === 0) return;
-
- if (name) name = name + " ";
- var handlerLine = "";
- var creatorLine = "";
- if (promiseCreated._trace) {
- var traceLines = promiseCreated._trace.stack.split("\n");
- var stack = cleanStack(traceLines);
- for (var i = stack.length - 1; i >= 0; --i) {
- var line = stack[i];
- if (!nodeFramePattern.test(line)) {
- var lineMatches = line.match(parseLinePattern);
- if (lineMatches) {
- handlerLine = "at " + lineMatches[1] +
- ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
- }
- break;
- }
- }
-
- if (stack.length > 0) {
- var firstUserLine = stack[0];
- for (var i = 0; i < traceLines.length; ++i) {
-
- if (traceLines[i] === firstUserLine) {
- if (i > 0) {
- creatorLine = "\n" + traceLines[i - 1];
- }
- break;
- }
- }
-
- }
- }
- var msg = "a promise was created in a " + name +
- "handler " + handlerLine + "but was not returned from it, " +
- "see http://goo.gl/rRqMUw" +
- creatorLine;
- promise._warn(msg, true, promiseCreated);
- }
- }
-
- function deprecated(name, replacement) {
- var message = name +
- " is deprecated and will be removed in a future version.";
- if (replacement) message += " Use " + replacement + " instead.";
- return warn(message);
- }
-
- function warn(message, shouldUseOwnTrace, promise) {
- if (!config.warnings) return;
- var warning = new Warning(message);
- var ctx;
- if (shouldUseOwnTrace) {
- promise._attachExtraTrace(warning);
- } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
- ctx.attachExtraTrace(warning);
- } else {
- var parsed = parseStackAndMessage(warning);
- warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
- }
-
- if (!activeFireEvent("warning", warning)) {
- formatAndLogError(warning, "", true);
- }
- }
-
- function reconstructStack(message, stacks) {
- for (var i = 0; i < stacks.length - 1; ++i) {
- stacks[i].push("From previous event:");
- stacks[i] = stacks[i].join("\n");
- }
- if (i < stacks.length) {
- stacks[i] = stacks[i].join("\n");
- }
- return message + "\n" + stacks.join("\n");
- }
-
- function removeDuplicateOrEmptyJumps(stacks) {
- for (var i = 0; i < stacks.length; ++i) {
- if (stacks[i].length === 0 ||
- ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
- stacks.splice(i, 1);
- i--;
- }
- }
- }
-
- function removeCommonRoots(stacks) {
- var current = stacks[0];
- for (var i = 1; i < stacks.length; ++i) {
- var prev = stacks[i];
- var currentLastIndex = current.length - 1;
- var currentLastLine = current[currentLastIndex];
- var commonRootMeetPoint = -1;
-
- for (var j = prev.length - 1; j >= 0; --j) {
- if (prev[j] === currentLastLine) {
- commonRootMeetPoint = j;
- break;
- }
- }
-
- for (var j = commonRootMeetPoint; j >= 0; --j) {
- var line = prev[j];
- if (current[currentLastIndex] === line) {
- current.pop();
- currentLastIndex--;
- } else {
- break;
- }
- }
- current = prev;
- }
- }
-
- function cleanStack(stack) {
- var ret = [];
- for (var i = 0; i < stack.length; ++i) {
- var line = stack[i];
- var isTraceLine = " (No stack trace)" === line ||
- stackFramePattern.test(line);
- var isInternalFrame = isTraceLine && shouldIgnore(line);
- if (isTraceLine && !isInternalFrame) {
- if (indentStackFrames && line.charAt(0) !== " ") {
- line = " " + line;
- }
- ret.push(line);
- }
- }
- return ret;
- }
-
- function stackFramesAsArray(error) {
- var stack = error.stack.replace(/\s+$/g, "").split("\n");
- for (var i = 0; i < stack.length; ++i) {
- var line = stack[i];
- if (" (No stack trace)" === line || stackFramePattern.test(line)) {
- break;
- }
- }
- if (i > 0) {
- stack = stack.slice(i);
- }
- return stack;
- }
-
- function parseStackAndMessage(error) {
- var stack = error.stack;
- var message = error.toString();
- stack = typeof stack === "string" && stack.length > 0
- ? stackFramesAsArray(error) : [" (No stack trace)"];
- return {
- message: message,
- stack: cleanStack(stack)
- };
- }
-
- function formatAndLogError(error, title, isSoft) {
- if (typeof console !== "undefined") {
- var message;
- if (util.isObject(error)) {
- var stack = error.stack;
- message = title + formatStack(stack, error);
- } else {
- message = title + String(error);
- }
- if (typeof printWarning === "function") {
- printWarning(message, isSoft);
- } else if (typeof console.log === "function" ||
- typeof console.log === "object") {
- console.log(message);
- }
- }
- }
-
- function fireRejectionEvent(name, localHandler, reason, promise) {
- var localEventFired = false;
- try {
- if (typeof localHandler === "function") {
- localEventFired = true;
- if (name === "rejectionHandled") {
- localHandler(promise);
- } else {
- localHandler(reason, promise);
- }
- }
- } catch (e) {
- async.throwLater(e);
- }
-
- if (name === "unhandledRejection") {
- if (!activeFireEvent(name, reason, promise) && !localEventFired) {
- formatAndLogError(reason, "Unhandled rejection ");
- }
- } else {
- activeFireEvent(name, promise);
- }
- }
-
- function formatNonError(obj) {
- var str;
- if (typeof obj === "function") {
- str = "[function " +
- (obj.name || "anonymous") +
- "]";
- } else {
- str = obj && typeof obj.toString === "function"
- ? obj.toString() : util.toString(obj);
- var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
- if (ruselessToString.test(str)) {
- try {
- var newStr = JSON.stringify(obj);
- str = newStr;
- }
- catch(e) {
-
- }
- }
- if (str.length === 0) {
- str = "(empty array)";
- }
- }
- return ("(<" + snip(str) + ">, no stack trace)");
- }
-
- function snip(str) {
- var maxChars = 41;
- if (str.length < maxChars) {
- return str;
- }
- return str.substr(0, maxChars - 3) + "...";
- }
-
- function longStackTracesIsSupported() {
- return typeof captureStackTrace === "function";
- }
-
- var shouldIgnore = function() { return false; };
- var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
- function parseLineInfo(line) {
- var matches = line.match(parseLineInfoRegex);
- if (matches) {
- return {
- fileName: matches[1],
- line: parseInt(matches[2], 10)
- };
- }
- }
-
- function setBounds(firstLineError, lastLineError) {
- if (!longStackTracesIsSupported()) return;
- var firstStackLines = firstLineError.stack.split("\n");
- var lastStackLines = lastLineError.stack.split("\n");
- var firstIndex = -1;
- var lastIndex = -1;
- var firstFileName;
- var lastFileName;
- for (var i = 0; i < firstStackLines.length; ++i) {
- var result = parseLineInfo(firstStackLines[i]);
- if (result) {
- firstFileName = result.fileName;
- firstIndex = result.line;
- break;
- }
- }
- for (var i = 0; i < lastStackLines.length; ++i) {
- var result = parseLineInfo(lastStackLines[i]);
- if (result) {
- lastFileName = result.fileName;
- lastIndex = result.line;
- break;
- }
- }
- if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
- firstFileName !== lastFileName || firstIndex >= lastIndex) {
- return;
- }
-
- shouldIgnore = function(line) {
- if (bluebirdFramePattern.test(line)) return true;
- var info = parseLineInfo(line);
- if (info) {
- if (info.fileName === firstFileName &&
- (firstIndex <= info.line && info.line <= lastIndex)) {
- return true;
- }
- }
- return false;
- };
- }
-
- function CapturedTrace(parent) {
- this._parent = parent;
- this._promisesCreated = 0;
- var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
- captureStackTrace(this, CapturedTrace);
- if (length > 32) this.uncycle();
- }
- util.inherits(CapturedTrace, Error);
- Context.CapturedTrace = CapturedTrace;
-
- CapturedTrace.prototype.uncycle = function() {
- var length = this._length;
- if (length < 2) return;
- var nodes = [];
- var stackToIndex = {};
-
- for (var i = 0, node = this; node !== undefined; ++i) {
- nodes.push(node);
- node = node._parent;
- }
- length = this._length = i;
- for (var i = length - 1; i >= 0; --i) {
- var stack = nodes[i].stack;
- if (stackToIndex[stack] === undefined) {
- stackToIndex[stack] = i;
- }
- }
- for (var i = 0; i < length; ++i) {
- var currentStack = nodes[i].stack;
- var index = stackToIndex[currentStack];
- if (index !== undefined && index !== i) {
- if (index > 0) {
- nodes[index - 1]._parent = undefined;
- nodes[index - 1]._length = 1;
- }
- nodes[i]._parent = undefined;
- nodes[i]._length = 1;
- var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
-
- if (index < length - 1) {
- cycleEdgeNode._parent = nodes[index + 1];
- cycleEdgeNode._parent.uncycle();
- cycleEdgeNode._length =
- cycleEdgeNode._parent._length + 1;
- } else {
- cycleEdgeNode._parent = undefined;
- cycleEdgeNode._length = 1;
- }
- var currentChildLength = cycleEdgeNode._length + 1;
- for (var j = i - 2; j >= 0; --j) {
- nodes[j]._length = currentChildLength;
- currentChildLength++;
- }
- return;
- }
- }
- };
-
- CapturedTrace.prototype.attachExtraTrace = function(error) {
- if (error.__stackCleaned__) return;
- this.uncycle();
- var parsed = parseStackAndMessage(error);
- var message = parsed.message;
- var stacks = [parsed.stack];
-
- var trace = this;
- while (trace !== undefined) {
- stacks.push(cleanStack(trace.stack.split("\n")));
- trace = trace._parent;
- }
- removeCommonRoots(stacks);
- removeDuplicateOrEmptyJumps(stacks);
- util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
- util.notEnumerableProp(error, "__stackCleaned__", true);
- };
-
- var captureStackTrace = (function stackDetection() {
- var v8stackFramePattern = /^\s*at\s*/;
- var v8stackFormatter = function(stack, error) {
- if (typeof stack === "string") return stack;
-
- if (error.name !== undefined &&
- error.message !== undefined) {
- return error.toString();
- }
- return formatNonError(error);
- };
-
- if (typeof Error.stackTraceLimit === "number" &&
- typeof Error.captureStackTrace === "function") {
- Error.stackTraceLimit += 6;
- stackFramePattern = v8stackFramePattern;
- formatStack = v8stackFormatter;
- var captureStackTrace = Error.captureStackTrace;
-
- shouldIgnore = function(line) {
- return bluebirdFramePattern.test(line);
- };
- return function(receiver, ignoreUntil) {
- Error.stackTraceLimit += 6;
- captureStackTrace(receiver, ignoreUntil);
- Error.stackTraceLimit -= 6;
- };
- }
- var err = new Error();
-
- if (typeof err.stack === "string" &&
- err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
- stackFramePattern = /@/;
- formatStack = v8stackFormatter;
- indentStackFrames = true;
- return function captureStackTrace(o) {
- o.stack = new Error().stack;
- };
- }
-
- var hasStackAfterThrow;
- try { throw new Error(); }
- catch(e) {
- hasStackAfterThrow = ("stack" in e);
- }
- if (!("stack" in err) && hasStackAfterThrow &&
- typeof Error.stackTraceLimit === "number") {
- stackFramePattern = v8stackFramePattern;
- formatStack = v8stackFormatter;
- return function captureStackTrace(o) {
- Error.stackTraceLimit += 6;
- try { throw new Error(); }
- catch(e) { o.stack = e.stack; }
- Error.stackTraceLimit -= 6;
- };
- }
-
- formatStack = function(stack, error) {
- if (typeof stack === "string") return stack;
-
- if ((typeof error === "object" ||
- typeof error === "function") &&
- error.name !== undefined &&
- error.message !== undefined) {
- return error.toString();
- }
- return formatNonError(error);
- };
-
- return null;
-
- })([]);
-
- if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
- printWarning = function (message) {
- console.warn(message);
- };
- if (util.isNode && process.stderr.isTTY) {
- printWarning = function(message, isSoft) {
- var color = isSoft ? "\u001b[33m" : "\u001b[31m";
- console.warn(color + message + "\u001b[0m\n");
- };
- } else if (!util.isNode && typeof (new Error().stack) === "string") {
- printWarning = function(message, isSoft) {
- console.warn("%c" + message,
- isSoft ? "color: darkorange" : "color: red");
- };
- }
- }
-
- var config = {
- warnings: warnings,
- longStackTraces: false,
- cancellation: false,
- monitoring: false
- };
-
- if (longStackTraces) Promise.longStackTraces();
-
- return {
- longStackTraces: function() {
- return config.longStackTraces;
- },
- warnings: function() {
- return config.warnings;
- },
- cancellation: function() {
- return config.cancellation;
- },
- monitoring: function() {
- return config.monitoring;
- },
- propagateFromFunction: function() {
- return propagateFromFunction;
- },
- boundValueFunction: function() {
- return boundValueFunction;
- },
- checkForgottenReturns: checkForgottenReturns,
- setBounds: setBounds,
- warn: warn,
- deprecated: deprecated,
- CapturedTrace: CapturedTrace,
- fireDomEvent: fireDomEvent,
- fireGlobalEvent: fireGlobalEvent
- };
- };
-
- },{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise) {
- function returner() {
- return this.value;
- }
- function thrower() {
- throw this.reason;
- }
-
- Promise.prototype["return"] =
- Promise.prototype.thenReturn = function (value) {
- if (value instanceof Promise) value.suppressUnhandledRejections();
- return this._then(
- returner, undefined, undefined, {value: value}, undefined);
- };
-
- Promise.prototype["throw"] =
- Promise.prototype.thenThrow = function (reason) {
- return this._then(
- thrower, undefined, undefined, {reason: reason}, undefined);
- };
-
- Promise.prototype.catchThrow = function (reason) {
- if (arguments.length <= 1) {
- return this._then(
- undefined, thrower, undefined, {reason: reason}, undefined);
- } else {
- var _reason = arguments[1];
- var handler = function() {throw _reason;};
- return this.caught(reason, handler);
- }
- };
-
- Promise.prototype.catchReturn = function (value) {
- if (arguments.length <= 1) {
- if (value instanceof Promise) value.suppressUnhandledRejections();
- return this._then(
- undefined, returner, undefined, {value: value}, undefined);
- } else {
- var _value = arguments[1];
- if (_value instanceof Promise) _value.suppressUnhandledRejections();
- var handler = function() {return _value;};
- return this.caught(value, handler);
- }
- };
- };
-
- },{}],11:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var PromiseReduce = Promise.reduce;
- var PromiseAll = Promise.all;
-
- function promiseAllThis() {
- return PromiseAll(this);
- }
-
- function PromiseMapSeries(promises, fn) {
- return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
- }
-
- Promise.prototype.each = function (fn) {
- return PromiseReduce(this, fn, INTERNAL, 0)
- ._then(promiseAllThis, undefined, undefined, this, undefined);
- };
-
- Promise.prototype.mapSeries = function (fn) {
- return PromiseReduce(this, fn, INTERNAL, INTERNAL);
- };
-
- Promise.each = function (promises, fn) {
- return PromiseReduce(promises, fn, INTERNAL, 0)
- ._then(promiseAllThis, undefined, undefined, promises, undefined);
- };
-
- Promise.mapSeries = PromiseMapSeries;
- };
-
-
- },{}],12:[function(_dereq_,module,exports){
- "use strict";
- var es5 = _dereq_("./es5");
- var Objectfreeze = es5.freeze;
- var util = _dereq_("./util");
- var inherits = util.inherits;
- var notEnumerableProp = util.notEnumerableProp;
-
- function subError(nameProperty, defaultMessage) {
- function SubError(message) {
- if (!(this instanceof SubError)) return new SubError(message);
- notEnumerableProp(this, "message",
- typeof message === "string" ? message : defaultMessage);
- notEnumerableProp(this, "name", nameProperty);
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- } else {
- Error.call(this);
- }
- }
- inherits(SubError, Error);
- return SubError;
- }
-
- var _TypeError, _RangeError;
- var Warning = subError("Warning", "warning");
- var CancellationError = subError("CancellationError", "cancellation error");
- var TimeoutError = subError("TimeoutError", "timeout error");
- var AggregateError = subError("AggregateError", "aggregate error");
- try {
- _TypeError = TypeError;
- _RangeError = RangeError;
- } catch(e) {
- _TypeError = subError("TypeError", "type error");
- _RangeError = subError("RangeError", "range error");
- }
-
- var methods = ("join pop push shift unshift slice filter forEach some " +
- "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
-
- for (var i = 0; i < methods.length; ++i) {
- if (typeof Array.prototype[methods[i]] === "function") {
- AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
- }
- }
-
- es5.defineProperty(AggregateError.prototype, "length", {
- value: 0,
- configurable: false,
- writable: true,
- enumerable: true
- });
- AggregateError.prototype["isOperational"] = true;
- var level = 0;
- AggregateError.prototype.toString = function() {
- var indent = Array(level * 4 + 1).join(" ");
- var ret = "\n" + indent + "AggregateError of:" + "\n";
- level++;
- indent = Array(level * 4 + 1).join(" ");
- for (var i = 0; i < this.length; ++i) {
- var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
- var lines = str.split("\n");
- for (var j = 0; j < lines.length; ++j) {
- lines[j] = indent + lines[j];
- }
- str = lines.join("\n");
- ret += str + "\n";
- }
- level--;
- return ret;
- };
-
- function OperationalError(message) {
- if (!(this instanceof OperationalError))
- return new OperationalError(message);
- notEnumerableProp(this, "name", "OperationalError");
- notEnumerableProp(this, "message", message);
- this.cause = message;
- this["isOperational"] = true;
-
- if (message instanceof Error) {
- notEnumerableProp(this, "message", message.message);
- notEnumerableProp(this, "stack", message.stack);
- } else if (Error.captureStackTrace) {
- Error.captureStackTrace(this, this.constructor);
- }
-
- }
- inherits(OperationalError, Error);
-
- var errorTypes = Error["__BluebirdErrorTypes__"];
- if (!errorTypes) {
- errorTypes = Objectfreeze({
- CancellationError: CancellationError,
- TimeoutError: TimeoutError,
- OperationalError: OperationalError,
- RejectionError: OperationalError,
- AggregateError: AggregateError
- });
- es5.defineProperty(Error, "__BluebirdErrorTypes__", {
- value: errorTypes,
- writable: false,
- enumerable: false,
- configurable: false
- });
- }
-
- module.exports = {
- Error: Error,
- TypeError: _TypeError,
- RangeError: _RangeError,
- CancellationError: errorTypes.CancellationError,
- OperationalError: errorTypes.OperationalError,
- TimeoutError: errorTypes.TimeoutError,
- AggregateError: errorTypes.AggregateError,
- Warning: Warning
- };
-
- },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
- var isES5 = (function(){
- "use strict";
- return this === undefined;
- })();
-
- if (isES5) {
- module.exports = {
- freeze: Object.freeze,
- defineProperty: Object.defineProperty,
- getDescriptor: Object.getOwnPropertyDescriptor,
- keys: Object.keys,
- names: Object.getOwnPropertyNames,
- getPrototypeOf: Object.getPrototypeOf,
- isArray: Array.isArray,
- isES5: isES5,
- propertyIsWritable: function(obj, prop) {
- var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
- return !!(!descriptor || descriptor.writable || descriptor.set);
- }
- };
- } else {
- var has = {}.hasOwnProperty;
- var str = {}.toString;
- var proto = {}.constructor.prototype;
-
- var ObjectKeys = function (o) {
- var ret = [];
- for (var key in o) {
- if (has.call(o, key)) {
- ret.push(key);
- }
- }
- return ret;
- };
-
- var ObjectGetDescriptor = function(o, key) {
- return {value: o[key]};
- };
-
- var ObjectDefineProperty = function (o, key, desc) {
- o[key] = desc.value;
- return o;
- };
-
- var ObjectFreeze = function (obj) {
- return obj;
- };
-
- var ObjectGetPrototypeOf = function (obj) {
- try {
- return Object(obj).constructor.prototype;
- }
- catch (e) {
- return proto;
- }
- };
-
- var ArrayIsArray = function (obj) {
- try {
- return str.call(obj) === "[object Array]";
- }
- catch(e) {
- return false;
- }
- };
-
- module.exports = {
- isArray: ArrayIsArray,
- keys: ObjectKeys,
- names: ObjectKeys,
- defineProperty: ObjectDefineProperty,
- getDescriptor: ObjectGetDescriptor,
- freeze: ObjectFreeze,
- getPrototypeOf: ObjectGetPrototypeOf,
- isES5: isES5,
- propertyIsWritable: function() {
- return true;
- }
- };
- }
-
- },{}],14:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var PromiseMap = Promise.map;
-
- Promise.prototype.filter = function (fn, options) {
- return PromiseMap(this, fn, options, INTERNAL);
- };
-
- Promise.filter = function (promises, fn, options) {
- return PromiseMap(promises, fn, options, INTERNAL);
- };
- };
-
- },{}],15:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, tryConvertToPromise) {
- var util = _dereq_("./util");
- var CancellationError = Promise.CancellationError;
- var errorObj = util.errorObj;
-
- function PassThroughHandlerContext(promise, type, handler) {
- this.promise = promise;
- this.type = type;
- this.handler = handler;
- this.called = false;
- this.cancelPromise = null;
- }
-
- PassThroughHandlerContext.prototype.isFinallyHandler = function() {
- return this.type === 0;
- };
-
- function FinallyHandlerCancelReaction(finallyHandler) {
- this.finallyHandler = finallyHandler;
- }
-
- FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
- checkCancel(this.finallyHandler);
- };
-
- function checkCancel(ctx, reason) {
- if (ctx.cancelPromise != null) {
- if (arguments.length > 1) {
- ctx.cancelPromise._reject(reason);
- } else {
- ctx.cancelPromise._cancel();
- }
- ctx.cancelPromise = null;
- return true;
- }
- return false;
- }
-
- function succeed() {
- return finallyHandler.call(this, this.promise._target()._settledValue());
- }
- function fail(reason) {
- if (checkCancel(this, reason)) return;
- errorObj.e = reason;
- return errorObj;
- }
- function finallyHandler(reasonOrValue) {
- var promise = this.promise;
- var handler = this.handler;
-
- if (!this.called) {
- this.called = true;
- var ret = this.isFinallyHandler()
- ? handler.call(promise._boundValue())
- : handler.call(promise._boundValue(), reasonOrValue);
- if (ret !== undefined) {
- promise._setReturnedNonUndefined();
- var maybePromise = tryConvertToPromise(ret, promise);
- if (maybePromise instanceof Promise) {
- if (this.cancelPromise != null) {
- if (maybePromise._isCancelled()) {
- var reason =
- new CancellationError("late cancellation observer");
- promise._attachExtraTrace(reason);
- errorObj.e = reason;
- return errorObj;
- } else if (maybePromise.isPending()) {
- maybePromise._attachCancellationCallback(
- new FinallyHandlerCancelReaction(this));
- }
- }
- return maybePromise._then(
- succeed, fail, undefined, this, undefined);
- }
- }
- }
-
- if (promise.isRejected()) {
- checkCancel(this);
- errorObj.e = reasonOrValue;
- return errorObj;
- } else {
- checkCancel(this);
- return reasonOrValue;
- }
- }
-
- Promise.prototype._passThrough = function(handler, type, success, fail) {
- if (typeof handler !== "function") return this.then();
- return this._then(success,
- fail,
- undefined,
- new PassThroughHandlerContext(this, type, handler),
- undefined);
- };
-
- Promise.prototype.lastly =
- Promise.prototype["finally"] = function (handler) {
- return this._passThrough(handler,
- 0,
- finallyHandler,
- finallyHandler);
- };
-
- Promise.prototype.tap = function (handler) {
- return this._passThrough(handler, 1, finallyHandler);
- };
-
- return PassThroughHandlerContext;
- };
-
- },{"./util":36}],16:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise,
- apiRejection,
- INTERNAL,
- tryConvertToPromise,
- Proxyable,
- debug) {
- var errors = _dereq_("./errors");
- var TypeError = errors.TypeError;
- var util = _dereq_("./util");
- var errorObj = util.errorObj;
- var tryCatch = util.tryCatch;
- var yieldHandlers = [];
-
- function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
- for (var i = 0; i < yieldHandlers.length; ++i) {
- traceParent._pushContext();
- var result = tryCatch(yieldHandlers[i])(value);
- traceParent._popContext();
- if (result === errorObj) {
- traceParent._pushContext();
- var ret = Promise.reject(errorObj.e);
- traceParent._popContext();
- return ret;
- }
- var maybePromise = tryConvertToPromise(result, traceParent);
- if (maybePromise instanceof Promise) return maybePromise;
- }
- return null;
- }
-
- function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
- if (debug.cancellation()) {
- var internal = new Promise(INTERNAL);
- var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
- this._promise = internal.lastly(function() {
- return _finallyPromise;
- });
- internal._captureStackTrace();
- internal._setOnCancel(this);
- } else {
- var promise = this._promise = new Promise(INTERNAL);
- promise._captureStackTrace();
- }
- this._stack = stack;
- this._generatorFunction = generatorFunction;
- this._receiver = receiver;
- this._generator = undefined;
- this._yieldHandlers = typeof yieldHandler === "function"
- ? [yieldHandler].concat(yieldHandlers)
- : yieldHandlers;
- this._yieldedPromise = null;
- this._cancellationPhase = false;
- }
- util.inherits(PromiseSpawn, Proxyable);
-
- PromiseSpawn.prototype._isResolved = function() {
- return this._promise === null;
- };
-
- PromiseSpawn.prototype._cleanup = function() {
- this._promise = this._generator = null;
- if (debug.cancellation() && this._finallyPromise !== null) {
- this._finallyPromise._fulfill();
- this._finallyPromise = null;
- }
- };
-
- PromiseSpawn.prototype._promiseCancelled = function() {
- if (this._isResolved()) return;
- var implementsReturn = typeof this._generator["return"] !== "undefined";
-
- var result;
- if (!implementsReturn) {
- var reason = new Promise.CancellationError(
- "generator .return() sentinel");
- Promise.coroutine.returnSentinel = reason;
- this._promise._attachExtraTrace(reason);
- this._promise._pushContext();
- result = tryCatch(this._generator["throw"]).call(this._generator,
- reason);
- this._promise._popContext();
- } else {
- this._promise._pushContext();
- result = tryCatch(this._generator["return"]).call(this._generator,
- undefined);
- this._promise._popContext();
- }
- this._cancellationPhase = true;
- this._yieldedPromise = null;
- this._continue(result);
- };
-
- PromiseSpawn.prototype._promiseFulfilled = function(value) {
- this._yieldedPromise = null;
- this._promise._pushContext();
- var result = tryCatch(this._generator.next).call(this._generator, value);
- this._promise._popContext();
- this._continue(result);
- };
-
- PromiseSpawn.prototype._promiseRejected = function(reason) {
- this._yieldedPromise = null;
- this._promise._attachExtraTrace(reason);
- this._promise._pushContext();
- var result = tryCatch(this._generator["throw"])
- .call(this._generator, reason);
- this._promise._popContext();
- this._continue(result);
- };
-
- PromiseSpawn.prototype._resultCancelled = function() {
- if (this._yieldedPromise instanceof Promise) {
- var promise = this._yieldedPromise;
- this._yieldedPromise = null;
- promise.cancel();
- }
- };
-
- PromiseSpawn.prototype.promise = function () {
- return this._promise;
- };
-
- PromiseSpawn.prototype._run = function () {
- this._generator = this._generatorFunction.call(this._receiver);
- this._receiver =
- this._generatorFunction = undefined;
- this._promiseFulfilled(undefined);
- };
-
- PromiseSpawn.prototype._continue = function (result) {
- var promise = this._promise;
- if (result === errorObj) {
- this._cleanup();
- if (this._cancellationPhase) {
- return promise.cancel();
- } else {
- return promise._rejectCallback(result.e, false);
- }
- }
-
- var value = result.value;
- if (result.done === true) {
- this._cleanup();
- if (this._cancellationPhase) {
- return promise.cancel();
- } else {
- return promise._resolveCallback(value);
- }
- } else {
- var maybePromise = tryConvertToPromise(value, this._promise);
- if (!(maybePromise instanceof Promise)) {
- maybePromise =
- promiseFromYieldHandler(maybePromise,
- this._yieldHandlers,
- this._promise);
- if (maybePromise === null) {
- this._promiseRejected(
- new TypeError(
- "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
- "From coroutine:\u000a" +
- this._stack.split("\n").slice(1, -7).join("\n")
- )
- );
- return;
- }
- }
- maybePromise = maybePromise._target();
- var bitField = maybePromise._bitField;
- ;
- if (((bitField & 50397184) === 0)) {
- this._yieldedPromise = maybePromise;
- maybePromise._proxy(this, null);
- } else if (((bitField & 33554432) !== 0)) {
- Promise._async.invoke(
- this._promiseFulfilled, this, maybePromise._value()
- );
- } else if (((bitField & 16777216) !== 0)) {
- Promise._async.invoke(
- this._promiseRejected, this, maybePromise._reason()
- );
- } else {
- this._promiseCancelled();
- }
- }
- };
-
- Promise.coroutine = function (generatorFunction, options) {
- if (typeof generatorFunction !== "function") {
- throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- var yieldHandler = Object(options).yieldHandler;
- var PromiseSpawn$ = PromiseSpawn;
- var stack = new Error().stack;
- return function () {
- var generator = generatorFunction.apply(this, arguments);
- var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
- stack);
- var ret = spawn.promise();
- spawn._generator = generator;
- spawn._promiseFulfilled(undefined);
- return ret;
- };
- };
-
- Promise.coroutine.addYieldHandler = function(fn) {
- if (typeof fn !== "function") {
- throw new TypeError("expecting a function but got " + util.classString(fn));
- }
- yieldHandlers.push(fn);
- };
-
- Promise.spawn = function (generatorFunction) {
- debug.deprecated("Promise.spawn()", "Promise.coroutine()");
- if (typeof generatorFunction !== "function") {
- return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- var spawn = new PromiseSpawn(generatorFunction, this);
- var ret = spawn.promise();
- spawn._run(Promise.spawn);
- return ret;
- };
- };
-
- },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
- "use strict";
- module.exports =
- function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
- getDomain) {
- var util = _dereq_("./util");
- var canEvaluate = util.canEvaluate;
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- var reject;
-
- if (!true) {
- if (canEvaluate) {
- var thenCallback = function(i) {
- return new Function("value", "holder", " \n\
- 'use strict'; \n\
- holder.pIndex = value; \n\
- holder.checkFulfillment(this); \n\
- ".replace(/Index/g, i));
- };
-
- var promiseSetter = function(i) {
- return new Function("promise", "holder", " \n\
- 'use strict'; \n\
- holder.pIndex = promise; \n\
- ".replace(/Index/g, i));
- };
-
- var generateHolderClass = function(total) {
- var props = new Array(total);
- for (var i = 0; i < props.length; ++i) {
- props[i] = "this.p" + (i+1);
- }
- var assignment = props.join(" = ") + " = null;";
- var cancellationCode= "var promise;\n" + props.map(function(prop) {
- return " \n\
- promise = " + prop + "; \n\
- if (promise instanceof Promise) { \n\
- promise.cancel(); \n\
- } \n\
- ";
- }).join("\n");
- var passedArguments = props.join(", ");
- var name = "Holder$" + total;
-
-
- var code = "return function(tryCatch, errorObj, Promise, async) { \n\
- 'use strict'; \n\
- function [TheName](fn) { \n\
- [TheProperties] \n\
- this.fn = fn; \n\
- this.asyncNeeded = true; \n\
- this.now = 0; \n\
- } \n\
- \n\
- [TheName].prototype._callFunction = function(promise) { \n\
- promise._pushContext(); \n\
- var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
- promise._popContext(); \n\
- if (ret === errorObj) { \n\
- promise._rejectCallback(ret.e, false); \n\
- } else { \n\
- promise._resolveCallback(ret); \n\
- } \n\
- }; \n\
- \n\
- [TheName].prototype.checkFulfillment = function(promise) { \n\
- var now = ++this.now; \n\
- if (now === [TheTotal]) { \n\
- if (this.asyncNeeded) { \n\
- async.invoke(this._callFunction, this, promise); \n\
- } else { \n\
- this._callFunction(promise); \n\
- } \n\
- \n\
- } \n\
- }; \n\
- \n\
- [TheName].prototype._resultCancelled = function() { \n\
- [CancellationCode] \n\
- }; \n\
- \n\
- return [TheName]; \n\
- }(tryCatch, errorObj, Promise, async); \n\
- ";
-
- code = code.replace(/\[TheName\]/g, name)
- .replace(/\[TheTotal\]/g, total)
- .replace(/\[ThePassedArguments\]/g, passedArguments)
- .replace(/\[TheProperties\]/g, assignment)
- .replace(/\[CancellationCode\]/g, cancellationCode);
-
- return new Function("tryCatch", "errorObj", "Promise", "async", code)
- (tryCatch, errorObj, Promise, async);
- };
-
- var holderClasses = [];
- var thenCallbacks = [];
- var promiseSetters = [];
-
- for (var i = 0; i < 8; ++i) {
- holderClasses.push(generateHolderClass(i + 1));
- thenCallbacks.push(thenCallback(i + 1));
- promiseSetters.push(promiseSetter(i + 1));
- }
-
- reject = function (reason) {
- this._reject(reason);
- };
- }}
-
- Promise.join = function () {
- var last = arguments.length - 1;
- var fn;
- if (last > 0 && typeof arguments[last] === "function") {
- fn = arguments[last];
- if (!true) {
- if (last <= 8 && canEvaluate) {
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- var HolderClass = holderClasses[last - 1];
- var holder = new HolderClass(fn);
- var callbacks = thenCallbacks;
-
- for (var i = 0; i < last; ++i) {
- var maybePromise = tryConvertToPromise(arguments[i], ret);
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- var bitField = maybePromise._bitField;
- ;
- if (((bitField & 50397184) === 0)) {
- maybePromise._then(callbacks[i], reject,
- undefined, ret, holder);
- promiseSetters[i](maybePromise, holder);
- holder.asyncNeeded = false;
- } else if (((bitField & 33554432) !== 0)) {
- callbacks[i].call(ret,
- maybePromise._value(), holder);
- } else if (((bitField & 16777216) !== 0)) {
- ret._reject(maybePromise._reason());
- } else {
- ret._cancel();
- }
- } else {
- callbacks[i].call(ret, maybePromise, holder);
- }
- }
-
- if (!ret._isFateSealed()) {
- if (holder.asyncNeeded) {
- var domain = getDomain();
- if (domain !== null) {
- holder.fn = util.domainBind(domain, holder.fn);
- }
- }
- ret._setAsyncGuaranteed();
- ret._setOnCancel(holder);
- }
- return ret;
- }
- }
- }
- var args = [].slice.call(arguments);;
- if (fn) args.pop();
- var ret = new PromiseArray(args).promise();
- return fn !== undefined ? ret.spread(fn) : ret;
- };
-
- };
-
- },{"./util":36}],18:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise,
- PromiseArray,
- apiRejection,
- tryConvertToPromise,
- INTERNAL,
- debug) {
- var getDomain = Promise._getDomain;
- var util = _dereq_("./util");
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
- var async = Promise._async;
-
- function MappingPromiseArray(promises, fn, limit, _filter) {
- this.constructor$(promises);
- this._promise._captureStackTrace();
- var domain = getDomain();
- this._callback = domain === null ? fn : util.domainBind(domain, fn);
- this._preservedValues = _filter === INTERNAL
- ? new Array(this.length())
- : null;
- this._limit = limit;
- this._inFlight = 0;
- this._queue = [];
- async.invoke(this._asyncInit, this, undefined);
- }
- util.inherits(MappingPromiseArray, PromiseArray);
-
- MappingPromiseArray.prototype._asyncInit = function() {
- this._init$(undefined, -2);
- };
-
- MappingPromiseArray.prototype._init = function () {};
-
- MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
- var values = this._values;
- var length = this.length();
- var preservedValues = this._preservedValues;
- var limit = this._limit;
-
- if (index < 0) {
- index = (index * -1) - 1;
- values[index] = value;
- if (limit >= 1) {
- this._inFlight--;
- this._drainQueue();
- if (this._isResolved()) return true;
- }
- } else {
- if (limit >= 1 && this._inFlight >= limit) {
- values[index] = value;
- this._queue.push(index);
- return false;
- }
- if (preservedValues !== null) preservedValues[index] = value;
-
- var promise = this._promise;
- var callback = this._callback;
- var receiver = promise._boundValue();
- promise._pushContext();
- var ret = tryCatch(callback).call(receiver, value, index, length);
- var promiseCreated = promise._popContext();
- debug.checkForgottenReturns(
- ret,
- promiseCreated,
- preservedValues !== null ? "Promise.filter" : "Promise.map",
- promise
- );
- if (ret === errorObj) {
- this._reject(ret.e);
- return true;
- }
-
- var maybePromise = tryConvertToPromise(ret, this._promise);
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- var bitField = maybePromise._bitField;
- ;
- if (((bitField & 50397184) === 0)) {
- if (limit >= 1) this._inFlight++;
- values[index] = maybePromise;
- maybePromise._proxy(this, (index + 1) * -1);
- return false;
- } else if (((bitField & 33554432) !== 0)) {
- ret = maybePromise._value();
- } else if (((bitField & 16777216) !== 0)) {
- this._reject(maybePromise._reason());
- return true;
- } else {
- this._cancel();
- return true;
- }
- }
- values[index] = ret;
- }
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= length) {
- if (preservedValues !== null) {
- this._filter(values, preservedValues);
- } else {
- this._resolve(values);
- }
- return true;
- }
- return false;
- };
-
- MappingPromiseArray.prototype._drainQueue = function () {
- var queue = this._queue;
- var limit = this._limit;
- var values = this._values;
- while (queue.length > 0 && this._inFlight < limit) {
- if (this._isResolved()) return;
- var index = queue.pop();
- this._promiseFulfilled(values[index], index);
- }
- };
-
- MappingPromiseArray.prototype._filter = function (booleans, values) {
- var len = values.length;
- var ret = new Array(len);
- var j = 0;
- for (var i = 0; i < len; ++i) {
- if (booleans[i]) ret[j++] = values[i];
- }
- ret.length = j;
- this._resolve(ret);
- };
-
- MappingPromiseArray.prototype.preservedValues = function () {
- return this._preservedValues;
- };
-
- function map(promises, fn, options, _filter) {
- if (typeof fn !== "function") {
- return apiRejection("expecting a function but got " + util.classString(fn));
- }
-
- var limit = 0;
- if (options !== undefined) {
- if (typeof options === "object" && options !== null) {
- if (typeof options.concurrency !== "number") {
- return Promise.reject(
- new TypeError("'concurrency' must be a number but it is " +
- util.classString(options.concurrency)));
- }
- limit = options.concurrency;
- } else {
- return Promise.reject(new TypeError(
- "options argument must be an object but it is " +
- util.classString(options)));
- }
- }
- limit = typeof limit === "number" &&
- isFinite(limit) && limit >= 1 ? limit : 0;
- return new MappingPromiseArray(promises, fn, limit, _filter).promise();
- }
-
- Promise.prototype.map = function (fn, options) {
- return map(this, fn, options, null);
- };
-
- Promise.map = function (promises, fn, options, _filter) {
- return map(promises, fn, options, _filter);
- };
-
-
- };
-
- },{"./util":36}],19:[function(_dereq_,module,exports){
- "use strict";
- module.exports =
- function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
- var util = _dereq_("./util");
- var tryCatch = util.tryCatch;
-
- Promise.method = function (fn) {
- if (typeof fn !== "function") {
- throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
- }
- return function () {
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- ret._pushContext();
- var value = tryCatch(fn).apply(this, arguments);
- var promiseCreated = ret._popContext();
- debug.checkForgottenReturns(
- value, promiseCreated, "Promise.method", ret);
- ret._resolveFromSyncValue(value);
- return ret;
- };
- };
-
- Promise.attempt = Promise["try"] = function (fn) {
- if (typeof fn !== "function") {
- return apiRejection("expecting a function but got " + util.classString(fn));
- }
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- ret._pushContext();
- var value;
- if (arguments.length > 1) {
- debug.deprecated("calling Promise.try with more than 1 argument");
- var arg = arguments[1];
- var ctx = arguments[2];
- value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
- : tryCatch(fn).call(ctx, arg);
- } else {
- value = tryCatch(fn)();
- }
- var promiseCreated = ret._popContext();
- debug.checkForgottenReturns(
- value, promiseCreated, "Promise.try", ret);
- ret._resolveFromSyncValue(value);
- return ret;
- };
-
- Promise.prototype._resolveFromSyncValue = function (value) {
- if (value === util.errorObj) {
- this._rejectCallback(value.e, false);
- } else {
- this._resolveCallback(value, true);
- }
- };
- };
-
- },{"./util":36}],20:[function(_dereq_,module,exports){
- "use strict";
- var util = _dereq_("./util");
- var maybeWrapAsError = util.maybeWrapAsError;
- var errors = _dereq_("./errors");
- var OperationalError = errors.OperationalError;
- var es5 = _dereq_("./es5");
-
- function isUntypedError(obj) {
- return obj instanceof Error &&
- es5.getPrototypeOf(obj) === Error.prototype;
- }
-
- var rErrorKey = /^(?:name|message|stack|cause)$/;
- function wrapAsOperationalError(obj) {
- var ret;
- if (isUntypedError(obj)) {
- ret = new OperationalError(obj);
- ret.name = obj.name;
- ret.message = obj.message;
- ret.stack = obj.stack;
- var keys = es5.keys(obj);
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- if (!rErrorKey.test(key)) {
- ret[key] = obj[key];
- }
- }
- return ret;
- }
- util.markAsOriginatingFromRejection(obj);
- return obj;
- }
-
- function nodebackForPromise(promise, multiArgs) {
- return function(err, value) {
- if (promise === null) return;
- if (err) {
- var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
- promise._attachExtraTrace(wrapped);
- promise._reject(wrapped);
- } else if (!multiArgs) {
- promise._fulfill(value);
- } else {
- var args = [].slice.call(arguments, 1);;
- promise._fulfill(args);
- }
- promise = null;
- };
- }
-
- module.exports = nodebackForPromise;
-
- },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise) {
- var util = _dereq_("./util");
- var async = Promise._async;
- var tryCatch = util.tryCatch;
- var errorObj = util.errorObj;
-
- function spreadAdapter(val, nodeback) {
- var promise = this;
- if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
- var ret =
- tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
- if (ret === errorObj) {
- async.throwLater(ret.e);
- }
- }
-
- function successAdapter(val, nodeback) {
- var promise = this;
- var receiver = promise._boundValue();
- var ret = val === undefined
- ? tryCatch(nodeback).call(receiver, null)
- : tryCatch(nodeback).call(receiver, null, val);
- if (ret === errorObj) {
- async.throwLater(ret.e);
- }
- }
- function errorAdapter(reason, nodeback) {
- var promise = this;
- if (!reason) {
- var newReason = new Error(reason + "");
- newReason.cause = reason;
- reason = newReason;
- }
- var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
- if (ret === errorObj) {
- async.throwLater(ret.e);
- }
- }
-
- Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
- options) {
- if (typeof nodeback == "function") {
- var adapter = successAdapter;
- if (options !== undefined && Object(options).spread) {
- adapter = spreadAdapter;
- }
- this._then(
- adapter,
- errorAdapter,
- undefined,
- this,
- nodeback
- );
- }
- return this;
- };
- };
-
- },{"./util":36}],22:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function() {
- var makeSelfResolutionError = function () {
- return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- };
- var reflectHandler = function() {
- return new Promise.PromiseInspection(this._target());
- };
- var apiRejection = function(msg) {
- return Promise.reject(new TypeError(msg));
- };
- function Proxyable() {}
- var UNDEFINED_BINDING = {};
- var util = _dereq_("./util");
-
- var getDomain;
- if (util.isNode) {
- getDomain = function() {
- var ret = process.domain;
- if (ret === undefined) ret = null;
- return ret;
- };
- } else {
- getDomain = function() {
- return null;
- };
- }
- util.notEnumerableProp(Promise, "_getDomain", getDomain);
-
- var es5 = _dereq_("./es5");
- var Async = _dereq_("./async");
- var async = new Async();
- es5.defineProperty(Promise, "_async", {value: async});
- var errors = _dereq_("./errors");
- var TypeError = Promise.TypeError = errors.TypeError;
- Promise.RangeError = errors.RangeError;
- var CancellationError = Promise.CancellationError = errors.CancellationError;
- Promise.TimeoutError = errors.TimeoutError;
- Promise.OperationalError = errors.OperationalError;
- Promise.RejectionError = errors.OperationalError;
- Promise.AggregateError = errors.AggregateError;
- var INTERNAL = function(){};
- var APPLY = {};
- var NEXT_FILTER = {};
- var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
- var PromiseArray =
- _dereq_("./promise_array")(Promise, INTERNAL,
- tryConvertToPromise, apiRejection, Proxyable);
- var Context = _dereq_("./context")(Promise);
- /*jshint unused:false*/
- var createContext = Context.create;
- var debug = _dereq_("./debuggability")(Promise, Context);
- var CapturedTrace = debug.CapturedTrace;
- var PassThroughHandlerContext =
- _dereq_("./finally")(Promise, tryConvertToPromise);
- var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
- var nodebackForPromise = _dereq_("./nodeback");
- var errorObj = util.errorObj;
- var tryCatch = util.tryCatch;
- function check(self, executor) {
- if (typeof executor !== "function") {
- throw new TypeError("expecting a function but got " + util.classString(executor));
- }
- if (self.constructor !== Promise) {
- throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- }
-
- function Promise(executor) {
- this._bitField = 0;
- this._fulfillmentHandler0 = undefined;
- this._rejectionHandler0 = undefined;
- this._promise0 = undefined;
- this._receiver0 = undefined;
- if (executor !== INTERNAL) {
- check(this, executor);
- this._resolveFromExecutor(executor);
- }
- this._promiseCreated();
- this._fireEvent("promiseCreated", this);
- }
-
- Promise.prototype.toString = function () {
- return "[object Promise]";
- };
-
- Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
- var len = arguments.length;
- if (len > 1) {
- var catchInstances = new Array(len - 1),
- j = 0, i;
- for (i = 0; i < len - 1; ++i) {
- var item = arguments[i];
- if (util.isObject(item)) {
- catchInstances[j++] = item;
- } else {
- return apiRejection("expecting an object but got " +
- "A catch statement predicate " + util.classString(item));
- }
- }
- catchInstances.length = j;
- fn = arguments[i];
- return this.then(undefined, catchFilter(catchInstances, fn, this));
- }
- return this.then(undefined, fn);
- };
-
- Promise.prototype.reflect = function () {
- return this._then(reflectHandler,
- reflectHandler, undefined, this, undefined);
- };
-
- Promise.prototype.then = function (didFulfill, didReject) {
- if (debug.warnings() && arguments.length > 0 &&
- typeof didFulfill !== "function" &&
- typeof didReject !== "function") {
- var msg = ".then() only accepts functions but was passed: " +
- util.classString(didFulfill);
- if (arguments.length > 1) {
- msg += ", " + util.classString(didReject);
- }
- this._warn(msg);
- }
- return this._then(didFulfill, didReject, undefined, undefined, undefined);
- };
-
- Promise.prototype.done = function (didFulfill, didReject) {
- var promise =
- this._then(didFulfill, didReject, undefined, undefined, undefined);
- promise._setIsFinal();
- };
-
- Promise.prototype.spread = function (fn) {
- if (typeof fn !== "function") {
- return apiRejection("expecting a function but got " + util.classString(fn));
- }
- return this.all()._then(fn, undefined, undefined, APPLY, undefined);
- };
-
- Promise.prototype.toJSON = function () {
- var ret = {
- isFulfilled: false,
- isRejected: false,
- fulfillmentValue: undefined,
- rejectionReason: undefined
- };
- if (this.isFulfilled()) {
- ret.fulfillmentValue = this.value();
- ret.isFulfilled = true;
- } else if (this.isRejected()) {
- ret.rejectionReason = this.reason();
- ret.isRejected = true;
- }
- return ret;
- };
-
- Promise.prototype.all = function () {
- if (arguments.length > 0) {
- this._warn(".all() was passed arguments but it does not take any");
- }
- return new PromiseArray(this).promise();
- };
-
- Promise.prototype.error = function (fn) {
- return this.caught(util.originatesFromRejection, fn);
- };
-
- Promise.getNewLibraryCopy = module.exports;
-
- Promise.is = function (val) {
- return val instanceof Promise;
- };
-
- Promise.fromNode = Promise.fromCallback = function(fn) {
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
- : false;
- var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
- if (result === errorObj) {
- ret._rejectCallback(result.e, true);
- }
- if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
- return ret;
- };
-
- Promise.all = function (promises) {
- return new PromiseArray(promises).promise();
- };
-
- Promise.cast = function (obj) {
- var ret = tryConvertToPromise(obj);
- if (!(ret instanceof Promise)) {
- ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- ret._setFulfilled();
- ret._rejectionHandler0 = obj;
- }
- return ret;
- };
-
- Promise.resolve = Promise.fulfilled = Promise.cast;
-
- Promise.reject = Promise.rejected = function (reason) {
- var ret = new Promise(INTERNAL);
- ret._captureStackTrace();
- ret._rejectCallback(reason, true);
- return ret;
- };
-
- Promise.setScheduler = function(fn) {
- if (typeof fn !== "function") {
- throw new TypeError("expecting a function but got " + util.classString(fn));
- }
- return async.setScheduler(fn);
- };
-
- Promise.prototype._then = function (
- didFulfill,
- didReject,
- _, receiver,
- internalData
- ) {
- var haveInternalData = internalData !== undefined;
- var promise = haveInternalData ? internalData : new Promise(INTERNAL);
- var target = this._target();
- var bitField = target._bitField;
-
- if (!haveInternalData) {
- promise._propagateFrom(this, 3);
- promise._captureStackTrace();
- if (receiver === undefined &&
- ((this._bitField & 2097152) !== 0)) {
- if (!((bitField & 50397184) === 0)) {
- receiver = this._boundValue();
- } else {
- receiver = target === this ? undefined : this._boundTo;
- }
- }
- this._fireEvent("promiseChained", this, promise);
- }
-
- var domain = getDomain();
- if (!((bitField & 50397184) === 0)) {
- var handler, value, settler = target._settlePromiseCtx;
- if (((bitField & 33554432) !== 0)) {
- value = target._rejectionHandler0;
- handler = didFulfill;
- } else if (((bitField & 16777216) !== 0)) {
- value = target._fulfillmentHandler0;
- handler = didReject;
- target._unsetRejectionIsUnhandled();
- } else {
- settler = target._settlePromiseLateCancellationObserver;
- value = new CancellationError("late cancellation observer");
- target._attachExtraTrace(value);
- handler = didReject;
- }
-
- async.invoke(settler, target, {
- handler: domain === null ? handler
- : (typeof handler === "function" &&
- util.domainBind(domain, handler)),
- promise: promise,
- receiver: receiver,
- value: value
- });
- } else {
- target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
- }
-
- return promise;
- };
-
- Promise.prototype._length = function () {
- return this._bitField & 65535;
- };
-
- Promise.prototype._isFateSealed = function () {
- return (this._bitField & 117506048) !== 0;
- };
-
- Promise.prototype._isFollowing = function () {
- return (this._bitField & 67108864) === 67108864;
- };
-
- Promise.prototype._setLength = function (len) {
- this._bitField = (this._bitField & -65536) |
- (len & 65535);
- };
-
- Promise.prototype._setFulfilled = function () {
- this._bitField = this._bitField | 33554432;
- this._fireEvent("promiseFulfilled", this);
- };
-
- Promise.prototype._setRejected = function () {
- this._bitField = this._bitField | 16777216;
- this._fireEvent("promiseRejected", this);
- };
-
- Promise.prototype._setFollowing = function () {
- this._bitField = this._bitField | 67108864;
- this._fireEvent("promiseResolved", this);
- };
-
- Promise.prototype._setIsFinal = function () {
- this._bitField = this._bitField | 4194304;
- };
-
- Promise.prototype._isFinal = function () {
- return (this._bitField & 4194304) > 0;
- };
-
- Promise.prototype._unsetCancelled = function() {
- this._bitField = this._bitField & (~65536);
- };
-
- Promise.prototype._setCancelled = function() {
- this._bitField = this._bitField | 65536;
- this._fireEvent("promiseCancelled", this);
- };
-
- Promise.prototype._setWillBeCancelled = function() {
- this._bitField = this._bitField | 8388608;
- };
-
- Promise.prototype._setAsyncGuaranteed = function() {
- if (async.hasCustomScheduler()) return;
- this._bitField = this._bitField | 134217728;
- };
-
- Promise.prototype._receiverAt = function (index) {
- var ret = index === 0 ? this._receiver0 : this[
- index * 4 - 4 + 3];
- if (ret === UNDEFINED_BINDING) {
- return undefined;
- } else if (ret === undefined && this._isBound()) {
- return this._boundValue();
- }
- return ret;
- };
-
- Promise.prototype._promiseAt = function (index) {
- return this[
- index * 4 - 4 + 2];
- };
-
- Promise.prototype._fulfillmentHandlerAt = function (index) {
- return this[
- index * 4 - 4 + 0];
- };
-
- Promise.prototype._rejectionHandlerAt = function (index) {
- return this[
- index * 4 - 4 + 1];
- };
-
- Promise.prototype._boundValue = function() {};
-
- Promise.prototype._migrateCallback0 = function (follower) {
- var bitField = follower._bitField;
- var fulfill = follower._fulfillmentHandler0;
- var reject = follower._rejectionHandler0;
- var promise = follower._promise0;
- var receiver = follower._receiverAt(0);
- if (receiver === undefined) receiver = UNDEFINED_BINDING;
- this._addCallbacks(fulfill, reject, promise, receiver, null);
- };
-
- Promise.prototype._migrateCallbackAt = function (follower, index) {
- var fulfill = follower._fulfillmentHandlerAt(index);
- var reject = follower._rejectionHandlerAt(index);
- var promise = follower._promiseAt(index);
- var receiver = follower._receiverAt(index);
- if (receiver === undefined) receiver = UNDEFINED_BINDING;
- this._addCallbacks(fulfill, reject, promise, receiver, null);
- };
-
- Promise.prototype._addCallbacks = function (
- fulfill,
- reject,
- promise,
- receiver,
- domain
- ) {
- var index = this._length();
-
- if (index >= 65535 - 4) {
- index = 0;
- this._setLength(0);
- }
-
- if (index === 0) {
- this._promise0 = promise;
- this._receiver0 = receiver;
- if (typeof fulfill === "function") {
- this._fulfillmentHandler0 =
- domain === null ? fulfill : util.domainBind(domain, fulfill);
- }
- if (typeof reject === "function") {
- this._rejectionHandler0 =
- domain === null ? reject : util.domainBind(domain, reject);
- }
- } else {
- var base = index * 4 - 4;
- this[base + 2] = promise;
- this[base + 3] = receiver;
- if (typeof fulfill === "function") {
- this[base + 0] =
- domain === null ? fulfill : util.domainBind(domain, fulfill);
- }
- if (typeof reject === "function") {
- this[base + 1] =
- domain === null ? reject : util.domainBind(domain, reject);
- }
- }
- this._setLength(index + 1);
- return index;
- };
-
- Promise.prototype._proxy = function (proxyable, arg) {
- this._addCallbacks(undefined, undefined, arg, proxyable, null);
- };
-
- Promise.prototype._resolveCallback = function(value, shouldBind) {
- if (((this._bitField & 117506048) !== 0)) return;
- if (value === this)
- return this._rejectCallback(makeSelfResolutionError(), false);
- var maybePromise = tryConvertToPromise(value, this);
- if (!(maybePromise instanceof Promise)) return this._fulfill(value);
-
- if (shouldBind) this._propagateFrom(maybePromise, 2);
-
- var promise = maybePromise._target();
-
- if (promise === this) {
- this._reject(makeSelfResolutionError());
- return;
- }
-
- var bitField = promise._bitField;
- if (((bitField & 50397184) === 0)) {
- var len = this._length();
- if (len > 0) promise._migrateCallback0(this);
- for (var i = 1; i < len; ++i) {
- promise._migrateCallbackAt(this, i);
- }
- this._setFollowing();
- this._setLength(0);
- this._setFollowee(promise);
- } else if (((bitField & 33554432) !== 0)) {
- this._fulfill(promise._value());
- } else if (((bitField & 16777216) !== 0)) {
- this._reject(promise._reason());
- } else {
- var reason = new CancellationError("late cancellation observer");
- promise._attachExtraTrace(reason);
- this._reject(reason);
- }
- };
-
- Promise.prototype._rejectCallback =
- function(reason, synchronous, ignoreNonErrorWarnings) {
- var trace = util.ensureErrorObject(reason);
- var hasStack = trace === reason;
- if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
- var message = "a promise was rejected with a non-error: " +
- util.classString(reason);
- this._warn(message, true);
- }
- this._attachExtraTrace(trace, synchronous ? hasStack : false);
- this._reject(reason);
- };
-
- Promise.prototype._resolveFromExecutor = function (executor) {
- var promise = this;
- this._captureStackTrace();
- this._pushContext();
- var synchronous = true;
- var r = this._execute(executor, function(value) {
- promise._resolveCallback(value);
- }, function (reason) {
- promise._rejectCallback(reason, synchronous);
- });
- synchronous = false;
- this._popContext();
-
- if (r !== undefined) {
- promise._rejectCallback(r, true);
- }
- };
-
- Promise.prototype._settlePromiseFromHandler = function (
- handler, receiver, value, promise
- ) {
- var bitField = promise._bitField;
- if (((bitField & 65536) !== 0)) return;
- promise._pushContext();
- var x;
- if (receiver === APPLY) {
- if (!value || typeof value.length !== "number") {
- x = errorObj;
- x.e = new TypeError("cannot .spread() a non-array: " +
- util.classString(value));
- } else {
- x = tryCatch(handler).apply(this._boundValue(), value);
- }
- } else {
- x = tryCatch(handler).call(receiver, value);
- }
- var promiseCreated = promise._popContext();
- bitField = promise._bitField;
- if (((bitField & 65536) !== 0)) return;
-
- if (x === NEXT_FILTER) {
- promise._reject(value);
- } else if (x === errorObj) {
- promise._rejectCallback(x.e, false);
- } else {
- debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
- promise._resolveCallback(x);
- }
- };
-
- Promise.prototype._target = function() {
- var ret = this;
- while (ret._isFollowing()) ret = ret._followee();
- return ret;
- };
-
- Promise.prototype._followee = function() {
- return this._rejectionHandler0;
- };
-
- Promise.prototype._setFollowee = function(promise) {
- this._rejectionHandler0 = promise;
- };
-
- Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
- var isPromise = promise instanceof Promise;
- var bitField = this._bitField;
- var asyncGuaranteed = ((bitField & 134217728) !== 0);
- if (((bitField & 65536) !== 0)) {
- if (isPromise) promise._invokeInternalOnCancel();
-
- if (receiver instanceof PassThroughHandlerContext &&
- receiver.isFinallyHandler()) {
- receiver.cancelPromise = promise;
- if (tryCatch(handler).call(receiver, value) === errorObj) {
- promise._reject(errorObj.e);
- }
- } else if (handler === reflectHandler) {
- promise._fulfill(reflectHandler.call(receiver));
- } else if (receiver instanceof Proxyable) {
- receiver._promiseCancelled(promise);
- } else if (isPromise || promise instanceof PromiseArray) {
- promise._cancel();
- } else {
- receiver.cancel();
- }
- } else if (typeof handler === "function") {
- if (!isPromise) {
- handler.call(receiver, value, promise);
- } else {
- if (asyncGuaranteed) promise._setAsyncGuaranteed();
- this._settlePromiseFromHandler(handler, receiver, value, promise);
- }
- } else if (receiver instanceof Proxyable) {
- if (!receiver._isResolved()) {
- if (((bitField & 33554432) !== 0)) {
- receiver._promiseFulfilled(value, promise);
- } else {
- receiver._promiseRejected(value, promise);
- }
- }
- } else if (isPromise) {
- if (asyncGuaranteed) promise._setAsyncGuaranteed();
- if (((bitField & 33554432) !== 0)) {
- promise._fulfill(value);
- } else {
- promise._reject(value);
- }
- }
- };
-
- Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
- var handler = ctx.handler;
- var promise = ctx.promise;
- var receiver = ctx.receiver;
- var value = ctx.value;
- if (typeof handler === "function") {
- if (!(promise instanceof Promise)) {
- handler.call(receiver, value, promise);
- } else {
- this._settlePromiseFromHandler(handler, receiver, value, promise);
- }
- } else if (promise instanceof Promise) {
- promise._reject(value);
- }
- };
-
- Promise.prototype._settlePromiseCtx = function(ctx) {
- this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
- };
-
- Promise.prototype._settlePromise0 = function(handler, value, bitField) {
- var promise = this._promise0;
- var receiver = this._receiverAt(0);
- this._promise0 = undefined;
- this._receiver0 = undefined;
- this._settlePromise(promise, handler, receiver, value);
- };
-
- Promise.prototype._clearCallbackDataAtIndex = function(index) {
- var base = index * 4 - 4;
- this[base + 2] =
- this[base + 3] =
- this[base + 0] =
- this[base + 1] = undefined;
- };
-
- Promise.prototype._fulfill = function (value) {
- var bitField = this._bitField;
- if (((bitField & 117506048) >>> 16)) return;
- if (value === this) {
- var err = makeSelfResolutionError();
- this._attachExtraTrace(err);
- return this._reject(err);
- }
- this._setFulfilled();
- this._rejectionHandler0 = value;
-
- if ((bitField & 65535) > 0) {
- if (((bitField & 134217728) !== 0)) {
- this._settlePromises();
- } else {
- async.settlePromises(this);
- }
- }
- };
-
- Promise.prototype._reject = function (reason) {
- var bitField = this._bitField;
- if (((bitField & 117506048) >>> 16)) return;
- this._setRejected();
- this._fulfillmentHandler0 = reason;
-
- if (this._isFinal()) {
- return async.fatalError(reason, util.isNode);
- }
-
- if ((bitField & 65535) > 0) {
- async.settlePromises(this);
- } else {
- this._ensurePossibleRejectionHandled();
- }
- };
-
- Promise.prototype._fulfillPromises = function (len, value) {
- for (var i = 1; i < len; i++) {
- var handler = this._fulfillmentHandlerAt(i);
- var promise = this._promiseAt(i);
- var receiver = this._receiverAt(i);
- this._clearCallbackDataAtIndex(i);
- this._settlePromise(promise, handler, receiver, value);
- }
- };
-
- Promise.prototype._rejectPromises = function (len, reason) {
- for (var i = 1; i < len; i++) {
- var handler = this._rejectionHandlerAt(i);
- var promise = this._promiseAt(i);
- var receiver = this._receiverAt(i);
- this._clearCallbackDataAtIndex(i);
- this._settlePromise(promise, handler, receiver, reason);
- }
- };
-
- Promise.prototype._settlePromises = function () {
- var bitField = this._bitField;
- var len = (bitField & 65535);
-
- if (len > 0) {
- if (((bitField & 16842752) !== 0)) {
- var reason = this._fulfillmentHandler0;
- this._settlePromise0(this._rejectionHandler0, reason, bitField);
- this._rejectPromises(len, reason);
- } else {
- var value = this._rejectionHandler0;
- this._settlePromise0(this._fulfillmentHandler0, value, bitField);
- this._fulfillPromises(len, value);
- }
- this._setLength(0);
- }
- this._clearCancellationData();
- };
-
- Promise.prototype._settledValue = function() {
- var bitField = this._bitField;
- if (((bitField & 33554432) !== 0)) {
- return this._rejectionHandler0;
- } else if (((bitField & 16777216) !== 0)) {
- return this._fulfillmentHandler0;
- }
- };
-
- function deferResolve(v) {this.promise._resolveCallback(v);}
- function deferReject(v) {this.promise._rejectCallback(v, false);}
-
- Promise.defer = Promise.pending = function() {
- debug.deprecated("Promise.defer", "new Promise");
- var promise = new Promise(INTERNAL);
- return {
- promise: promise,
- resolve: deferResolve,
- reject: deferReject
- };
- };
-
- util.notEnumerableProp(Promise,
- "_makeSelfResolutionError",
- makeSelfResolutionError);
-
- _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
- debug);
- _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
- _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
- _dereq_("./direct_resolve")(Promise);
- _dereq_("./synchronous_inspection")(Promise);
- _dereq_("./join")(
- Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
- Promise.Promise = Promise;
- Promise.version = "3.4.6";
- _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
- _dereq_('./call_get.js')(Promise);
- _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
- _dereq_('./timers.js')(Promise, INTERNAL, debug);
- _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
- _dereq_('./nodeify.js')(Promise);
- _dereq_('./promisify.js')(Promise, INTERNAL);
- _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
- _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
- _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
- _dereq_('./settle.js')(Promise, PromiseArray, debug);
- _dereq_('./some.js')(Promise, PromiseArray, apiRejection);
- _dereq_('./filter.js')(Promise, INTERNAL);
- _dereq_('./each.js')(Promise, INTERNAL);
- _dereq_('./any.js')(Promise);
-
- util.toFastProperties(Promise);
- util.toFastProperties(Promise.prototype);
- function fillTypes(value) {
- var p = new Promise(INTERNAL);
- p._fulfillmentHandler0 = value;
- p._rejectionHandler0 = value;
- p._promise0 = value;
- p._receiver0 = value;
- }
- // Complete slack tracking, opt out of field-type tracking and
- // stabilize map
- fillTypes({a: 1});
- fillTypes({b: 2});
- fillTypes({c: 3});
- fillTypes(1);
- fillTypes(function(){});
- fillTypes(undefined);
- fillTypes(false);
- fillTypes(new Promise(INTERNAL));
- debug.setBounds(Async.firstLineError, util.lastLineError);
- return Promise;
-
- };
-
- },{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL, tryConvertToPromise,
- apiRejection, Proxyable) {
- var util = _dereq_("./util");
- var isArray = util.isArray;
-
- function toResolutionValue(val) {
- switch(val) {
- case -2: return [];
- case -3: return {};
- }
- }
-
- function PromiseArray(values) {
- var promise = this._promise = new Promise(INTERNAL);
- if (values instanceof Promise) {
- promise._propagateFrom(values, 3);
- }
- promise._setOnCancel(this);
- this._values = values;
- this._length = 0;
- this._totalResolved = 0;
- this._init(undefined, -2);
- }
- util.inherits(PromiseArray, Proxyable);
-
- PromiseArray.prototype.length = function () {
- return this._length;
- };
-
- PromiseArray.prototype.promise = function () {
- return this._promise;
- };
-
- PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
- var values = tryConvertToPromise(this._values, this._promise);
- if (values instanceof Promise) {
- values = values._target();
- var bitField = values._bitField;
- ;
- this._values = values;
-
- if (((bitField & 50397184) === 0)) {
- this._promise._setAsyncGuaranteed();
- return values._then(
- init,
- this._reject,
- undefined,
- this,
- resolveValueIfEmpty
- );
- } else if (((bitField & 33554432) !== 0)) {
- values = values._value();
- } else if (((bitField & 16777216) !== 0)) {
- return this._reject(values._reason());
- } else {
- return this._cancel();
- }
- }
- values = util.asArray(values);
- if (values === null) {
- var err = apiRejection(
- "expecting an array or an iterable object but got " + util.classString(values)).reason();
- this._promise._rejectCallback(err, false);
- return;
- }
-
- if (values.length === 0) {
- if (resolveValueIfEmpty === -5) {
- this._resolveEmptyArray();
- }
- else {
- this._resolve(toResolutionValue(resolveValueIfEmpty));
- }
- return;
- }
- this._iterate(values);
- };
-
- PromiseArray.prototype._iterate = function(values) {
- var len = this.getActualLength(values.length);
- this._length = len;
- this._values = this.shouldCopyValues() ? new Array(len) : this._values;
- var result = this._promise;
- var isResolved = false;
- var bitField = null;
- for (var i = 0; i < len; ++i) {
- var maybePromise = tryConvertToPromise(values[i], result);
-
- if (maybePromise instanceof Promise) {
- maybePromise = maybePromise._target();
- bitField = maybePromise._bitField;
- } else {
- bitField = null;
- }
-
- if (isResolved) {
- if (bitField !== null) {
- maybePromise.suppressUnhandledRejections();
- }
- } else if (bitField !== null) {
- if (((bitField & 50397184) === 0)) {
- maybePromise._proxy(this, i);
- this._values[i] = maybePromise;
- } else if (((bitField & 33554432) !== 0)) {
- isResolved = this._promiseFulfilled(maybePromise._value(), i);
- } else if (((bitField & 16777216) !== 0)) {
- isResolved = this._promiseRejected(maybePromise._reason(), i);
- } else {
- isResolved = this._promiseCancelled(i);
- }
- } else {
- isResolved = this._promiseFulfilled(maybePromise, i);
- }
- }
- if (!isResolved) result._setAsyncGuaranteed();
- };
-
- PromiseArray.prototype._isResolved = function () {
- return this._values === null;
- };
-
- PromiseArray.prototype._resolve = function (value) {
- this._values = null;
- this._promise._fulfill(value);
- };
-
- PromiseArray.prototype._cancel = function() {
- if (this._isResolved() || !this._promise._isCancellable()) return;
- this._values = null;
- this._promise._cancel();
- };
-
- PromiseArray.prototype._reject = function (reason) {
- this._values = null;
- this._promise._rejectCallback(reason, false);
- };
-
- PromiseArray.prototype._promiseFulfilled = function (value, index) {
- this._values[index] = value;
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= this._length) {
- this._resolve(this._values);
- return true;
- }
- return false;
- };
-
- PromiseArray.prototype._promiseCancelled = function() {
- this._cancel();
- return true;
- };
-
- PromiseArray.prototype._promiseRejected = function (reason) {
- this._totalResolved++;
- this._reject(reason);
- return true;
- };
-
- PromiseArray.prototype._resultCancelled = function() {
- if (this._isResolved()) return;
- var values = this._values;
- this._cancel();
- if (values instanceof Promise) {
- values.cancel();
- } else {
- for (var i = 0; i < values.length; ++i) {
- if (values[i] instanceof Promise) {
- values[i].cancel();
- }
- }
- }
- };
-
- PromiseArray.prototype.shouldCopyValues = function () {
- return true;
- };
-
- PromiseArray.prototype.getActualLength = function (len) {
- return len;
- };
-
- return PromiseArray;
- };
-
- },{"./util":36}],24:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var THIS = {};
- var util = _dereq_("./util");
- var nodebackForPromise = _dereq_("./nodeback");
- var withAppended = util.withAppended;
- var maybeWrapAsError = util.maybeWrapAsError;
- var canEvaluate = util.canEvaluate;
- var TypeError = _dereq_("./errors").TypeError;
- var defaultSuffix = "Async";
- var defaultPromisified = {__isPromisified__: true};
- var noCopyProps = [
- "arity", "length",
- "name",
- "arguments",
- "caller",
- "callee",
- "prototype",
- "__isPromisified__"
- ];
- var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
-
- var defaultFilter = function(name) {
- return util.isIdentifier(name) &&
- name.charAt(0) !== "_" &&
- name !== "constructor";
- };
-
- function propsFilter(key) {
- return !noCopyPropsPattern.test(key);
- }
-
- function isPromisified(fn) {
- try {
- return fn.__isPromisified__ === true;
- }
- catch (e) {
- return false;
- }
- }
-
- function hasPromisified(obj, key, suffix) {
- var val = util.getDataPropertyOrDefault(obj, key + suffix,
- defaultPromisified);
- return val ? isPromisified(val) : false;
- }
- function checkValid(ret, suffix, suffixRegexp) {
- for (var i = 0; i < ret.length; i += 2) {
- var key = ret[i];
- if (suffixRegexp.test(key)) {
- var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
- for (var j = 0; j < ret.length; j += 2) {
- if (ret[j] === keyWithoutAsyncSuffix) {
- throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
- .replace("%s", suffix));
- }
- }
- }
- }
- }
-
- function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
- var keys = util.inheritedDataKeys(obj);
- var ret = [];
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- var value = obj[key];
- var passesDefaultFilter = filter === defaultFilter
- ? true : defaultFilter(key, value, obj);
- if (typeof value === "function" &&
- !isPromisified(value) &&
- !hasPromisified(obj, key, suffix) &&
- filter(key, value, obj, passesDefaultFilter)) {
- ret.push(key, value);
- }
- }
- checkValid(ret, suffix, suffixRegexp);
- return ret;
- }
-
- var escapeIdentRegex = function(str) {
- return str.replace(/([$])/, "\\$");
- };
-
- var makeNodePromisifiedEval;
- if (!true) {
- var switchCaseArgumentOrder = function(likelyArgumentCount) {
- var ret = [likelyArgumentCount];
- var min = Math.max(0, likelyArgumentCount - 1 - 3);
- for(var i = likelyArgumentCount - 1; i >= min; --i) {
- ret.push(i);
- }
- for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
- ret.push(i);
- }
- return ret;
- };
-
- var argumentSequence = function(argumentCount) {
- return util.filledRange(argumentCount, "_arg", "");
- };
-
- var parameterDeclaration = function(parameterCount) {
- return util.filledRange(
- Math.max(parameterCount, 3), "_arg", "");
- };
-
- var parameterCount = function(fn) {
- if (typeof fn.length === "number") {
- return Math.max(Math.min(fn.length, 1023 + 1), 0);
- }
- return 0;
- };
-
- makeNodePromisifiedEval =
- function(callback, receiver, originalName, fn, _, multiArgs) {
- var newParameterCount = Math.max(0, parameterCount(fn) - 1);
- var argumentOrder = switchCaseArgumentOrder(newParameterCount);
- var shouldProxyThis = typeof callback === "string" || receiver === THIS;
-
- function generateCallForArgumentCount(count) {
- var args = argumentSequence(count).join(", ");
- var comma = count > 0 ? ", " : "";
- var ret;
- if (shouldProxyThis) {
- ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
- } else {
- ret = receiver === undefined
- ? "ret = callback({{args}}, nodeback); break;\n"
- : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
- }
- return ret.replace("{{args}}", args).replace(", ", comma);
- }
-
- function generateArgumentSwitchCase() {
- var ret = "";
- for (var i = 0; i < argumentOrder.length; ++i) {
- ret += "case " + argumentOrder[i] +":" +
- generateCallForArgumentCount(argumentOrder[i]);
- }
-
- ret += " \n\
- default: \n\
- var args = new Array(len + 1); \n\
- var i = 0; \n\
- for (var i = 0; i < len; ++i) { \n\
- args[i] = arguments[i]; \n\
- } \n\
- args[i] = nodeback; \n\
- [CodeForCall] \n\
- break; \n\
- ".replace("[CodeForCall]", (shouldProxyThis
- ? "ret = callback.apply(this, args);\n"
- : "ret = callback.apply(receiver, args);\n"));
- return ret;
- }
-
- var getFunctionCode = typeof callback === "string"
- ? ("this != null ? this['"+callback+"'] : fn")
- : "fn";
- var body = "'use strict'; \n\
- var ret = function (Parameters) { \n\
- 'use strict'; \n\
- var len = arguments.length; \n\
- var promise = new Promise(INTERNAL); \n\
- promise._captureStackTrace(); \n\
- var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
- var ret; \n\
- var callback = tryCatch([GetFunctionCode]); \n\
- switch(len) { \n\
- [CodeForSwitchCase] \n\
- } \n\
- if (ret === errorObj) { \n\
- promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
- } \n\
- if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
- return promise; \n\
- }; \n\
- notEnumerableProp(ret, '__isPromisified__', true); \n\
- return ret; \n\
- ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
- .replace("[GetFunctionCode]", getFunctionCode);
- body = body.replace("Parameters", parameterDeclaration(newParameterCount));
- return new Function("Promise",
- "fn",
- "receiver",
- "withAppended",
- "maybeWrapAsError",
- "nodebackForPromise",
- "tryCatch",
- "errorObj",
- "notEnumerableProp",
- "INTERNAL",
- body)(
- Promise,
- fn,
- receiver,
- withAppended,
- maybeWrapAsError,
- nodebackForPromise,
- util.tryCatch,
- util.errorObj,
- util.notEnumerableProp,
- INTERNAL);
- };
- }
-
- function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
- var defaultThis = (function() {return this;})();
- var method = callback;
- if (typeof method === "string") {
- callback = fn;
- }
- function promisified() {
- var _receiver = receiver;
- if (receiver === THIS) _receiver = this;
- var promise = new Promise(INTERNAL);
- promise._captureStackTrace();
- var cb = typeof method === "string" && this !== defaultThis
- ? this[method] : callback;
- var fn = nodebackForPromise(promise, multiArgs);
- try {
- cb.apply(_receiver, withAppended(arguments, fn));
- } catch(e) {
- promise._rejectCallback(maybeWrapAsError(e), true, true);
- }
- if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
- return promise;
- }
- util.notEnumerableProp(promisified, "__isPromisified__", true);
- return promisified;
- }
-
- var makeNodePromisified = canEvaluate
- ? makeNodePromisifiedEval
- : makeNodePromisifiedClosure;
-
- function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
- var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
- var methods =
- promisifiableMethods(obj, suffix, suffixRegexp, filter);
-
- for (var i = 0, len = methods.length; i < len; i+= 2) {
- var key = methods[i];
- var fn = methods[i+1];
- var promisifiedKey = key + suffix;
- if (promisifier === makeNodePromisified) {
- obj[promisifiedKey] =
- makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
- } else {
- var promisified = promisifier(fn, function() {
- return makeNodePromisified(key, THIS, key,
- fn, suffix, multiArgs);
- });
- util.notEnumerableProp(promisified, "__isPromisified__", true);
- obj[promisifiedKey] = promisified;
- }
- }
- util.toFastProperties(obj);
- return obj;
- }
-
- function promisify(callback, receiver, multiArgs) {
- return makeNodePromisified(callback, receiver, undefined,
- callback, null, multiArgs);
- }
-
- Promise.promisify = function (fn, options) {
- if (typeof fn !== "function") {
- throw new TypeError("expecting a function but got " + util.classString(fn));
- }
- if (isPromisified(fn)) {
- return fn;
- }
- options = Object(options);
- var receiver = options.context === undefined ? THIS : options.context;
- var multiArgs = !!options.multiArgs;
- var ret = promisify(fn, receiver, multiArgs);
- util.copyDescriptors(fn, ret, propsFilter);
- return ret;
- };
-
- Promise.promisifyAll = function (target, options) {
- if (typeof target !== "function" && typeof target !== "object") {
- throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- options = Object(options);
- var multiArgs = !!options.multiArgs;
- var suffix = options.suffix;
- if (typeof suffix !== "string") suffix = defaultSuffix;
- var filter = options.filter;
- if (typeof filter !== "function") filter = defaultFilter;
- var promisifier = options.promisifier;
- if (typeof promisifier !== "function") promisifier = makeNodePromisified;
-
- if (!util.isIdentifier(suffix)) {
- throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
-
- var keys = util.inheritedDataKeys(target);
- for (var i = 0; i < keys.length; ++i) {
- var value = target[keys[i]];
- if (keys[i] !== "constructor" &&
- util.isClass(value)) {
- promisifyAll(value.prototype, suffix, filter, promisifier,
- multiArgs);
- promisifyAll(value, suffix, filter, promisifier, multiArgs);
- }
- }
-
- return promisifyAll(target, suffix, filter, promisifier, multiArgs);
- };
- };
-
-
- },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(
- Promise, PromiseArray, tryConvertToPromise, apiRejection) {
- var util = _dereq_("./util");
- var isObject = util.isObject;
- var es5 = _dereq_("./es5");
- var Es6Map;
- if (typeof Map === "function") Es6Map = Map;
-
- var mapToEntries = (function() {
- var index = 0;
- var size = 0;
-
- function extractEntry(value, key) {
- this[index] = value;
- this[index + size] = key;
- index++;
- }
-
- return function mapToEntries(map) {
- size = map.size;
- index = 0;
- var ret = new Array(map.size * 2);
- map.forEach(extractEntry, ret);
- return ret;
- };
- })();
-
- var entriesToMap = function(entries) {
- var ret = new Es6Map();
- var length = entries.length / 2 | 0;
- for (var i = 0; i < length; ++i) {
- var key = entries[length + i];
- var value = entries[i];
- ret.set(key, value);
- }
- return ret;
- };
-
- function PropertiesPromiseArray(obj) {
- var isMap = false;
- var entries;
- if (Es6Map !== undefined && obj instanceof Es6Map) {
- entries = mapToEntries(obj);
- isMap = true;
- } else {
- var keys = es5.keys(obj);
- var len = keys.length;
- entries = new Array(len * 2);
- for (var i = 0; i < len; ++i) {
- var key = keys[i];
- entries[i] = obj[key];
- entries[i + len] = key;
- }
- }
- this.constructor$(entries);
- this._isMap = isMap;
- this._init$(undefined, -3);
- }
- util.inherits(PropertiesPromiseArray, PromiseArray);
-
- PropertiesPromiseArray.prototype._init = function () {};
-
- PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
- this._values[index] = value;
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= this._length) {
- var val;
- if (this._isMap) {
- val = entriesToMap(this._values);
- } else {
- val = {};
- var keyOffset = this.length();
- for (var i = 0, len = this.length(); i < len; ++i) {
- val[this._values[i + keyOffset]] = this._values[i];
- }
- }
- this._resolve(val);
- return true;
- }
- return false;
- };
-
- PropertiesPromiseArray.prototype.shouldCopyValues = function () {
- return false;
- };
-
- PropertiesPromiseArray.prototype.getActualLength = function (len) {
- return len >> 1;
- };
-
- function props(promises) {
- var ret;
- var castValue = tryConvertToPromise(promises);
-
- if (!isObject(castValue)) {
- return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- } else if (castValue instanceof Promise) {
- ret = castValue._then(
- Promise.props, undefined, undefined, undefined, undefined);
- } else {
- ret = new PropertiesPromiseArray(castValue).promise();
- }
-
- if (castValue instanceof Promise) {
- ret._propagateFrom(castValue, 2);
- }
- return ret;
- }
-
- Promise.prototype.props = function () {
- return props(this);
- };
-
- Promise.props = function (promises) {
- return props(promises);
- };
- };
-
- },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
- "use strict";
- function arrayMove(src, srcIndex, dst, dstIndex, len) {
- for (var j = 0; j < len; ++j) {
- dst[j + dstIndex] = src[j + srcIndex];
- src[j + srcIndex] = void 0;
- }
- }
-
- function Queue(capacity) {
- this._capacity = capacity;
- this._length = 0;
- this._front = 0;
- }
-
- Queue.prototype._willBeOverCapacity = function (size) {
- return this._capacity < size;
- };
-
- Queue.prototype._pushOne = function (arg) {
- var length = this.length();
- this._checkCapacity(length + 1);
- var i = (this._front + length) & (this._capacity - 1);
- this[i] = arg;
- this._length = length + 1;
- };
-
- Queue.prototype._unshiftOne = function(value) {
- var capacity = this._capacity;
- this._checkCapacity(this.length() + 1);
- var front = this._front;
- var i = (((( front - 1 ) &
- ( capacity - 1) ) ^ capacity ) - capacity );
- this[i] = value;
- this._front = i;
- this._length = this.length() + 1;
- };
-
- Queue.prototype.unshift = function(fn, receiver, arg) {
- this._unshiftOne(arg);
- this._unshiftOne(receiver);
- this._unshiftOne(fn);
- };
-
- Queue.prototype.push = function (fn, receiver, arg) {
- var length = this.length() + 3;
- if (this._willBeOverCapacity(length)) {
- this._pushOne(fn);
- this._pushOne(receiver);
- this._pushOne(arg);
- return;
- }
- var j = this._front + length - 3;
- this._checkCapacity(length);
- var wrapMask = this._capacity - 1;
- this[(j + 0) & wrapMask] = fn;
- this[(j + 1) & wrapMask] = receiver;
- this[(j + 2) & wrapMask] = arg;
- this._length = length;
- };
-
- Queue.prototype.shift = function () {
- var front = this._front,
- ret = this[front];
-
- this[front] = undefined;
- this._front = (front + 1) & (this._capacity - 1);
- this._length--;
- return ret;
- };
-
- Queue.prototype.length = function () {
- return this._length;
- };
-
- Queue.prototype._checkCapacity = function (size) {
- if (this._capacity < size) {
- this._resizeTo(this._capacity << 1);
- }
- };
-
- Queue.prototype._resizeTo = function (capacity) {
- var oldCapacity = this._capacity;
- this._capacity = capacity;
- var front = this._front;
- var length = this._length;
- var moveItemsCount = (front + length) & (oldCapacity - 1);
- arrayMove(this, 0, this, oldCapacity, moveItemsCount);
- };
-
- module.exports = Queue;
-
- },{}],27:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(
- Promise, INTERNAL, tryConvertToPromise, apiRejection) {
- var util = _dereq_("./util");
-
- var raceLater = function (promise) {
- return promise.then(function(array) {
- return race(array, promise);
- });
- };
-
- function race(promises, parent) {
- var maybePromise = tryConvertToPromise(promises);
-
- if (maybePromise instanceof Promise) {
- return raceLater(maybePromise);
- } else {
- promises = util.asArray(promises);
- if (promises === null)
- return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
- }
-
- var ret = new Promise(INTERNAL);
- if (parent !== undefined) {
- ret._propagateFrom(parent, 3);
- }
- var fulfill = ret._fulfill;
- var reject = ret._reject;
- for (var i = 0, len = promises.length; i < len; ++i) {
- var val = promises[i];
-
- if (val === undefined && !(i in promises)) {
- continue;
- }
-
- Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
- }
- return ret;
- }
-
- Promise.race = function (promises) {
- return race(promises, undefined);
- };
-
- Promise.prototype.race = function () {
- return race(this, undefined);
- };
-
- };
-
- },{"./util":36}],28:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise,
- PromiseArray,
- apiRejection,
- tryConvertToPromise,
- INTERNAL,
- debug) {
- var getDomain = Promise._getDomain;
- var util = _dereq_("./util");
- var tryCatch = util.tryCatch;
-
- function ReductionPromiseArray(promises, fn, initialValue, _each) {
- this.constructor$(promises);
- var domain = getDomain();
- this._fn = domain === null ? fn : util.domainBind(domain, fn);
- if (initialValue !== undefined) {
- initialValue = Promise.resolve(initialValue);
- initialValue._attachCancellationCallback(this);
- }
- this._initialValue = initialValue;
- this._currentCancellable = null;
- if(_each === INTERNAL) {
- this._eachValues = Array(this._length);
- } else if (_each === 0) {
- this._eachValues = null;
- } else {
- this._eachValues = undefined;
- }
- this._promise._captureStackTrace();
- this._init$(undefined, -5);
- }
- util.inherits(ReductionPromiseArray, PromiseArray);
-
- ReductionPromiseArray.prototype._gotAccum = function(accum) {
- if (this._eachValues !== undefined &&
- this._eachValues !== null &&
- accum !== INTERNAL) {
- this._eachValues.push(accum);
- }
- };
-
- ReductionPromiseArray.prototype._eachComplete = function(value) {
- if (this._eachValues !== null) {
- this._eachValues.push(value);
- }
- return this._eachValues;
- };
-
- ReductionPromiseArray.prototype._init = function() {};
-
- ReductionPromiseArray.prototype._resolveEmptyArray = function() {
- this._resolve(this._eachValues !== undefined ? this._eachValues
- : this._initialValue);
- };
-
- ReductionPromiseArray.prototype.shouldCopyValues = function () {
- return false;
- };
-
- ReductionPromiseArray.prototype._resolve = function(value) {
- this._promise._resolveCallback(value);
- this._values = null;
- };
-
- ReductionPromiseArray.prototype._resultCancelled = function(sender) {
- if (sender === this._initialValue) return this._cancel();
- if (this._isResolved()) return;
- this._resultCancelled$();
- if (this._currentCancellable instanceof Promise) {
- this._currentCancellable.cancel();
- }
- if (this._initialValue instanceof Promise) {
- this._initialValue.cancel();
- }
- };
-
- ReductionPromiseArray.prototype._iterate = function (values) {
- this._values = values;
- var value;
- var i;
- var length = values.length;
- if (this._initialValue !== undefined) {
- value = this._initialValue;
- i = 0;
- } else {
- value = Promise.resolve(values[0]);
- i = 1;
- }
-
- this._currentCancellable = value;
-
- if (!value.isRejected()) {
- for (; i < length; ++i) {
- var ctx = {
- accum: null,
- value: values[i],
- index: i,
- length: length,
- array: this
- };
- value = value._then(gotAccum, undefined, undefined, ctx, undefined);
- }
- }
-
- if (this._eachValues !== undefined) {
- value = value
- ._then(this._eachComplete, undefined, undefined, this, undefined);
- }
- value._then(completed, completed, undefined, value, this);
- };
-
- Promise.prototype.reduce = function (fn, initialValue) {
- return reduce(this, fn, initialValue, null);
- };
-
- Promise.reduce = function (promises, fn, initialValue, _each) {
- return reduce(promises, fn, initialValue, _each);
- };
-
- function completed(valueOrReason, array) {
- if (this.isFulfilled()) {
- array._resolve(valueOrReason);
- } else {
- array._reject(valueOrReason);
- }
- }
-
- function reduce(promises, fn, initialValue, _each) {
- if (typeof fn !== "function") {
- return apiRejection("expecting a function but got " + util.classString(fn));
- }
- var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
- return array.promise();
- }
-
- function gotAccum(accum) {
- this.accum = accum;
- this.array._gotAccum(accum);
- var value = tryConvertToPromise(this.value, this.array._promise);
- if (value instanceof Promise) {
- this.array._currentCancellable = value;
- return value._then(gotValue, undefined, undefined, this, undefined);
- } else {
- return gotValue.call(this, value);
- }
- }
-
- function gotValue(value) {
- var array = this.array;
- var promise = array._promise;
- var fn = tryCatch(array._fn);
- promise._pushContext();
- var ret;
- if (array._eachValues !== undefined) {
- ret = fn.call(promise._boundValue(), value, this.index, this.length);
- } else {
- ret = fn.call(promise._boundValue(),
- this.accum, value, this.index, this.length);
- }
- if (ret instanceof Promise) {
- array._currentCancellable = ret;
- }
- var promiseCreated = promise._popContext();
- debug.checkForgottenReturns(
- ret,
- promiseCreated,
- array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
- promise
- );
- return ret;
- }
- };
-
- },{"./util":36}],29:[function(_dereq_,module,exports){
- "use strict";
- var util = _dereq_("./util");
- var schedule;
- var noAsyncScheduler = function() {
- throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- };
- var NativePromise = util.getNativePromise();
- if (util.isNode && typeof MutationObserver === "undefined") {
- var GlobalSetImmediate = global.setImmediate;
- var ProcessNextTick = process.nextTick;
- schedule = util.isRecentNode
- ? function(fn) { GlobalSetImmediate.call(global, fn); }
- : function(fn) { ProcessNextTick.call(process, fn); };
- } else if (typeof NativePromise === "function" &&
- typeof NativePromise.resolve === "function") {
- var nativePromise = NativePromise.resolve();
- schedule = function(fn) {
- nativePromise.then(fn);
- };
- } else if ((typeof MutationObserver !== "undefined") &&
- !(typeof window !== "undefined" &&
- window.navigator &&
- (window.navigator.standalone || window.cordova))) {
- schedule = (function() {
- var div = document.createElement("div");
- var opts = {attributes: true};
- var toggleScheduled = false;
- var div2 = document.createElement("div");
- var o2 = new MutationObserver(function() {
- div.classList.toggle("foo");
- toggleScheduled = false;
- });
- o2.observe(div2, opts);
-
- var scheduleToggle = function() {
- if (toggleScheduled) return;
- toggleScheduled = true;
- div2.classList.toggle("foo");
- };
-
- return function schedule(fn) {
- var o = new MutationObserver(function() {
- o.disconnect();
- fn();
- });
- o.observe(div, opts);
- scheduleToggle();
- };
- })();
- } else if (typeof setImmediate !== "undefined") {
- schedule = function (fn) {
- setImmediate(fn);
- };
- } else if (typeof setTimeout !== "undefined") {
- schedule = function (fn) {
- setTimeout(fn, 0);
- };
- } else {
- schedule = noAsyncScheduler;
- }
- module.exports = schedule;
-
- },{"./util":36}],30:[function(_dereq_,module,exports){
- "use strict";
- module.exports =
- function(Promise, PromiseArray, debug) {
- var PromiseInspection = Promise.PromiseInspection;
- var util = _dereq_("./util");
-
- function SettledPromiseArray(values) {
- this.constructor$(values);
- }
- util.inherits(SettledPromiseArray, PromiseArray);
-
- SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
- this._values[index] = inspection;
- var totalResolved = ++this._totalResolved;
- if (totalResolved >= this._length) {
- this._resolve(this._values);
- return true;
- }
- return false;
- };
-
- SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
- var ret = new PromiseInspection();
- ret._bitField = 33554432;
- ret._settledValueField = value;
- return this._promiseResolved(index, ret);
- };
- SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
- var ret = new PromiseInspection();
- ret._bitField = 16777216;
- ret._settledValueField = reason;
- return this._promiseResolved(index, ret);
- };
-
- Promise.settle = function (promises) {
- debug.deprecated(".settle()", ".reflect()");
- return new SettledPromiseArray(promises).promise();
- };
-
- Promise.prototype.settle = function () {
- return Promise.settle(this);
- };
- };
-
- },{"./util":36}],31:[function(_dereq_,module,exports){
- "use strict";
- module.exports =
- function(Promise, PromiseArray, apiRejection) {
- var util = _dereq_("./util");
- var RangeError = _dereq_("./errors").RangeError;
- var AggregateError = _dereq_("./errors").AggregateError;
- var isArray = util.isArray;
- var CANCELLATION = {};
-
-
- function SomePromiseArray(values) {
- this.constructor$(values);
- this._howMany = 0;
- this._unwrap = false;
- this._initialized = false;
- }
- util.inherits(SomePromiseArray, PromiseArray);
-
- SomePromiseArray.prototype._init = function () {
- if (!this._initialized) {
- return;
- }
- if (this._howMany === 0) {
- this._resolve([]);
- return;
- }
- this._init$(undefined, -5);
- var isArrayResolved = isArray(this._values);
- if (!this._isResolved() &&
- isArrayResolved &&
- this._howMany > this._canPossiblyFulfill()) {
- this._reject(this._getRangeError(this.length()));
- }
- };
-
- SomePromiseArray.prototype.init = function () {
- this._initialized = true;
- this._init();
- };
-
- SomePromiseArray.prototype.setUnwrap = function () {
- this._unwrap = true;
- };
-
- SomePromiseArray.prototype.howMany = function () {
- return this._howMany;
- };
-
- SomePromiseArray.prototype.setHowMany = function (count) {
- this._howMany = count;
- };
-
- SomePromiseArray.prototype._promiseFulfilled = function (value) {
- this._addFulfilled(value);
- if (this._fulfilled() === this.howMany()) {
- this._values.length = this.howMany();
- if (this.howMany() === 1 && this._unwrap) {
- this._resolve(this._values[0]);
- } else {
- this._resolve(this._values);
- }
- return true;
- }
- return false;
-
- };
- SomePromiseArray.prototype._promiseRejected = function (reason) {
- this._addRejected(reason);
- return this._checkOutcome();
- };
-
- SomePromiseArray.prototype._promiseCancelled = function () {
- if (this._values instanceof Promise || this._values == null) {
- return this._cancel();
- }
- this._addRejected(CANCELLATION);
- return this._checkOutcome();
- };
-
- SomePromiseArray.prototype._checkOutcome = function() {
- if (this.howMany() > this._canPossiblyFulfill()) {
- var e = new AggregateError();
- for (var i = this.length(); i < this._values.length; ++i) {
- if (this._values[i] !== CANCELLATION) {
- e.push(this._values[i]);
- }
- }
- if (e.length > 0) {
- this._reject(e);
- } else {
- this._cancel();
- }
- return true;
- }
- return false;
- };
-
- SomePromiseArray.prototype._fulfilled = function () {
- return this._totalResolved;
- };
-
- SomePromiseArray.prototype._rejected = function () {
- return this._values.length - this.length();
- };
-
- SomePromiseArray.prototype._addRejected = function (reason) {
- this._values.push(reason);
- };
-
- SomePromiseArray.prototype._addFulfilled = function (value) {
- this._values[this._totalResolved++] = value;
- };
-
- SomePromiseArray.prototype._canPossiblyFulfill = function () {
- return this.length() - this._rejected();
- };
-
- SomePromiseArray.prototype._getRangeError = function (count) {
- var message = "Input array must contain at least " +
- this._howMany + " items but contains only " + count + " items";
- return new RangeError(message);
- };
-
- SomePromiseArray.prototype._resolveEmptyArray = function () {
- this._reject(this._getRangeError(0));
- };
-
- function some(promises, howMany) {
- if ((howMany | 0) !== howMany || howMany < 0) {
- return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- var ret = new SomePromiseArray(promises);
- var promise = ret.promise();
- ret.setHowMany(howMany);
- ret.init();
- return promise;
- }
-
- Promise.some = function (promises, howMany) {
- return some(promises, howMany);
- };
-
- Promise.prototype.some = function (howMany) {
- return some(this, howMany);
- };
-
- Promise._SomePromiseArray = SomePromiseArray;
- };
-
- },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise) {
- function PromiseInspection(promise) {
- if (promise !== undefined) {
- promise = promise._target();
- this._bitField = promise._bitField;
- this._settledValueField = promise._isFateSealed()
- ? promise._settledValue() : undefined;
- }
- else {
- this._bitField = 0;
- this._settledValueField = undefined;
- }
- }
-
- PromiseInspection.prototype._settledValue = function() {
- return this._settledValueField;
- };
-
- var value = PromiseInspection.prototype.value = function () {
- if (!this.isFulfilled()) {
- throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- return this._settledValue();
- };
-
- var reason = PromiseInspection.prototype.error =
- PromiseInspection.prototype.reason = function () {
- if (!this.isRejected()) {
- throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
- }
- return this._settledValue();
- };
-
- var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
- return (this._bitField & 33554432) !== 0;
- };
-
- var isRejected = PromiseInspection.prototype.isRejected = function () {
- return (this._bitField & 16777216) !== 0;
- };
-
- var isPending = PromiseInspection.prototype.isPending = function () {
- return (this._bitField & 50397184) === 0;
- };
-
- var isResolved = PromiseInspection.prototype.isResolved = function () {
- return (this._bitField & 50331648) !== 0;
- };
-
- PromiseInspection.prototype.isCancelled = function() {
- return (this._bitField & 8454144) !== 0;
- };
-
- Promise.prototype.__isCancelled = function() {
- return (this._bitField & 65536) === 65536;
- };
-
- Promise.prototype._isCancelled = function() {
- return this._target().__isCancelled();
- };
-
- Promise.prototype.isCancelled = function() {
- return (this._target()._bitField & 8454144) !== 0;
- };
-
- Promise.prototype.isPending = function() {
- return isPending.call(this._target());
- };
-
- Promise.prototype.isRejected = function() {
- return isRejected.call(this._target());
- };
-
- Promise.prototype.isFulfilled = function() {
- return isFulfilled.call(this._target());
- };
-
- Promise.prototype.isResolved = function() {
- return isResolved.call(this._target());
- };
-
- Promise.prototype.value = function() {
- return value.call(this._target());
- };
-
- Promise.prototype.reason = function() {
- var target = this._target();
- target._unsetRejectionIsUnhandled();
- return reason.call(target);
- };
-
- Promise.prototype._value = function() {
- return this._settledValue();
- };
-
- Promise.prototype._reason = function() {
- this._unsetRejectionIsUnhandled();
- return this._settledValue();
- };
-
- Promise.PromiseInspection = PromiseInspection;
- };
-
- },{}],33:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL) {
- var util = _dereq_("./util");
- var errorObj = util.errorObj;
- var isObject = util.isObject;
-
- function tryConvertToPromise(obj, context) {
- if (isObject(obj)) {
- if (obj instanceof Promise) return obj;
- var then = getThen(obj);
- if (then === errorObj) {
- if (context) context._pushContext();
- var ret = Promise.reject(then.e);
- if (context) context._popContext();
- return ret;
- } else if (typeof then === "function") {
- if (isAnyBluebirdPromise(obj)) {
- var ret = new Promise(INTERNAL);
- obj._then(
- ret._fulfill,
- ret._reject,
- undefined,
- ret,
- null
- );
- return ret;
- }
- return doThenable(obj, then, context);
- }
- }
- return obj;
- }
-
- function doGetThen(obj) {
- return obj.then;
- }
-
- function getThen(obj) {
- try {
- return doGetThen(obj);
- } catch (e) {
- errorObj.e = e;
- return errorObj;
- }
- }
-
- var hasProp = {}.hasOwnProperty;
- function isAnyBluebirdPromise(obj) {
- try {
- return hasProp.call(obj, "_promise0");
- } catch (e) {
- return false;
- }
- }
-
- function doThenable(x, then, context) {
- var promise = new Promise(INTERNAL);
- var ret = promise;
- if (context) context._pushContext();
- promise._captureStackTrace();
- if (context) context._popContext();
- var synchronous = true;
- var result = util.tryCatch(then).call(x, resolve, reject);
- synchronous = false;
-
- if (promise && result === errorObj) {
- promise._rejectCallback(result.e, true, true);
- promise = null;
- }
-
- function resolve(value) {
- if (!promise) return;
- promise._resolveCallback(value);
- promise = null;
- }
-
- function reject(reason) {
- if (!promise) return;
- promise._rejectCallback(reason, synchronous, true);
- promise = null;
- }
- return ret;
- }
-
- return tryConvertToPromise;
- };
-
- },{"./util":36}],34:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function(Promise, INTERNAL, debug) {
- var util = _dereq_("./util");
- var TimeoutError = Promise.TimeoutError;
-
- function HandleWrapper(handle) {
- this.handle = handle;
- }
-
- HandleWrapper.prototype._resultCancelled = function() {
- clearTimeout(this.handle);
- };
-
- var afterValue = function(value) { return delay(+this).thenReturn(value); };
- var delay = Promise.delay = function (ms, value) {
- var ret;
- var handle;
- if (value !== undefined) {
- ret = Promise.resolve(value)
- ._then(afterValue, null, null, ms, undefined);
- if (debug.cancellation() && value instanceof Promise) {
- ret._setOnCancel(value);
- }
- } else {
- ret = new Promise(INTERNAL);
- handle = setTimeout(function() { ret._fulfill(); }, +ms);
- if (debug.cancellation()) {
- ret._setOnCancel(new HandleWrapper(handle));
- }
- ret._captureStackTrace();
- }
- ret._setAsyncGuaranteed();
- return ret;
- };
-
- Promise.prototype.delay = function (ms) {
- return delay(ms, this);
- };
-
- var afterTimeout = function (promise, message, parent) {
- var err;
- if (typeof message !== "string") {
- if (message instanceof Error) {
- err = message;
- } else {
- err = new TimeoutError("operation timed out");
- }
- } else {
- err = new TimeoutError(message);
- }
- util.markAsOriginatingFromRejection(err);
- promise._attachExtraTrace(err);
- promise._reject(err);
-
- if (parent != null) {
- parent.cancel();
- }
- };
-
- function successClear(value) {
- clearTimeout(this.handle);
- return value;
- }
-
- function failureClear(reason) {
- clearTimeout(this.handle);
- throw reason;
- }
-
- Promise.prototype.timeout = function (ms, message) {
- ms = +ms;
- var ret, parent;
-
- var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
- if (ret.isPending()) {
- afterTimeout(ret, message, parent);
- }
- }, ms));
-
- if (debug.cancellation()) {
- parent = this.then();
- ret = parent._then(successClear, failureClear,
- undefined, handleWrapper, undefined);
- ret._setOnCancel(handleWrapper);
- } else {
- ret = this._then(successClear, failureClear,
- undefined, handleWrapper, undefined);
- }
-
- return ret;
- };
-
- };
-
- },{"./util":36}],35:[function(_dereq_,module,exports){
- "use strict";
- module.exports = function (Promise, apiRejection, tryConvertToPromise,
- createContext, INTERNAL, debug) {
- var util = _dereq_("./util");
- var TypeError = _dereq_("./errors").TypeError;
- var inherits = _dereq_("./util").inherits;
- var errorObj = util.errorObj;
- var tryCatch = util.tryCatch;
- var NULL = {};
-
- function thrower(e) {
- setTimeout(function(){throw e;}, 0);
- }
-
- function castPreservingDisposable(thenable) {
- var maybePromise = tryConvertToPromise(thenable);
- if (maybePromise !== thenable &&
- typeof thenable._isDisposable === "function" &&
- typeof thenable._getDisposer === "function" &&
- thenable._isDisposable()) {
- maybePromise._setDisposable(thenable._getDisposer());
- }
- return maybePromise;
- }
- function dispose(resources, inspection) {
- var i = 0;
- var len = resources.length;
- var ret = new Promise(INTERNAL);
- function iterator() {
- if (i >= len) return ret._fulfill();
- var maybePromise = castPreservingDisposable(resources[i++]);
- if (maybePromise instanceof Promise &&
- maybePromise._isDisposable()) {
- try {
- maybePromise = tryConvertToPromise(
- maybePromise._getDisposer().tryDispose(inspection),
- resources.promise);
- } catch (e) {
- return thrower(e);
- }
- if (maybePromise instanceof Promise) {
- return maybePromise._then(iterator, thrower,
- null, null, null);
- }
- }
- iterator();
- }
- iterator();
- return ret;
- }
-
- function Disposer(data, promise, context) {
- this._data = data;
- this._promise = promise;
- this._context = context;
- }
-
- Disposer.prototype.data = function () {
- return this._data;
- };
-
- Disposer.prototype.promise = function () {
- return this._promise;
- };
-
- Disposer.prototype.resource = function () {
- if (this.promise().isFulfilled()) {
- return this.promise().value();
- }
- return NULL;
- };
-
- Disposer.prototype.tryDispose = function(inspection) {
- var resource = this.resource();
- var context = this._context;
- if (context !== undefined) context._pushContext();
- var ret = resource !== NULL
- ? this.doDispose(resource, inspection) : null;
- if (context !== undefined) context._popContext();
- this._promise._unsetDisposable();
- this._data = null;
- return ret;
- };
-
- Disposer.isDisposer = function (d) {
- return (d != null &&
- typeof d.resource === "function" &&
- typeof d.tryDispose === "function");
- };
-
- function FunctionDisposer(fn, promise, context) {
- this.constructor$(fn, promise, context);
- }
- inherits(FunctionDisposer, Disposer);
-
- FunctionDisposer.prototype.doDispose = function (resource, inspection) {
- var fn = this.data();
- return fn.call(resource, resource, inspection);
- };
-
- function maybeUnwrapDisposer(value) {
- if (Disposer.isDisposer(value)) {
- this.resources[this.index]._setDisposable(value);
- return value.promise();
- }
- return value;
- }
-
- function ResourceList(length) {
- this.length = length;
- this.promise = null;
- this[length-1] = null;
- }
-
- ResourceList.prototype._resultCancelled = function() {
- var len = this.length;
- for (var i = 0; i < len; ++i) {
- var item = this[i];
- if (item instanceof Promise) {
- item.cancel();
- }
- }
- };
-
- Promise.using = function () {
- var len = arguments.length;
- if (len < 2) return apiRejection(
- "you must pass at least 2 arguments to Promise.using");
- var fn = arguments[len - 1];
- if (typeof fn !== "function") {
- return apiRejection("expecting a function but got " + util.classString(fn));
- }
- var input;
- var spreadArgs = true;
- if (len === 2 && Array.isArray(arguments[0])) {
- input = arguments[0];
- len = input.length;
- spreadArgs = false;
- } else {
- input = arguments;
- len--;
- }
- var resources = new ResourceList(len);
- for (var i = 0; i < len; ++i) {
- var resource = input[i];
- if (Disposer.isDisposer(resource)) {
- var disposer = resource;
- resource = resource.promise();
- resource._setDisposable(disposer);
- } else {
- var maybePromise = tryConvertToPromise(resource);
- if (maybePromise instanceof Promise) {
- resource =
- maybePromise._then(maybeUnwrapDisposer, null, null, {
- resources: resources,
- index: i
- }, undefined);
- }
- }
- resources[i] = resource;
- }
-
- var reflectedResources = new Array(resources.length);
- for (var i = 0; i < reflectedResources.length; ++i) {
- reflectedResources[i] = Promise.resolve(resources[i]).reflect();
- }
-
- var resultPromise = Promise.all(reflectedResources)
- .then(function(inspections) {
- for (var i = 0; i < inspections.length; ++i) {
- var inspection = inspections[i];
- if (inspection.isRejected()) {
- errorObj.e = inspection.error();
- return errorObj;
- } else if (!inspection.isFulfilled()) {
- resultPromise.cancel();
- return;
- }
- inspections[i] = inspection.value();
- }
- promise._pushContext();
-
- fn = tryCatch(fn);
- var ret = spreadArgs
- ? fn.apply(undefined, inspections) : fn(inspections);
- var promiseCreated = promise._popContext();
- debug.checkForgottenReturns(
- ret, promiseCreated, "Promise.using", promise);
- return ret;
- });
-
- var promise = resultPromise.lastly(function() {
- var inspection = new Promise.PromiseInspection(resultPromise);
- return dispose(resources, inspection);
- });
- resources.promise = promise;
- promise._setOnCancel(resources);
- return promise;
- };
-
- Promise.prototype._setDisposable = function (disposer) {
- this._bitField = this._bitField | 131072;
- this._disposer = disposer;
- };
-
- Promise.prototype._isDisposable = function () {
- return (this._bitField & 131072) > 0;
- };
-
- Promise.prototype._getDisposer = function () {
- return this._disposer;
- };
-
- Promise.prototype._unsetDisposable = function () {
- this._bitField = this._bitField & (~131072);
- this._disposer = undefined;
- };
-
- Promise.prototype.disposer = function (fn) {
- if (typeof fn === "function") {
- return new FunctionDisposer(fn, this, createContext());
- }
- throw new TypeError();
- };
-
- };
-
- },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
- "use strict";
- var es5 = _dereq_("./es5");
- var canEvaluate = typeof navigator == "undefined";
-
- var errorObj = {e: {}};
- var tryCatchTarget;
- var globalObject = typeof self !== "undefined" ? self :
- typeof window !== "undefined" ? window :
- typeof global !== "undefined" ? global :
- this !== undefined ? this : null;
-
- function tryCatcher() {
- try {
- var target = tryCatchTarget;
- tryCatchTarget = null;
- return target.apply(this, arguments);
- } catch (e) {
- errorObj.e = e;
- return errorObj;
- }
- }
- function tryCatch(fn) {
- tryCatchTarget = fn;
- return tryCatcher;
- }
-
- var inherits = function(Child, Parent) {
- var hasProp = {}.hasOwnProperty;
-
- function T() {
- this.constructor = Child;
- this.constructor$ = Parent;
- for (var propertyName in Parent.prototype) {
- if (hasProp.call(Parent.prototype, propertyName) &&
- propertyName.charAt(propertyName.length-1) !== "$"
- ) {
- this[propertyName + "$"] = Parent.prototype[propertyName];
- }
- }
- }
- T.prototype = Parent.prototype;
- Child.prototype = new T();
- return Child.prototype;
- };
-
-
- function isPrimitive(val) {
- return val == null || val === true || val === false ||
- typeof val === "string" || typeof val === "number";
-
- }
-
- function isObject(value) {
- return typeof value === "function" ||
- typeof value === "object" && value !== null;
- }
-
- function maybeWrapAsError(maybeError) {
- if (!isPrimitive(maybeError)) return maybeError;
-
- return new Error(safeToString(maybeError));
- }
-
- function withAppended(target, appendee) {
- var len = target.length;
- var ret = new Array(len + 1);
- var i;
- for (i = 0; i < len; ++i) {
- ret[i] = target[i];
- }
- ret[i] = appendee;
- return ret;
- }
-
- function getDataPropertyOrDefault(obj, key, defaultValue) {
- if (es5.isES5) {
- var desc = Object.getOwnPropertyDescriptor(obj, key);
-
- if (desc != null) {
- return desc.get == null && desc.set == null
- ? desc.value
- : defaultValue;
- }
- } else {
- return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
- }
- }
-
- function notEnumerableProp(obj, name, value) {
- if (isPrimitive(obj)) return obj;
- var descriptor = {
- value: value,
- configurable: true,
- enumerable: false,
- writable: true
- };
- es5.defineProperty(obj, name, descriptor);
- return obj;
- }
-
- function thrower(r) {
- throw r;
- }
-
- var inheritedDataKeys = (function() {
- var excludedPrototypes = [
- Array.prototype,
- Object.prototype,
- Function.prototype
- ];
-
- var isExcludedProto = function(val) {
- for (var i = 0; i < excludedPrototypes.length; ++i) {
- if (excludedPrototypes[i] === val) {
- return true;
- }
- }
- return false;
- };
-
- if (es5.isES5) {
- var getKeys = Object.getOwnPropertyNames;
- return function(obj) {
- var ret = [];
- var visitedKeys = Object.create(null);
- while (obj != null && !isExcludedProto(obj)) {
- var keys;
- try {
- keys = getKeys(obj);
- } catch (e) {
- return ret;
- }
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- if (visitedKeys[key]) continue;
- visitedKeys[key] = true;
- var desc = Object.getOwnPropertyDescriptor(obj, key);
- if (desc != null && desc.get == null && desc.set == null) {
- ret.push(key);
- }
- }
- obj = es5.getPrototypeOf(obj);
- }
- return ret;
- };
- } else {
- var hasProp = {}.hasOwnProperty;
- return function(obj) {
- if (isExcludedProto(obj)) return [];
- var ret = [];
-
- /*jshint forin:false */
- enumeration: for (var key in obj) {
- if (hasProp.call(obj, key)) {
- ret.push(key);
- } else {
- for (var i = 0; i < excludedPrototypes.length; ++i) {
- if (hasProp.call(excludedPrototypes[i], key)) {
- continue enumeration;
- }
- }
- ret.push(key);
- }
- }
- return ret;
- };
- }
-
- })();
-
- var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
- function isClass(fn) {
- try {
- if (typeof fn === "function") {
- var keys = es5.names(fn.prototype);
-
- var hasMethods = es5.isES5 && keys.length > 1;
- var hasMethodsOtherThanConstructor = keys.length > 0 &&
- !(keys.length === 1 && keys[0] === "constructor");
- var hasThisAssignmentAndStaticMethods =
- thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
-
- if (hasMethods || hasMethodsOtherThanConstructor ||
- hasThisAssignmentAndStaticMethods) {
- return true;
- }
- }
- return false;
- } catch (e) {
- return false;
- }
- }
-
- function toFastProperties(obj) {
- /*jshint -W027,-W055,-W031*/
- function FakeConstructor() {}
- FakeConstructor.prototype = obj;
- var l = 8;
- while (l--) new FakeConstructor();
- return obj;
- eval(obj);
- }
-
- var rident = /^[a-z$_][a-z$_0-9]*$/i;
- function isIdentifier(str) {
- return rident.test(str);
- }
-
- function filledRange(count, prefix, suffix) {
- var ret = new Array(count);
- for(var i = 0; i < count; ++i) {
- ret[i] = prefix + i + suffix;
- }
- return ret;
- }
-
- function safeToString(obj) {
- try {
- return obj + "";
- } catch (e) {
- return "[no string representation]";
- }
- }
-
- function isError(obj) {
- return obj !== null &&
- typeof obj === "object" &&
- typeof obj.message === "string" &&
- typeof obj.name === "string";
- }
-
- function markAsOriginatingFromRejection(e) {
- try {
- notEnumerableProp(e, "isOperational", true);
- }
- catch(ignore) {}
- }
-
- function originatesFromRejection(e) {
- if (e == null) return false;
- return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
- e["isOperational"] === true);
- }
-
- function canAttachTrace(obj) {
- return isError(obj) && es5.propertyIsWritable(obj, "stack");
- }
-
- var ensureErrorObject = (function() {
- if (!("stack" in new Error())) {
- return function(value) {
- if (canAttachTrace(value)) return value;
- try {throw new Error(safeToString(value));}
- catch(err) {return err;}
- };
- } else {
- return function(value) {
- if (canAttachTrace(value)) return value;
- return new Error(safeToString(value));
- };
- }
- })();
-
- function classString(obj) {
- return {}.toString.call(obj);
- }
-
- function copyDescriptors(from, to, filter) {
- var keys = es5.names(from);
- for (var i = 0; i < keys.length; ++i) {
- var key = keys[i];
- if (filter(key)) {
- try {
- es5.defineProperty(to, key, es5.getDescriptor(from, key));
- } catch (ignore) {}
- }
- }
- }
-
- var asArray = function(v) {
- if (es5.isArray(v)) {
- return v;
- }
- return null;
- };
-
- if (typeof Symbol !== "undefined" && Symbol.iterator) {
- var ArrayFrom = typeof Array.from === "function" ? function(v) {
- return Array.from(v);
- } : function(v) {
- var ret = [];
- var it = v[Symbol.iterator]();
- var itResult;
- while (!((itResult = it.next()).done)) {
- ret.push(itResult.value);
- }
- return ret;
- };
-
- asArray = function(v) {
- if (es5.isArray(v)) {
- return v;
- } else if (v != null && typeof v[Symbol.iterator] === "function") {
- return ArrayFrom(v);
- }
- return null;
- };
- }
-
- var isNode = typeof process !== "undefined" &&
- classString(process).toLowerCase() === "[object process]";
-
- function env(key, def) {
- return isNode ? process.env[key] : def;
- }
-
- function getNativePromise() {
- if (typeof Promise === "function") {
- try {
- var promise = new Promise(function(){});
- if ({}.toString.call(promise) === "[object Promise]") {
- return Promise;
- }
- } catch (e) {}
- }
- }
-
- function domainBind(self, cb) {
- return self.bind(cb);
- }
-
- var ret = {
- isClass: isClass,
- isIdentifier: isIdentifier,
- inheritedDataKeys: inheritedDataKeys,
- getDataPropertyOrDefault: getDataPropertyOrDefault,
- thrower: thrower,
- isArray: es5.isArray,
- asArray: asArray,
- notEnumerableProp: notEnumerableProp,
- isPrimitive: isPrimitive,
- isObject: isObject,
- isError: isError,
- canEvaluate: canEvaluate,
- errorObj: errorObj,
- tryCatch: tryCatch,
- inherits: inherits,
- withAppended: withAppended,
- maybeWrapAsError: maybeWrapAsError,
- toFastProperties: toFastProperties,
- filledRange: filledRange,
- toString: safeToString,
- canAttachTrace: canAttachTrace,
- ensureErrorObject: ensureErrorObject,
- originatesFromRejection: originatesFromRejection,
- markAsOriginatingFromRejection: markAsOriginatingFromRejection,
- classString: classString,
- copyDescriptors: copyDescriptors,
- hasDevTools: typeof chrome !== "undefined" && chrome &&
- typeof chrome.loadTimes === "function",
- isNode: isNode,
- env: env,
- global: globalObject,
- getNativePromise: getNativePromise,
- domainBind: domainBind
- };
- ret.isRecentNode = ret.isNode && (function() {
- var version = process.versions.node.split(".").map(Number);
- return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
- })();
-
- if (ret.isNode) ret.toFastProperties(process);
-
- try {throw new Error(); } catch (e) {ret.lastLineError = e;}
- module.exports = ret;
-
- },{"./es5":13}]},{},[4])(4)
- }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
- }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"_process":22}],5:[function(require,module,exports){
-
- },{}],6:[function(require,module,exports){
- (function (global){
- 'use strict';
-
- var buffer = require('buffer');
- var Buffer = buffer.Buffer;
- var SlowBuffer = buffer.SlowBuffer;
- var MAX_LEN = buffer.kMaxLength || 2147483647;
- exports.alloc = function alloc(size, fill, encoding) {
- if (typeof Buffer.alloc === 'function') {
- return Buffer.alloc(size, fill, encoding);
- }
- if (typeof encoding === 'number') {
- throw new TypeError('encoding must not be number');
- }
- if (typeof size !== 'number') {
- throw new TypeError('size must be a number');
- }
- if (size > MAX_LEN) {
- throw new RangeError('size is too large');
- }
- var enc = encoding;
- var _fill = fill;
- if (_fill === undefined) {
- enc = undefined;
- _fill = 0;
- }
- var buf = new Buffer(size);
- if (typeof _fill === 'string') {
- var fillBuf = new Buffer(_fill, enc);
- var flen = fillBuf.length;
- var i = -1;
- while (++i < size) {
- buf[i] = fillBuf[i % flen];
- }
- } else {
- buf.fill(_fill);
- }
- return buf;
- }
- exports.allocUnsafe = function allocUnsafe(size) {
- if (typeof Buffer.allocUnsafe === 'function') {
- return Buffer.allocUnsafe(size);
- }
- if (typeof size !== 'number') {
- throw new TypeError('size must be a number');
- }
- if (size > MAX_LEN) {
- throw new RangeError('size is too large');
- }
- return new Buffer(size);
- }
- exports.from = function from(value, encodingOrOffset, length) {
- if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
- return Buffer.from(value, encodingOrOffset, length);
- }
- if (typeof value === 'number') {
- throw new TypeError('"value" argument must not be a number');
- }
- if (typeof value === 'string') {
- return new Buffer(value, encodingOrOffset);
- }
- if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
- var offset = encodingOrOffset;
- if (arguments.length === 1) {
- return new Buffer(value);
- }
- if (typeof offset === 'undefined') {
- offset = 0;
- }
- var len = length;
- if (typeof len === 'undefined') {
- len = value.byteLength - offset;
- }
- if (offset >= value.byteLength) {
- throw new RangeError('\'offset\' is out of bounds');
- }
- if (len > value.byteLength - offset) {
- throw new RangeError('\'length\' is out of bounds');
- }
- return new Buffer(value.slice(offset, offset + len));
- }
- if (Buffer.isBuffer(value)) {
- var out = new Buffer(value.length);
- value.copy(out, 0, 0, value.length);
- return out;
- }
- if (value) {
- if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
- return new Buffer(value);
- }
- if (value.type === 'Buffer' && Array.isArray(value.data)) {
- return new Buffer(value.data);
- }
- }
-
- throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
- }
- exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
- if (typeof Buffer.allocUnsafeSlow === 'function') {
- return Buffer.allocUnsafeSlow(size);
- }
- if (typeof size !== 'number') {
- throw new TypeError('size must be a number');
- }
- if (size >= MAX_LEN) {
- throw new RangeError('size is too large');
- }
- return new SlowBuffer(size);
- }
-
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"buffer":7}],7:[function(require,module,exports){
- (function (global){
- /*!
- * The buffer module from node.js, for the browser.
- *
- * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
- * @license MIT
- */
- /* eslint-disable no-proto */
-
- 'use strict'
-
- var base64 = require('base64-js')
- var ieee754 = require('ieee754')
- var isArray = require('isarray')
-
- exports.Buffer = Buffer
- exports.SlowBuffer = SlowBuffer
- exports.INSPECT_MAX_BYTES = 50
-
- /**
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
- * === true Use Uint8Array implementation (fastest)
- * === false Use Object implementation (most compatible, even IE6)
- *
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
- * Opera 11.6+, iOS 4.2+.
- *
- * Due to various browser bugs, sometimes the Object implementation will be used even
- * when the browser supports typed arrays.
- *
- * Note:
- *
- * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
- * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
- *
- * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
- *
- * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
- * incorrect length in some situations.
-
- * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
- * get the Object implementation, which is slower but behaves correctly.
- */
- Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
- ? global.TYPED_ARRAY_SUPPORT
- : typedArraySupport()
-
- /*
- * Export kMaxLength after typed array support is determined.
- */
- exports.kMaxLength = kMaxLength()
-
- function typedArraySupport () {
- try {
- var arr = new Uint8Array(1)
- arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
- return arr.foo() === 42 && // typed array instances can be augmented
- typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
- arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
- } catch (e) {
- return false
- }
- }
-
- function kMaxLength () {
- return Buffer.TYPED_ARRAY_SUPPORT
- ? 0x7fffffff
- : 0x3fffffff
- }
-
- function createBuffer (that, length) {
- if (kMaxLength() < length) {
- throw new RangeError('Invalid typed array length')
- }
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- // Return an augmented `Uint8Array` instance, for best performance
- that = new Uint8Array(length)
- that.__proto__ = Buffer.prototype
- } else {
- // Fallback: Return an object instance of the Buffer class
- if (that === null) {
- that = new Buffer(length)
- }
- that.length = length
- }
-
- return that
- }
-
- /**
- * The Buffer constructor returns instances of `Uint8Array` that have their
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
- * returns a single octet.
- *
- * The `Uint8Array` prototype remains unmodified.
- */
-
- function Buffer (arg, encodingOrOffset, length) {
- if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
- return new Buffer(arg, encodingOrOffset, length)
- }
-
- // Common case.
- if (typeof arg === 'number') {
- if (typeof encodingOrOffset === 'string') {
- throw new Error(
- 'If encoding is specified then the first argument must be a string'
- )
- }
- return allocUnsafe(this, arg)
- }
- return from(this, arg, encodingOrOffset, length)
- }
-
- Buffer.poolSize = 8192 // not used by this implementation
-
- // TODO: Legacy, not needed anymore. Remove in next major version.
- Buffer._augment = function (arr) {
- arr.__proto__ = Buffer.prototype
- return arr
- }
-
- function from (that, value, encodingOrOffset, length) {
- if (typeof value === 'number') {
- throw new TypeError('"value" argument must not be a number')
- }
-
- if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
- return fromArrayBuffer(that, value, encodingOrOffset, length)
- }
-
- if (typeof value === 'string') {
- return fromString(that, value, encodingOrOffset)
- }
-
- return fromObject(that, value)
- }
-
- /**
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
- * if value is a number.
- * Buffer.from(str[, encoding])
- * Buffer.from(array)
- * Buffer.from(buffer)
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
- **/
- Buffer.from = function (value, encodingOrOffset, length) {
- return from(null, value, encodingOrOffset, length)
- }
-
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- Buffer.prototype.__proto__ = Uint8Array.prototype
- Buffer.__proto__ = Uint8Array
- if (typeof Symbol !== 'undefined' && Symbol.species &&
- Buffer[Symbol.species] === Buffer) {
- // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
- Object.defineProperty(Buffer, Symbol.species, {
- value: null,
- configurable: true
- })
- }
- }
-
- function assertSize (size) {
- if (typeof size !== 'number') {
- throw new TypeError('"size" argument must be a number')
- } else if (size < 0) {
- throw new RangeError('"size" argument must not be negative')
- }
- }
-
- function alloc (that, size, fill, encoding) {
- assertSize(size)
- if (size <= 0) {
- return createBuffer(that, size)
- }
- if (fill !== undefined) {
- // Only pay attention to encoding if it's a string. This
- // prevents accidentally sending in a number that would
- // be interpretted as a start offset.
- return typeof encoding === 'string'
- ? createBuffer(that, size).fill(fill, encoding)
- : createBuffer(that, size).fill(fill)
- }
- return createBuffer(that, size)
- }
-
- /**
- * Creates a new filled Buffer instance.
- * alloc(size[, fill[, encoding]])
- **/
- Buffer.alloc = function (size, fill, encoding) {
- return alloc(null, size, fill, encoding)
- }
-
- function allocUnsafe (that, size) {
- assertSize(size)
- that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
- if (!Buffer.TYPED_ARRAY_SUPPORT) {
- for (var i = 0; i < size; ++i) {
- that[i] = 0
- }
- }
- return that
- }
-
- /**
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
- * */
- Buffer.allocUnsafe = function (size) {
- return allocUnsafe(null, size)
- }
- /**
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
- */
- Buffer.allocUnsafeSlow = function (size) {
- return allocUnsafe(null, size)
- }
-
- function fromString (that, string, encoding) {
- if (typeof encoding !== 'string' || encoding === '') {
- encoding = 'utf8'
- }
-
- if (!Buffer.isEncoding(encoding)) {
- throw new TypeError('"encoding" must be a valid string encoding')
- }
-
- var length = byteLength(string, encoding) | 0
- that = createBuffer(that, length)
-
- var actual = that.write(string, encoding)
-
- if (actual !== length) {
- // Writing a hex string, for example, that contains invalid characters will
- // cause everything after the first invalid character to be ignored. (e.g.
- // 'abxxcd' will be treated as 'ab')
- that = that.slice(0, actual)
- }
-
- return that
- }
-
- function fromArrayLike (that, array) {
- var length = array.length < 0 ? 0 : checked(array.length) | 0
- that = createBuffer(that, length)
- for (var i = 0; i < length; i += 1) {
- that[i] = array[i] & 255
- }
- return that
- }
-
- function fromArrayBuffer (that, array, byteOffset, length) {
- array.byteLength // this throws if `array` is not a valid ArrayBuffer
-
- if (byteOffset < 0 || array.byteLength < byteOffset) {
- throw new RangeError('\'offset\' is out of bounds')
- }
-
- if (array.byteLength < byteOffset + (length || 0)) {
- throw new RangeError('\'length\' is out of bounds')
- }
-
- if (byteOffset === undefined && length === undefined) {
- array = new Uint8Array(array)
- } else if (length === undefined) {
- array = new Uint8Array(array, byteOffset)
- } else {
- array = new Uint8Array(array, byteOffset, length)
- }
-
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- // Return an augmented `Uint8Array` instance, for best performance
- that = array
- that.__proto__ = Buffer.prototype
- } else {
- // Fallback: Return an object instance of the Buffer class
- that = fromArrayLike(that, array)
- }
- return that
- }
-
- function fromObject (that, obj) {
- if (Buffer.isBuffer(obj)) {
- var len = checked(obj.length) | 0
- that = createBuffer(that, len)
-
- if (that.length === 0) {
- return that
- }
-
- obj.copy(that, 0, 0, len)
- return that
- }
-
- if (obj) {
- if ((typeof ArrayBuffer !== 'undefined' &&
- obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
- if (typeof obj.length !== 'number' || isnan(obj.length)) {
- return createBuffer(that, 0)
- }
- return fromArrayLike(that, obj)
- }
-
- if (obj.type === 'Buffer' && isArray(obj.data)) {
- return fromArrayLike(that, obj.data)
- }
- }
-
- throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
- }
-
- function checked (length) {
- // Note: cannot use `length < kMaxLength()` here because that fails when
- // length is NaN (which is otherwise coerced to zero.)
- if (length >= kMaxLength()) {
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
- 'size: 0x' + kMaxLength().toString(16) + ' bytes')
- }
- return length | 0
- }
-
- function SlowBuffer (length) {
- if (+length != length) { // eslint-disable-line eqeqeq
- length = 0
- }
- return Buffer.alloc(+length)
- }
-
- Buffer.isBuffer = function isBuffer (b) {
- return !!(b != null && b._isBuffer)
- }
-
- Buffer.compare = function compare (a, b) {
- if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
- throw new TypeError('Arguments must be Buffers')
- }
-
- if (a === b) return 0
-
- var x = a.length
- var y = b.length
-
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
- if (a[i] !== b[i]) {
- x = a[i]
- y = b[i]
- break
- }
- }
-
- if (x < y) return -1
- if (y < x) return 1
- return 0
- }
-
- Buffer.isEncoding = function isEncoding (encoding) {
- switch (String(encoding).toLowerCase()) {
- case 'hex':
- case 'utf8':
- case 'utf-8':
- case 'ascii':
- case 'latin1':
- case 'binary':
- case 'base64':
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return true
- default:
- return false
- }
- }
-
- Buffer.concat = function concat (list, length) {
- if (!isArray(list)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
-
- if (list.length === 0) {
- return Buffer.alloc(0)
- }
-
- var i
- if (length === undefined) {
- length = 0
- for (i = 0; i < list.length; ++i) {
- length += list[i].length
- }
- }
-
- var buffer = Buffer.allocUnsafe(length)
- var pos = 0
- for (i = 0; i < list.length; ++i) {
- var buf = list[i]
- if (!Buffer.isBuffer(buf)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
- buf.copy(buffer, pos)
- pos += buf.length
- }
- return buffer
- }
-
- function byteLength (string, encoding) {
- if (Buffer.isBuffer(string)) {
- return string.length
- }
- if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
- (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
- return string.byteLength
- }
- if (typeof string !== 'string') {
- string = '' + string
- }
-
- var len = string.length
- if (len === 0) return 0
-
- // Use a for loop to avoid recursion
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'ascii':
- case 'latin1':
- case 'binary':
- return len
- case 'utf8':
- case 'utf-8':
- case undefined:
- return utf8ToBytes(string).length
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return len * 2
- case 'hex':
- return len >>> 1
- case 'base64':
- return base64ToBytes(string).length
- default:
- if (loweredCase) return utf8ToBytes(string).length // assume utf8
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
- }
- }
- }
- Buffer.byteLength = byteLength
-
- function slowToString (encoding, start, end) {
- var loweredCase = false
-
- // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
- // property of a typed array.
-
- // This behaves neither like String nor Uint8Array in that we set start/end
- // to their upper/lower bounds if the value passed is out of range.
- // undefined is handled specially as per ECMA-262 6th Edition,
- // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
- if (start === undefined || start < 0) {
- start = 0
- }
- // Return early if start > this.length. Done here to prevent potential uint32
- // coercion fail below.
- if (start > this.length) {
- return ''
- }
-
- if (end === undefined || end > this.length) {
- end = this.length
- }
-
- if (end <= 0) {
- return ''
- }
-
- // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
- end >>>= 0
- start >>>= 0
-
- if (end <= start) {
- return ''
- }
-
- if (!encoding) encoding = 'utf8'
-
- while (true) {
- switch (encoding) {
- case 'hex':
- return hexSlice(this, start, end)
-
- case 'utf8':
- case 'utf-8':
- return utf8Slice(this, start, end)
-
- case 'ascii':
- return asciiSlice(this, start, end)
-
- case 'latin1':
- case 'binary':
- return latin1Slice(this, start, end)
-
- case 'base64':
- return base64Slice(this, start, end)
-
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return utf16leSlice(this, start, end)
-
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = (encoding + '').toLowerCase()
- loweredCase = true
- }
- }
- }
-
- // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
- // Buffer instances.
- Buffer.prototype._isBuffer = true
-
- function swap (b, n, m) {
- var i = b[n]
- b[n] = b[m]
- b[m] = i
- }
-
- Buffer.prototype.swap16 = function swap16 () {
- var len = this.length
- if (len % 2 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 16-bits')
- }
- for (var i = 0; i < len; i += 2) {
- swap(this, i, i + 1)
- }
- return this
- }
-
- Buffer.prototype.swap32 = function swap32 () {
- var len = this.length
- if (len % 4 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 32-bits')
- }
- for (var i = 0; i < len; i += 4) {
- swap(this, i, i + 3)
- swap(this, i + 1, i + 2)
- }
- return this
- }
-
- Buffer.prototype.swap64 = function swap64 () {
- var len = this.length
- if (len % 8 !== 0) {
- throw new RangeError('Buffer size must be a multiple of 64-bits')
- }
- for (var i = 0; i < len; i += 8) {
- swap(this, i, i + 7)
- swap(this, i + 1, i + 6)
- swap(this, i + 2, i + 5)
- swap(this, i + 3, i + 4)
- }
- return this
- }
-
- Buffer.prototype.toString = function toString () {
- var length = this.length | 0
- if (length === 0) return ''
- if (arguments.length === 0) return utf8Slice(this, 0, length)
- return slowToString.apply(this, arguments)
- }
-
- Buffer.prototype.equals = function equals (b) {
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
- if (this === b) return true
- return Buffer.compare(this, b) === 0
- }
-
- Buffer.prototype.inspect = function inspect () {
- var str = ''
- var max = exports.INSPECT_MAX_BYTES
- if (this.length > 0) {
- str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
- if (this.length > max) str += ' ... '
- }
- return '<Buffer ' + str + '>'
- }
-
- Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
- if (!Buffer.isBuffer(target)) {
- throw new TypeError('Argument must be a Buffer')
- }
-
- if (start === undefined) {
- start = 0
- }
- if (end === undefined) {
- end = target ? target.length : 0
- }
- if (thisStart === undefined) {
- thisStart = 0
- }
- if (thisEnd === undefined) {
- thisEnd = this.length
- }
-
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
- throw new RangeError('out of range index')
- }
-
- if (thisStart >= thisEnd && start >= end) {
- return 0
- }
- if (thisStart >= thisEnd) {
- return -1
- }
- if (start >= end) {
- return 1
- }
-
- start >>>= 0
- end >>>= 0
- thisStart >>>= 0
- thisEnd >>>= 0
-
- if (this === target) return 0
-
- var x = thisEnd - thisStart
- var y = end - start
- var len = Math.min(x, y)
-
- var thisCopy = this.slice(thisStart, thisEnd)
- var targetCopy = target.slice(start, end)
-
- for (var i = 0; i < len; ++i) {
- if (thisCopy[i] !== targetCopy[i]) {
- x = thisCopy[i]
- y = targetCopy[i]
- break
- }
- }
-
- if (x < y) return -1
- if (y < x) return 1
- return 0
- }
-
- // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
- // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
- //
- // Arguments:
- // - buffer - a Buffer to search
- // - val - a string, Buffer, or number
- // - byteOffset - an index into `buffer`; will be clamped to an int32
- // - encoding - an optional encoding, relevant is val is a string
- // - dir - true for indexOf, false for lastIndexOf
- function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
- // Empty buffer means no match
- if (buffer.length === 0) return -1
-
- // Normalize byteOffset
- if (typeof byteOffset === 'string') {
- encoding = byteOffset
- byteOffset = 0
- } else if (byteOffset > 0x7fffffff) {
- byteOffset = 0x7fffffff
- } else if (byteOffset < -0x80000000) {
- byteOffset = -0x80000000
- }
- byteOffset = +byteOffset // Coerce to Number.
- if (isNaN(byteOffset)) {
- // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
- byteOffset = dir ? 0 : (buffer.length - 1)
- }
-
- // Normalize byteOffset: negative offsets start from the end of the buffer
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset
- if (byteOffset >= buffer.length) {
- if (dir) return -1
- else byteOffset = buffer.length - 1
- } else if (byteOffset < 0) {
- if (dir) byteOffset = 0
- else return -1
- }
-
- // Normalize val
- if (typeof val === 'string') {
- val = Buffer.from(val, encoding)
- }
-
- // Finally, search either indexOf (if dir is true) or lastIndexOf
- if (Buffer.isBuffer(val)) {
- // Special case: looking for empty string/buffer always fails
- if (val.length === 0) {
- return -1
- }
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
- } else if (typeof val === 'number') {
- val = val & 0xFF // Search for a byte value [0-255]
- if (Buffer.TYPED_ARRAY_SUPPORT &&
- typeof Uint8Array.prototype.indexOf === 'function') {
- if (dir) {
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
- } else {
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
- }
- }
- return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
- }
-
- throw new TypeError('val must be string, number or Buffer')
- }
-
- function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
- var indexSize = 1
- var arrLength = arr.length
- var valLength = val.length
-
- if (encoding !== undefined) {
- encoding = String(encoding).toLowerCase()
- if (encoding === 'ucs2' || encoding === 'ucs-2' ||
- encoding === 'utf16le' || encoding === 'utf-16le') {
- if (arr.length < 2 || val.length < 2) {
- return -1
- }
- indexSize = 2
- arrLength /= 2
- valLength /= 2
- byteOffset /= 2
- }
- }
-
- function read (buf, i) {
- if (indexSize === 1) {
- return buf[i]
- } else {
- return buf.readUInt16BE(i * indexSize)
- }
- }
-
- var i
- if (dir) {
- var foundIndex = -1
- for (i = byteOffset; i < arrLength; i++) {
- if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
- if (foundIndex === -1) foundIndex = i
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
- } else {
- if (foundIndex !== -1) i -= i - foundIndex
- foundIndex = -1
- }
- }
- } else {
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
- for (i = byteOffset; i >= 0; i--) {
- var found = true
- for (var j = 0; j < valLength; j++) {
- if (read(arr, i + j) !== read(val, j)) {
- found = false
- break
- }
- }
- if (found) return i
- }
- }
-
- return -1
- }
-
- Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
- return this.indexOf(val, byteOffset, encoding) !== -1
- }
-
- Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
- }
-
- Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
- }
-
- function hexWrite (buf, string, offset, length) {
- offset = Number(offset) || 0
- var remaining = buf.length - offset
- if (!length) {
- length = remaining
- } else {
- length = Number(length)
- if (length > remaining) {
- length = remaining
- }
- }
-
- // must be an even number of digits
- var strLen = string.length
- if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
-
- if (length > strLen / 2) {
- length = strLen / 2
- }
- for (var i = 0; i < length; ++i) {
- var parsed = parseInt(string.substr(i * 2, 2), 16)
- if (isNaN(parsed)) return i
- buf[offset + i] = parsed
- }
- return i
- }
-
- function utf8Write (buf, string, offset, length) {
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
- }
-
- function asciiWrite (buf, string, offset, length) {
- return blitBuffer(asciiToBytes(string), buf, offset, length)
- }
-
- function latin1Write (buf, string, offset, length) {
- return asciiWrite(buf, string, offset, length)
- }
-
- function base64Write (buf, string, offset, length) {
- return blitBuffer(base64ToBytes(string), buf, offset, length)
- }
-
- function ucs2Write (buf, string, offset, length) {
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
- }
-
- Buffer.prototype.write = function write (string, offset, length, encoding) {
- // Buffer#write(string)
- if (offset === undefined) {
- encoding = 'utf8'
- length = this.length
- offset = 0
- // Buffer#write(string, encoding)
- } else if (length === undefined && typeof offset === 'string') {
- encoding = offset
- length = this.length
- offset = 0
- // Buffer#write(string, offset[, length][, encoding])
- } else if (isFinite(offset)) {
- offset = offset | 0
- if (isFinite(length)) {
- length = length | 0
- if (encoding === undefined) encoding = 'utf8'
- } else {
- encoding = length
- length = undefined
- }
- // legacy write(string, encoding, offset, length) - remove in v0.13
- } else {
- throw new Error(
- 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
- )
- }
-
- var remaining = this.length - offset
- if (length === undefined || length > remaining) length = remaining
-
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
- throw new RangeError('Attempt to write outside buffer bounds')
- }
-
- if (!encoding) encoding = 'utf8'
-
- var loweredCase = false
- for (;;) {
- switch (encoding) {
- case 'hex':
- return hexWrite(this, string, offset, length)
-
- case 'utf8':
- case 'utf-8':
- return utf8Write(this, string, offset, length)
-
- case 'ascii':
- return asciiWrite(this, string, offset, length)
-
- case 'latin1':
- case 'binary':
- return latin1Write(this, string, offset, length)
-
- case 'base64':
- // Warning: maxLength not taken into account in base64Write
- return base64Write(this, string, offset, length)
-
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return ucs2Write(this, string, offset, length)
-
- default:
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
- encoding = ('' + encoding).toLowerCase()
- loweredCase = true
- }
- }
- }
-
- Buffer.prototype.toJSON = function toJSON () {
- return {
- type: 'Buffer',
- data: Array.prototype.slice.call(this._arr || this, 0)
- }
- }
-
- function base64Slice (buf, start, end) {
- if (start === 0 && end === buf.length) {
- return base64.fromByteArray(buf)
- } else {
- return base64.fromByteArray(buf.slice(start, end))
- }
- }
-
- function utf8Slice (buf, start, end) {
- end = Math.min(buf.length, end)
- var res = []
-
- var i = start
- while (i < end) {
- var firstByte = buf[i]
- var codePoint = null
- var bytesPerSequence = (firstByte > 0xEF) ? 4
- : (firstByte > 0xDF) ? 3
- : (firstByte > 0xBF) ? 2
- : 1
-
- if (i + bytesPerSequence <= end) {
- var secondByte, thirdByte, fourthByte, tempCodePoint
-
- switch (bytesPerSequence) {
- case 1:
- if (firstByte < 0x80) {
- codePoint = firstByte
- }
- break
- case 2:
- secondByte = buf[i + 1]
- if ((secondByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
- if (tempCodePoint > 0x7F) {
- codePoint = tempCodePoint
- }
- }
- break
- case 3:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
- codePoint = tempCodePoint
- }
- }
- break
- case 4:
- secondByte = buf[i + 1]
- thirdByte = buf[i + 2]
- fourthByte = buf[i + 3]
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
- codePoint = tempCodePoint
- }
- }
- }
- }
-
- if (codePoint === null) {
- // we did not generate a valid codePoint so insert a
- // replacement char (U+FFFD) and advance only 1 byte
- codePoint = 0xFFFD
- bytesPerSequence = 1
- } else if (codePoint > 0xFFFF) {
- // encode to utf16 (surrogate pair dance)
- codePoint -= 0x10000
- res.push(codePoint >>> 10 & 0x3FF | 0xD800)
- codePoint = 0xDC00 | codePoint & 0x3FF
- }
-
- res.push(codePoint)
- i += bytesPerSequence
- }
-
- return decodeCodePointsArray(res)
- }
-
- // Based on http://stackoverflow.com/a/22747272/680742, the browser with
- // the lowest limit is Chrome, with 0x10000 args.
- // We go 1 magnitude less, for safety
- var MAX_ARGUMENTS_LENGTH = 0x1000
-
- function decodeCodePointsArray (codePoints) {
- var len = codePoints.length
- if (len <= MAX_ARGUMENTS_LENGTH) {
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
- }
-
- // Decode in chunks to avoid "call stack size exceeded".
- var res = ''
- var i = 0
- while (i < len) {
- res += String.fromCharCode.apply(
- String,
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
- )
- }
- return res
- }
-
- function asciiSlice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
-
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i] & 0x7F)
- }
- return ret
- }
-
- function latin1Slice (buf, start, end) {
- var ret = ''
- end = Math.min(buf.length, end)
-
- for (var i = start; i < end; ++i) {
- ret += String.fromCharCode(buf[i])
- }
- return ret
- }
-
- function hexSlice (buf, start, end) {
- var len = buf.length
-
- if (!start || start < 0) start = 0
- if (!end || end < 0 || end > len) end = len
-
- var out = ''
- for (var i = start; i < end; ++i) {
- out += toHex(buf[i])
- }
- return out
- }
-
- function utf16leSlice (buf, start, end) {
- var bytes = buf.slice(start, end)
- var res = ''
- for (var i = 0; i < bytes.length; i += 2) {
- res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
- }
- return res
- }
-
- Buffer.prototype.slice = function slice (start, end) {
- var len = this.length
- start = ~~start
- end = end === undefined ? len : ~~end
-
- if (start < 0) {
- start += len
- if (start < 0) start = 0
- } else if (start > len) {
- start = len
- }
-
- if (end < 0) {
- end += len
- if (end < 0) end = 0
- } else if (end > len) {
- end = len
- }
-
- if (end < start) end = start
-
- var newBuf
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- newBuf = this.subarray(start, end)
- newBuf.__proto__ = Buffer.prototype
- } else {
- var sliceLen = end - start
- newBuf = new Buffer(sliceLen, undefined)
- for (var i = 0; i < sliceLen; ++i) {
- newBuf[i] = this[i + start]
- }
- }
-
- return newBuf
- }
-
- /*
- * Need to make sure that buffer isn't trying to write out of bounds.
- */
- function checkOffset (offset, ext, length) {
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
- }
-
- Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
-
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
-
- return val
- }
-
- Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) {
- checkOffset(offset, byteLength, this.length)
- }
-
- var val = this[offset + --byteLength]
- var mul = 1
- while (byteLength > 0 && (mul *= 0x100)) {
- val += this[offset + --byteLength] * mul
- }
-
- return val
- }
-
- Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 1, this.length)
- return this[offset]
- }
-
- Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- return this[offset] | (this[offset + 1] << 8)
- }
-
- Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- return (this[offset] << 8) | this[offset + 1]
- }
-
- Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
-
- return ((this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16)) +
- (this[offset + 3] * 0x1000000)
- }
-
- Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
-
- return (this[offset] * 0x1000000) +
- ((this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- this[offset + 3])
- }
-
- Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
-
- var val = this[offset]
- var mul = 1
- var i = 0
- while (++i < byteLength && (mul *= 0x100)) {
- val += this[offset + i] * mul
- }
- mul *= 0x80
-
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
-
- return val
- }
-
- Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) checkOffset(offset, byteLength, this.length)
-
- var i = byteLength
- var mul = 1
- var val = this[offset + --i]
- while (i > 0 && (mul *= 0x100)) {
- val += this[offset + --i] * mul
- }
- mul *= 0x80
-
- if (val >= mul) val -= Math.pow(2, 8 * byteLength)
-
- return val
- }
-
- Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 1, this.length)
- if (!(this[offset] & 0x80)) return (this[offset])
- return ((0xff - this[offset] + 1) * -1)
- }
-
- Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset] | (this[offset + 1] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
- }
-
- Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 2, this.length)
- var val = this[offset + 1] | (this[offset] << 8)
- return (val & 0x8000) ? val | 0xFFFF0000 : val
- }
-
- Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
-
- return (this[offset]) |
- (this[offset + 1] << 8) |
- (this[offset + 2] << 16) |
- (this[offset + 3] << 24)
- }
-
- Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
-
- return (this[offset] << 24) |
- (this[offset + 1] << 16) |
- (this[offset + 2] << 8) |
- (this[offset + 3])
- }
-
- Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, true, 23, 4)
- }
-
- Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 4, this.length)
- return ieee754.read(this, offset, false, 23, 4)
- }
-
- Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, true, 52, 8)
- }
-
- Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
- if (!noAssert) checkOffset(offset, 8, this.length)
- return ieee754.read(this, offset, false, 52, 8)
- }
-
- function checkInt (buf, value, offset, ext, max, min) {
- if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
- if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
- }
-
- Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1
- checkInt(this, value, offset, byteLength, maxBytes, 0)
- }
-
- var mul = 1
- var i = 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
-
- return offset + byteLength
- }
-
- Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- byteLength = byteLength | 0
- if (!noAssert) {
- var maxBytes = Math.pow(2, 8 * byteLength) - 1
- checkInt(this, value, offset, byteLength, maxBytes, 0)
- }
-
- var i = byteLength - 1
- var mul = 1
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- this[offset + i] = (value / mul) & 0xFF
- }
-
- return offset + byteLength
- }
-
- Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
- this[offset] = (value & 0xff)
- return offset + 1
- }
-
- function objectWriteUInt16 (buf, value, offset, littleEndian) {
- if (value < 0) value = 0xffff + value + 1
- for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
- buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
- (littleEndian ? i : 1 - i) * 8
- }
- }
-
- Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- } else {
- objectWriteUInt16(this, value, offset, true)
- }
- return offset + 2
- }
-
- Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- } else {
- objectWriteUInt16(this, value, offset, false)
- }
- return offset + 2
- }
-
- function objectWriteUInt32 (buf, value, offset, littleEndian) {
- if (value < 0) value = 0xffffffff + value + 1
- for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
- buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
- }
- }
-
- Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset + 3] = (value >>> 24)
- this[offset + 2] = (value >>> 16)
- this[offset + 1] = (value >>> 8)
- this[offset] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, true)
- }
- return offset + 4
- }
-
- Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, false)
- }
- return offset + 4
- }
-
- Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) {
- var limit = Math.pow(2, 8 * byteLength - 1)
-
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
-
- var i = 0
- var mul = 1
- var sub = 0
- this[offset] = value & 0xFF
- while (++i < byteLength && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
- sub = 1
- }
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
- }
-
- return offset + byteLength
- }
-
- Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) {
- var limit = Math.pow(2, 8 * byteLength - 1)
-
- checkInt(this, value, offset, byteLength, limit - 1, -limit)
- }
-
- var i = byteLength - 1
- var mul = 1
- var sub = 0
- this[offset + i] = value & 0xFF
- while (--i >= 0 && (mul *= 0x100)) {
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
- sub = 1
- }
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
- }
-
- return offset + byteLength
- }
-
- Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
- if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
- if (value < 0) value = 0xff + value + 1
- this[offset] = (value & 0xff)
- return offset + 1
- }
-
- Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- } else {
- objectWriteUInt16(this, value, offset, true)
- }
- return offset + 2
- }
-
- Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 8)
- this[offset + 1] = (value & 0xff)
- } else {
- objectWriteUInt16(this, value, offset, false)
- }
- return offset + 2
- }
-
- Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value & 0xff)
- this[offset + 1] = (value >>> 8)
- this[offset + 2] = (value >>> 16)
- this[offset + 3] = (value >>> 24)
- } else {
- objectWriteUInt32(this, value, offset, true)
- }
- return offset + 4
- }
-
- Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
- value = +value
- offset = offset | 0
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
- if (value < 0) value = 0xffffffff + value + 1
- if (Buffer.TYPED_ARRAY_SUPPORT) {
- this[offset] = (value >>> 24)
- this[offset + 1] = (value >>> 16)
- this[offset + 2] = (value >>> 8)
- this[offset + 3] = (value & 0xff)
- } else {
- objectWriteUInt32(this, value, offset, false)
- }
- return offset + 4
- }
-
- function checkIEEE754 (buf, value, offset, ext, max, min) {
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
- if (offset < 0) throw new RangeError('Index out of range')
- }
-
- function writeFloat (buf, value, offset, littleEndian, noAssert) {
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
- }
- ieee754.write(buf, value, offset, littleEndian, 23, 4)
- return offset + 4
- }
-
- Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
- return writeFloat(this, value, offset, true, noAssert)
- }
-
- Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
- return writeFloat(this, value, offset, false, noAssert)
- }
-
- function writeDouble (buf, value, offset, littleEndian, noAssert) {
- if (!noAssert) {
- checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
- }
- ieee754.write(buf, value, offset, littleEndian, 52, 8)
- return offset + 8
- }
-
- Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
- return writeDouble(this, value, offset, true, noAssert)
- }
-
- Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
- return writeDouble(this, value, offset, false, noAssert)
- }
-
- // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
- Buffer.prototype.copy = function copy (target, targetStart, start, end) {
- if (!start) start = 0
- if (!end && end !== 0) end = this.length
- if (targetStart >= target.length) targetStart = target.length
- if (!targetStart) targetStart = 0
- if (end > 0 && end < start) end = start
-
- // Copy 0 bytes; we're done
- if (end === start) return 0
- if (target.length === 0 || this.length === 0) return 0
-
- // Fatal error conditions
- if (targetStart < 0) {
- throw new RangeError('targetStart out of bounds')
- }
- if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
-
- // Are we oob?
- if (end > this.length) end = this.length
- if (target.length - targetStart < end - start) {
- end = target.length - targetStart + start
- }
-
- var len = end - start
- var i
-
- if (this === target && start < targetStart && targetStart < end) {
- // descending copy from end
- for (i = len - 1; i >= 0; --i) {
- target[i + targetStart] = this[i + start]
- }
- } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
- // ascending copy from start
- for (i = 0; i < len; ++i) {
- target[i + targetStart] = this[i + start]
- }
- } else {
- Uint8Array.prototype.set.call(
- target,
- this.subarray(start, start + len),
- targetStart
- )
- }
-
- return len
- }
-
- // Usage:
- // buffer.fill(number[, offset[, end]])
- // buffer.fill(buffer[, offset[, end]])
- // buffer.fill(string[, offset[, end]][, encoding])
- Buffer.prototype.fill = function fill (val, start, end, encoding) {
- // Handle string cases:
- if (typeof val === 'string') {
- if (typeof start === 'string') {
- encoding = start
- start = 0
- end = this.length
- } else if (typeof end === 'string') {
- encoding = end
- end = this.length
- }
- if (val.length === 1) {
- var code = val.charCodeAt(0)
- if (code < 256) {
- val = code
- }
- }
- if (encoding !== undefined && typeof encoding !== 'string') {
- throw new TypeError('encoding must be a string')
- }
- if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
- throw new TypeError('Unknown encoding: ' + encoding)
- }
- } else if (typeof val === 'number') {
- val = val & 255
- }
-
- // Invalid ranges are not set to a default, so can range check early.
- if (start < 0 || this.length < start || this.length < end) {
- throw new RangeError('Out of range index')
- }
-
- if (end <= start) {
- return this
- }
-
- start = start >>> 0
- end = end === undefined ? this.length : end >>> 0
-
- if (!val) val = 0
-
- var i
- if (typeof val === 'number') {
- for (i = start; i < end; ++i) {
- this[i] = val
- }
- } else {
- var bytes = Buffer.isBuffer(val)
- ? val
- : utf8ToBytes(new Buffer(val, encoding).toString())
- var len = bytes.length
- for (i = 0; i < end - start; ++i) {
- this[i + start] = bytes[i % len]
- }
- }
-
- return this
- }
-
- // HELPER FUNCTIONS
- // ================
-
- var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
-
- function base64clean (str) {
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
- str = stringtrim(str).replace(INVALID_BASE64_RE, '')
- // Node converts strings with length < 2 to ''
- if (str.length < 2) return ''
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
- while (str.length % 4 !== 0) {
- str = str + '='
- }
- return str
- }
-
- function stringtrim (str) {
- if (str.trim) return str.trim()
- return str.replace(/^\s+|\s+$/g, '')
- }
-
- function toHex (n) {
- if (n < 16) return '0' + n.toString(16)
- return n.toString(16)
- }
-
- function utf8ToBytes (string, units) {
- units = units || Infinity
- var codePoint
- var length = string.length
- var leadSurrogate = null
- var bytes = []
-
- for (var i = 0; i < length; ++i) {
- codePoint = string.charCodeAt(i)
-
- // is surrogate component
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
- // last char was a lead
- if (!leadSurrogate) {
- // no lead yet
- if (codePoint > 0xDBFF) {
- // unexpected trail
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- } else if (i + 1 === length) {
- // unpaired lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- continue
- }
-
- // valid lead
- leadSurrogate = codePoint
-
- continue
- }
-
- // 2 leads in a row
- if (codePoint < 0xDC00) {
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- leadSurrogate = codePoint
- continue
- }
-
- // valid surrogate pair
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
- } else if (leadSurrogate) {
- // valid bmp char, but last char was a lead
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
- }
-
- leadSurrogate = null
-
- // encode utf8
- if (codePoint < 0x80) {
- if ((units -= 1) < 0) break
- bytes.push(codePoint)
- } else if (codePoint < 0x800) {
- if ((units -= 2) < 0) break
- bytes.push(
- codePoint >> 0x6 | 0xC0,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x10000) {
- if ((units -= 3) < 0) break
- bytes.push(
- codePoint >> 0xC | 0xE0,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else if (codePoint < 0x110000) {
- if ((units -= 4) < 0) break
- bytes.push(
- codePoint >> 0x12 | 0xF0,
- codePoint >> 0xC & 0x3F | 0x80,
- codePoint >> 0x6 & 0x3F | 0x80,
- codePoint & 0x3F | 0x80
- )
- } else {
- throw new Error('Invalid code point')
- }
- }
-
- return bytes
- }
-
- function asciiToBytes (str) {
- var byteArray = []
- for (var i = 0; i < str.length; ++i) {
- // Node's code seems to be doing this and not & 0x7F..
- byteArray.push(str.charCodeAt(i) & 0xFF)
- }
- return byteArray
- }
-
- function utf16leToBytes (str, units) {
- var c, hi, lo
- var byteArray = []
- for (var i = 0; i < str.length; ++i) {
- if ((units -= 2) < 0) break
-
- c = str.charCodeAt(i)
- hi = c >> 8
- lo = c % 256
- byteArray.push(lo)
- byteArray.push(hi)
- }
-
- return byteArray
- }
-
- function base64ToBytes (str) {
- return base64.toByteArray(base64clean(str))
- }
-
- function blitBuffer (src, dst, offset, length) {
- for (var i = 0; i < length; ++i) {
- if ((i + offset >= dst.length) || (i >= src.length)) break
- dst[i + offset] = src[i]
- }
- return i
- }
-
- function isnan (val) {
- return val !== val // eslint-disable-line no-self-compare
- }
-
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{"base64-js":2,"ieee754":15,"isarray":18}],8:[function(require,module,exports){
- (function (Buffer){
- var Transform = require('stream').Transform
- var inherits = require('inherits')
- var StringDecoder = require('string_decoder').StringDecoder
- module.exports = CipherBase
- inherits(CipherBase, Transform)
- function CipherBase (hashMode) {
- Transform.call(this)
- this.hashMode = typeof hashMode === 'string'
- if (this.hashMode) {
- this[hashMode] = this._finalOrDigest
- } else {
- this.final = this._finalOrDigest
- }
- this._decoder = null
- this._encoding = null
- }
- CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
- if (typeof data === 'string') {
- data = new Buffer(data, inputEnc)
- }
- var outData = this._update(data)
- if (this.hashMode) {
- return this
- }
- if (outputEnc) {
- outData = this._toString(outData, outputEnc)
- }
- return outData
- }
-
- CipherBase.prototype.setAutoPadding = function () {}
-
- CipherBase.prototype.getAuthTag = function () {
- throw new Error('trying to get auth tag in unsupported state')
- }
-
- CipherBase.prototype.setAuthTag = function () {
- throw new Error('trying to set auth tag in unsupported state')
- }
-
- CipherBase.prototype.setAAD = function () {
- throw new Error('trying to set aad in unsupported state')
- }
-
- CipherBase.prototype._transform = function (data, _, next) {
- var err
- try {
- if (this.hashMode) {
- this._update(data)
- } else {
- this.push(this._update(data))
- }
- } catch (e) {
- err = e
- } finally {
- next(err)
- }
- }
- CipherBase.prototype._flush = function (done) {
- var err
- try {
- this.push(this._final())
- } catch (e) {
- err = e
- } finally {
- done(err)
- }
- }
- CipherBase.prototype._finalOrDigest = function (outputEnc) {
- var outData = this._final() || new Buffer('')
- if (outputEnc) {
- outData = this._toString(outData, outputEnc, true)
- }
- return outData
- }
-
- CipherBase.prototype._toString = function (value, enc, fin) {
- if (!this._decoder) {
- this._decoder = new StringDecoder(enc)
- this._encoding = enc
- }
- if (this._encoding !== enc) {
- throw new Error('can\'t switch encodings')
- }
- var out = this._decoder.write(value)
- if (fin) {
- out += this._decoder.end()
- }
- return out
- }
-
- }).call(this,require("buffer").Buffer)
- },{"buffer":7,"inherits":16,"stream":43,"string_decoder":44}],9:[function(require,module,exports){
- (function (Buffer){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
-
- // NOTE: These type checking functions intentionally don't use `instanceof`
- // because it is fragile and can be easily faked with `Object.create()`.
-
- function isArray(arg) {
- if (Array.isArray) {
- return Array.isArray(arg);
- }
- return objectToString(arg) === '[object Array]';
- }
- exports.isArray = isArray;
-
- function isBoolean(arg) {
- return typeof arg === 'boolean';
- }
- exports.isBoolean = isBoolean;
-
- function isNull(arg) {
- return arg === null;
- }
- exports.isNull = isNull;
-
- function isNullOrUndefined(arg) {
- return arg == null;
- }
- exports.isNullOrUndefined = isNullOrUndefined;
-
- function isNumber(arg) {
- return typeof arg === 'number';
- }
- exports.isNumber = isNumber;
-
- function isString(arg) {
- return typeof arg === 'string';
- }
- exports.isString = isString;
-
- function isSymbol(arg) {
- return typeof arg === 'symbol';
- }
- exports.isSymbol = isSymbol;
-
- function isUndefined(arg) {
- return arg === void 0;
- }
- exports.isUndefined = isUndefined;
-
- function isRegExp(re) {
- return objectToString(re) === '[object RegExp]';
- }
- exports.isRegExp = isRegExp;
-
- function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
- }
- exports.isObject = isObject;
-
- function isDate(d) {
- return objectToString(d) === '[object Date]';
- }
- exports.isDate = isDate;
-
- function isError(e) {
- return (objectToString(e) === '[object Error]' || e instanceof Error);
- }
- exports.isError = isError;
-
- function isFunction(arg) {
- return typeof arg === 'function';
- }
- exports.isFunction = isFunction;
-
- function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
- }
- exports.isPrimitive = isPrimitive;
-
- exports.isBuffer = Buffer.isBuffer;
-
- function objectToString(o) {
- return Object.prototype.toString.call(o);
- }
-
- }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
- },{"../../is-buffer/index.js":17}],10:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var inherits = require('inherits')
- var md5 = require('./md5')
- var rmd160 = require('ripemd160')
- var sha = require('sha.js')
-
- var Base = require('cipher-base')
-
- function HashNoConstructor(hash) {
- Base.call(this, 'digest')
-
- this._hash = hash
- this.buffers = []
- }
-
- inherits(HashNoConstructor, Base)
-
- HashNoConstructor.prototype._update = function (data) {
- this.buffers.push(data)
- }
-
- HashNoConstructor.prototype._final = function () {
- var buf = Buffer.concat(this.buffers)
- var r = this._hash(buf)
- this.buffers = null
-
- return r
- }
-
- function Hash(hash) {
- Base.call(this, 'digest')
-
- this._hash = hash
- }
-
- inherits(Hash, Base)
-
- Hash.prototype._update = function (data) {
- this._hash.update(data)
- }
-
- Hash.prototype._final = function () {
- return this._hash.digest()
- }
-
- module.exports = function createHash (alg) {
- alg = alg.toLowerCase()
- if ('md5' === alg) return new HashNoConstructor(md5)
- if ('rmd160' === alg || 'ripemd160' === alg) return new HashNoConstructor(rmd160)
-
- return new Hash(sha(alg))
- }
-
- }).call(this,require("buffer").Buffer)
- },{"./md5":12,"buffer":7,"cipher-base":8,"inherits":16,"ripemd160":34,"sha.js":36}],11:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var intSize = 4;
- var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0);
- var chrsz = 8;
-
- function toArray(buf, bigEndian) {
- if ((buf.length % intSize) !== 0) {
- var len = buf.length + (intSize - (buf.length % intSize));
- buf = Buffer.concat([buf, zeroBuffer], len);
- }
-
- var arr = [];
- var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
- for (var i = 0; i < buf.length; i += intSize) {
- arr.push(fn.call(buf, i));
- }
- return arr;
- }
-
- function toBuffer(arr, size, bigEndian) {
- var buf = new Buffer(size);
- var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
- for (var i = 0; i < arr.length; i++) {
- fn.call(buf, arr[i], i * 4, true);
- }
- return buf;
- }
-
- function hash(buf, fn, hashSize, bigEndian) {
- if (!Buffer.isBuffer(buf)) buf = new Buffer(buf);
- var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
- return toBuffer(arr, hashSize, bigEndian);
- }
- exports.hash = hash;
- }).call(this,require("buffer").Buffer)
- },{"buffer":7}],12:[function(require,module,exports){
- 'use strict';
- /*
- * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
- * Digest Algorithm, as defined in RFC 1321.
- * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
- * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
- * Distributed under the BSD License
- * See http://pajhome.org.uk/crypt/md5 for more info.
- */
-
- var helpers = require('./helpers');
-
- /*
- * Calculate the MD5 of an array of little-endian words, and a bit length
- */
- function core_md5(x, len)
- {
- /* append padding */
- x[len >> 5] |= 0x80 << ((len) % 32);
- x[(((len + 64) >>> 9) << 4) + 14] = len;
-
- var a = 1732584193;
- var b = -271733879;
- var c = -1732584194;
- var d = 271733878;
-
- for(var i = 0; i < x.length; i += 16)
- {
- var olda = a;
- var oldb = b;
- var oldc = c;
- var oldd = d;
-
- a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
- d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
- c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
- b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
- a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
- d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
- c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
- b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
- a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
- d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
- c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
- b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
- a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
- d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
- c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
- b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
-
- a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
- d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
- c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
- b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
- a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
- d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
- c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
- b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
- a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
- d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
- c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
- b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
- a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
- d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
- c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
- b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
-
- a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
- d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
- c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
- b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
- a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
- d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
- c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
- b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
- a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
- d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
- c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
- b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
- a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
- d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
- c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
- b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
-
- a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
- d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
- c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
- b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
- a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
- d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
- c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
- b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
- a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
- d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
- c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
- b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
- a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
- d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
- c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
- b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
-
- a = safe_add(a, olda);
- b = safe_add(b, oldb);
- c = safe_add(c, oldc);
- d = safe_add(d, oldd);
- }
- return Array(a, b, c, d);
-
- }
-
- /*
- * These functions implement the four basic operations the algorithm uses.
- */
- function md5_cmn(q, a, b, x, s, t)
- {
- return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
- }
- function md5_ff(a, b, c, d, x, s, t)
- {
- return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
- }
- function md5_gg(a, b, c, d, x, s, t)
- {
- return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
- }
- function md5_hh(a, b, c, d, x, s, t)
- {
- return md5_cmn(b ^ c ^ d, a, b, x, s, t);
- }
- function md5_ii(a, b, c, d, x, s, t)
- {
- return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
- }
-
- /*
- * Add integers, wrapping at 2^32. This uses 16-bit operations internally
- * to work around bugs in some JS interpreters.
- */
- function safe_add(x, y)
- {
- var lsw = (x & 0xFFFF) + (y & 0xFFFF);
- var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
- return (msw << 16) | (lsw & 0xFFFF);
- }
-
- /*
- * Bitwise rotate a 32-bit number to the left.
- */
- function bit_rol(num, cnt)
- {
- return (num << cnt) | (num >>> (32 - cnt));
- }
-
- module.exports = function md5(buf) {
- return helpers.hash(buf, core_md5, 16);
- };
- },{"./helpers":11}],13:[function(require,module,exports){
- (function (Buffer){
- 'use strict';
- var createHash = require('create-hash/browser');
- var inherits = require('inherits')
-
- var Transform = require('stream').Transform
-
- var ZEROS = new Buffer(128)
- ZEROS.fill(0)
-
- function Hmac(alg, key) {
- Transform.call(this)
- alg = alg.toLowerCase()
- if (typeof key === 'string') {
- key = new Buffer(key)
- }
-
- var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
-
- this._alg = alg
- this._key = key
-
- if (key.length > blocksize) {
- key = createHash(alg).update(key).digest()
-
- } else if (key.length < blocksize) {
- key = Buffer.concat([key, ZEROS], blocksize)
- }
-
- var ipad = this._ipad = new Buffer(blocksize)
- var opad = this._opad = new Buffer(blocksize)
-
- for (var i = 0; i < blocksize; i++) {
- ipad[i] = key[i] ^ 0x36
- opad[i] = key[i] ^ 0x5C
- }
-
- this._hash = createHash(alg).update(ipad)
- }
-
- inherits(Hmac, Transform)
-
- Hmac.prototype.update = function (data, enc) {
- this._hash.update(data, enc)
-
- return this
- }
-
- Hmac.prototype._transform = function (data, _, next) {
- this._hash.update(data)
-
- next()
- }
-
- Hmac.prototype._flush = function (next) {
- this.push(this.digest())
-
- next()
- }
-
- Hmac.prototype.digest = function (enc) {
- var h = this._hash.digest()
-
- return createHash(this._alg).update(this._opad).update(h).digest(enc)
- }
-
- module.exports = function createHmac(alg, key) {
- return new Hmac(alg, key)
- }
-
- }).call(this,require("buffer").Buffer)
- },{"buffer":7,"create-hash/browser":10,"inherits":16,"stream":43}],14:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
-
- function EventEmitter() {
- this._events = this._events || {};
- this._maxListeners = this._maxListeners || undefined;
- }
- module.exports = EventEmitter;
-
- // Backwards-compat with node 0.10.x
- EventEmitter.EventEmitter = EventEmitter;
-
- EventEmitter.prototype._events = undefined;
- EventEmitter.prototype._maxListeners = undefined;
-
- // By default EventEmitters will print a warning if more than 10 listeners are
- // added to it. This is a useful default which helps finding memory leaks.
- EventEmitter.defaultMaxListeners = 10;
-
- // Obviously not all Emitters should be limited to 10. This function allows
- // that to be increased. Set to zero for unlimited.
- EventEmitter.prototype.setMaxListeners = function(n) {
- if (!isNumber(n) || n < 0 || isNaN(n))
- throw TypeError('n must be a positive number');
- this._maxListeners = n;
- return this;
- };
-
- EventEmitter.prototype.emit = function(type) {
- var er, handler, len, args, i, listeners;
-
- if (!this._events)
- this._events = {};
-
- // If there is no 'error' event listener then throw.
- if (type === 'error') {
- if (!this._events.error ||
- (isObject(this._events.error) && !this._events.error.length)) {
- er = arguments[1];
- if (er instanceof Error) {
- throw er; // Unhandled 'error' event
- } else {
- // At least give some kind of context to the user
- var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
- err.context = er;
- throw err;
- }
- }
- }
-
- handler = this._events[type];
-
- if (isUndefined(handler))
- return false;
-
- if (isFunction(handler)) {
- switch (arguments.length) {
- // fast cases
- case 1:
- handler.call(this);
- break;
- case 2:
- handler.call(this, arguments[1]);
- break;
- case 3:
- handler.call(this, arguments[1], arguments[2]);
- break;
- // slower
- default:
- args = Array.prototype.slice.call(arguments, 1);
- handler.apply(this, args);
- }
- } else if (isObject(handler)) {
- args = Array.prototype.slice.call(arguments, 1);
- listeners = handler.slice();
- len = listeners.length;
- for (i = 0; i < len; i++)
- listeners[i].apply(this, args);
- }
-
- return true;
- };
-
- EventEmitter.prototype.addListener = function(type, listener) {
- var m;
-
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
-
- if (!this._events)
- this._events = {};
-
- // To avoid recursion in the case that type === "newListener"! Before
- // adding it to the listeners, first emit "newListener".
- if (this._events.newListener)
- this.emit('newListener', type,
- isFunction(listener.listener) ?
- listener.listener : listener);
-
- if (!this._events[type])
- // Optimize the case of one listener. Don't need the extra array object.
- this._events[type] = listener;
- else if (isObject(this._events[type]))
- // If we've already got an array, just append.
- this._events[type].push(listener);
- else
- // Adding the second element, need to change to array.
- this._events[type] = [this._events[type], listener];
-
- // Check for listener leak
- if (isObject(this._events[type]) && !this._events[type].warned) {
- if (!isUndefined(this._maxListeners)) {
- m = this._maxListeners;
- } else {
- m = EventEmitter.defaultMaxListeners;
- }
-
- if (m && m > 0 && this._events[type].length > m) {
- this._events[type].warned = true;
- console.error('(node) warning: possible EventEmitter memory ' +
- 'leak detected. %d listeners added. ' +
- 'Use emitter.setMaxListeners() to increase limit.',
- this._events[type].length);
- if (typeof console.trace === 'function') {
- // not supported in IE 10
- console.trace();
- }
- }
- }
-
- return this;
- };
-
- EventEmitter.prototype.on = EventEmitter.prototype.addListener;
-
- EventEmitter.prototype.once = function(type, listener) {
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
-
- var fired = false;
-
- function g() {
- this.removeListener(type, g);
-
- if (!fired) {
- fired = true;
- listener.apply(this, arguments);
- }
- }
-
- g.listener = listener;
- this.on(type, g);
-
- return this;
- };
-
- // emits a 'removeListener' event iff the listener was removed
- EventEmitter.prototype.removeListener = function(type, listener) {
- var list, position, length, i;
-
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
-
- if (!this._events || !this._events[type])
- return this;
-
- list = this._events[type];
- length = list.length;
- position = -1;
-
- if (list === listener ||
- (isFunction(list.listener) && list.listener === listener)) {
- delete this._events[type];
- if (this._events.removeListener)
- this.emit('removeListener', type, listener);
-
- } else if (isObject(list)) {
- for (i = length; i-- > 0;) {
- if (list[i] === listener ||
- (list[i].listener && list[i].listener === listener)) {
- position = i;
- break;
- }
- }
-
- if (position < 0)
- return this;
-
- if (list.length === 1) {
- list.length = 0;
- delete this._events[type];
- } else {
- list.splice(position, 1);
- }
-
- if (this._events.removeListener)
- this.emit('removeListener', type, listener);
- }
-
- return this;
- };
-
- EventEmitter.prototype.removeAllListeners = function(type) {
- var key, listeners;
-
- if (!this._events)
- return this;
-
- // not listening for removeListener, no need to emit
- if (!this._events.removeListener) {
- if (arguments.length === 0)
- this._events = {};
- else if (this._events[type])
- delete this._events[type];
- return this;
- }
-
- // emit removeListener for all listeners on all events
- if (arguments.length === 0) {
- for (key in this._events) {
- if (key === 'removeListener') continue;
- this.removeAllListeners(key);
- }
- this.removeAllListeners('removeListener');
- this._events = {};
- return this;
- }
-
- listeners = this._events[type];
-
- if (isFunction(listeners)) {
- this.removeListener(type, listeners);
- } else if (listeners) {
- // LIFO order
- while (listeners.length)
- this.removeListener(type, listeners[listeners.length - 1]);
- }
- delete this._events[type];
-
- return this;
- };
-
- EventEmitter.prototype.listeners = function(type) {
- var ret;
- if (!this._events || !this._events[type])
- ret = [];
- else if (isFunction(this._events[type]))
- ret = [this._events[type]];
- else
- ret = this._events[type].slice();
- return ret;
- };
-
- EventEmitter.prototype.listenerCount = function(type) {
- if (this._events) {
- var evlistener = this._events[type];
-
- if (isFunction(evlistener))
- return 1;
- else if (evlistener)
- return evlistener.length;
- }
- return 0;
- };
-
- EventEmitter.listenerCount = function(emitter, type) {
- return emitter.listenerCount(type);
- };
-
- function isFunction(arg) {
- return typeof arg === 'function';
- }
-
- function isNumber(arg) {
- return typeof arg === 'number';
- }
-
- function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
- }
-
- function isUndefined(arg) {
- return arg === void 0;
- }
-
- },{}],15:[function(require,module,exports){
- exports.read = function (buffer, offset, isLE, mLen, nBytes) {
- var e, m
- var eLen = nBytes * 8 - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var nBits = -7
- var i = isLE ? (nBytes - 1) : 0
- var d = isLE ? -1 : 1
- var s = buffer[offset + i]
-
- i += d
-
- e = s & ((1 << (-nBits)) - 1)
- s >>= (-nBits)
- nBits += eLen
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
-
- m = e & ((1 << (-nBits)) - 1)
- e >>= (-nBits)
- nBits += mLen
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
-
- if (e === 0) {
- e = 1 - eBias
- } else if (e === eMax) {
- return m ? NaN : ((s ? -1 : 1) * Infinity)
- } else {
- m = m + Math.pow(2, mLen)
- e = e - eBias
- }
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
- }
-
- exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
- var e, m, c
- var eLen = nBytes * 8 - mLen - 1
- var eMax = (1 << eLen) - 1
- var eBias = eMax >> 1
- var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
- var i = isLE ? 0 : (nBytes - 1)
- var d = isLE ? 1 : -1
- var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
-
- value = Math.abs(value)
-
- if (isNaN(value) || value === Infinity) {
- m = isNaN(value) ? 1 : 0
- e = eMax
- } else {
- e = Math.floor(Math.log(value) / Math.LN2)
- if (value * (c = Math.pow(2, -e)) < 1) {
- e--
- c *= 2
- }
- if (e + eBias >= 1) {
- value += rt / c
- } else {
- value += rt * Math.pow(2, 1 - eBias)
- }
- if (value * c >= 2) {
- e++
- c /= 2
- }
-
- if (e + eBias >= eMax) {
- m = 0
- e = eMax
- } else if (e + eBias >= 1) {
- m = (value * c - 1) * Math.pow(2, mLen)
- e = e + eBias
- } else {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
- e = 0
- }
- }
-
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
-
- e = (e << mLen) | m
- eLen += mLen
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
-
- buffer[offset + i - d] |= s * 128
- }
-
- },{}],16:[function(require,module,exports){
- if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- };
- } else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
- }
-
- },{}],17:[function(require,module,exports){
- /*!
- * Determine if an object is a Buffer
- *
- * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
- * @license MIT
- */
-
- // The _isBuffer check is for Safari 5-7 support, because it's missing
- // Object.prototype.constructor. Remove this eventually
- module.exports = function (obj) {
- return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
- }
-
- function isBuffer (obj) {
- return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
- }
-
- // For Node v0.10 support. Remove this eventually.
- function isSlowBuffer (obj) {
- return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
- }
-
- },{}],18:[function(require,module,exports){
- var toString = {}.toString;
-
- module.exports = Array.isArray || function (arr) {
- return toString.call(arr) == '[object Array]';
- };
-
- },{}],19:[function(require,module,exports){
- (function (process,Buffer){
- var createHmac = require('create-hmac')
- var checkParameters = require('./precondition')
-
- exports.pbkdf2 = function (password, salt, iterations, keylen, digest, callback) {
- if (typeof digest === 'function') {
- callback = digest
- digest = undefined
- }
-
- checkParameters(iterations, keylen)
- if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')
-
- setTimeout(function () {
- callback(null, exports.pbkdf2Sync(password, salt, iterations, keylen, digest))
- })
- }
-
- var defaultEncoding
- if (process.browser) {
- defaultEncoding = 'utf-8'
- } else {
- var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)
-
- defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
- }
-
- exports.pbkdf2Sync = function (password, salt, iterations, keylen, digest) {
- if (!Buffer.isBuffer(password)) password = new Buffer(password, defaultEncoding)
- if (!Buffer.isBuffer(salt)) salt = new Buffer(salt, defaultEncoding)
-
- checkParameters(iterations, keylen)
-
- digest = digest || 'sha1'
-
- var hLen
- var l = 1
- var DK = new Buffer(keylen)
- var block1 = new Buffer(salt.length + 4)
- salt.copy(block1, 0, 0, salt.length)
-
- var r
- var T
-
- for (var i = 1; i <= l; i++) {
- block1.writeUInt32BE(i, salt.length)
- var U = createHmac(digest, password).update(block1).digest()
-
- if (!hLen) {
- hLen = U.length
- T = new Buffer(hLen)
- l = Math.ceil(keylen / hLen)
- r = keylen - (l - 1) * hLen
- }
-
- U.copy(T, 0, 0, hLen)
-
- for (var j = 1; j < iterations; j++) {
- U = createHmac(digest, password).update(U).digest()
- for (var k = 0; k < hLen; k++) T[k] ^= U[k]
- }
-
- var destPos = (i - 1) * hLen
- var len = (i === l ? r : hLen)
- T.copy(DK, destPos, 0, len)
- }
-
- return DK
- }
-
- }).call(this,require('_process'),require("buffer").Buffer)
- },{"./precondition":20,"_process":22,"buffer":7,"create-hmac":13}],20:[function(require,module,exports){
- var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
- module.exports = function (iterations, keylen) {
- if (typeof iterations !== 'number') {
- throw new TypeError('Iterations not a number')
- }
-
- if (iterations < 0) {
- throw new TypeError('Bad iterations')
- }
-
- if (typeof keylen !== 'number') {
- throw new TypeError('Key length not a number')
- }
-
- if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
- throw new TypeError('Bad key length')
- }
- }
-
- },{}],21:[function(require,module,exports){
- (function (process){
- 'use strict';
-
- if (!process.version ||
- process.version.indexOf('v0.') === 0 ||
- process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
- module.exports = nextTick;
- } else {
- module.exports = process.nextTick;
- }
-
- function nextTick(fn, arg1, arg2, arg3) {
- if (typeof fn !== 'function') {
- throw new TypeError('"callback" argument must be a function');
- }
- var len = arguments.length;
- var args, i;
- switch (len) {
- case 0:
- case 1:
- return process.nextTick(fn);
- case 2:
- return process.nextTick(function afterTickOne() {
- fn.call(null, arg1);
- });
- case 3:
- return process.nextTick(function afterTickTwo() {
- fn.call(null, arg1, arg2);
- });
- case 4:
- return process.nextTick(function afterTickThree() {
- fn.call(null, arg1, arg2, arg3);
- });
- default:
- args = new Array(len - 1);
- i = 0;
- while (i < args.length) {
- args[i++] = arguments[i];
- }
- return process.nextTick(function afterTick() {
- fn.apply(null, args);
- });
- }
- }
-
- }).call(this,require('_process'))
- },{"_process":22}],22:[function(require,module,exports){
- // shim for using process in browser
- var process = module.exports = {};
-
- // cached from whatever global is present so that test runners that stub it
- // don't break things. But we need to wrap it in a try catch in case it is
- // wrapped in strict mode code which doesn't define any globals. It's inside a
- // function because try/catches deoptimize in certain engines.
-
- var cachedSetTimeout;
- var cachedClearTimeout;
-
- function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
- }
- function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
- }
- (function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
- } ())
- function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // 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
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
-
-
- }
- function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // 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.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
-
-
-
- }
- var queue = [];
- var draining = false;
- var currentQueue;
- var queueIndex = -1;
-
- function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
- }
-
- function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
-
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
- }
-
- process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
- };
-
- // v8 likes predictible objects
- function Item(fun, array) {
- this.fun = fun;
- this.array = array;
- }
- Item.prototype.run = function () {
- this.fun.apply(null, this.array);
- };
- process.title = 'browser';
- process.browser = true;
- process.env = {};
- process.argv = [];
- process.version = ''; // empty string to avoid regexp issues
- process.versions = {};
-
- function noop() {}
-
- process.on = noop;
- process.addListener = noop;
- process.once = noop;
- process.off = noop;
- process.removeListener = noop;
- process.removeAllListeners = noop;
- process.emit = noop;
-
- process.binding = function (name) {
- throw new Error('process.binding is not supported');
- };
-
- process.cwd = function () { return '/' };
- process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
- };
- process.umask = function() { return 0; };
-
- },{}],23:[function(require,module,exports){
- module.exports = require("./lib/_stream_duplex.js")
-
- },{"./lib/_stream_duplex.js":24}],24:[function(require,module,exports){
- // a duplex stream is just a stream that is both readable and writable.
- // Since JS doesn't have multiple prototypal inheritance, this class
- // prototypally inherits from Readable, and then parasitically from
- // Writable.
-
- 'use strict';
-
- /*<replacement>*/
-
- var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- keys.push(key);
- }return keys;
- };
- /*</replacement>*/
-
- module.exports = Duplex;
-
- /*<replacement>*/
- var processNextTick = require('process-nextick-args');
- /*</replacement>*/
-
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
-
- var Readable = require('./_stream_readable');
- var Writable = require('./_stream_writable');
-
- util.inherits(Duplex, Readable);
-
- var keys = objectKeys(Writable.prototype);
- for (var v = 0; v < keys.length; v++) {
- var method = keys[v];
- if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
- }
-
- function Duplex(options) {
- if (!(this instanceof Duplex)) return new Duplex(options);
-
- Readable.call(this, options);
- Writable.call(this, options);
-
- if (options && options.readable === false) this.readable = false;
-
- if (options && options.writable === false) this.writable = false;
-
- this.allowHalfOpen = true;
- if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
-
- this.once('end', onend);
- }
-
- // the no-half-open enforcer
- function onend() {
- // if we allow half-open state, or if the writable side ended,
- // then we're ok.
- if (this.allowHalfOpen || this._writableState.ended) return;
-
- // no more data can be written.
- // But allow more writes to happen in this tick.
- processNextTick(onEndNT, this);
- }
-
- function onEndNT(self) {
- self.end();
- }
-
- function forEach(xs, f) {
- for (var i = 0, l = xs.length; i < l; i++) {
- f(xs[i], i);
- }
- }
- },{"./_stream_readable":26,"./_stream_writable":28,"core-util-is":9,"inherits":16,"process-nextick-args":21}],25:[function(require,module,exports){
- // a passthrough stream.
- // basically just the most minimal sort of Transform stream.
- // Every written chunk gets output as-is.
-
- 'use strict';
-
- module.exports = PassThrough;
-
- var Transform = require('./_stream_transform');
-
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
-
- util.inherits(PassThrough, Transform);
-
- function PassThrough(options) {
- if (!(this instanceof PassThrough)) return new PassThrough(options);
-
- Transform.call(this, options);
- }
-
- PassThrough.prototype._transform = function (chunk, encoding, cb) {
- cb(null, chunk);
- };
- },{"./_stream_transform":27,"core-util-is":9,"inherits":16}],26:[function(require,module,exports){
- (function (process){
- 'use strict';
-
- module.exports = Readable;
-
- /*<replacement>*/
- var processNextTick = require('process-nextick-args');
- /*</replacement>*/
-
- /*<replacement>*/
- var isArray = require('isarray');
- /*</replacement>*/
-
- Readable.ReadableState = ReadableState;
-
- /*<replacement>*/
- var EE = require('events').EventEmitter;
-
- var EElistenerCount = function (emitter, type) {
- return emitter.listeners(type).length;
- };
- /*</replacement>*/
-
- /*<replacement>*/
- var Stream;
- (function () {
- try {
- Stream = require('st' + 'ream');
- } catch (_) {} finally {
- if (!Stream) Stream = require('events').EventEmitter;
- }
- })();
- /*</replacement>*/
-
- var Buffer = require('buffer').Buffer;
- /*<replacement>*/
- var bufferShim = require('buffer-shims');
- /*</replacement>*/
-
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
-
- /*<replacement>*/
- var debugUtil = require('util');
- var debug = void 0;
- if (debugUtil && debugUtil.debuglog) {
- debug = debugUtil.debuglog('stream');
- } else {
- debug = function () {};
- }
- /*</replacement>*/
-
- var BufferList = require('./internal/streams/BufferList');
- var StringDecoder;
-
- util.inherits(Readable, Stream);
-
- function prependListener(emitter, event, fn) {
- if (typeof emitter.prependListener === 'function') {
- return emitter.prependListener(event, fn);
- } else {
- // This is a hack to make sure that our error handler is attached before any
- // userland ones. NEVER DO THIS. This is here only because this code needs
- // to continue to work with older versions of Node.js that do not include
- // the prependListener() method. The goal is to eventually remove this hack.
- if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
- }
- }
-
- var Duplex;
- function ReadableState(options, stream) {
- Duplex = Duplex || require('./_stream_duplex');
-
- options = options || {};
-
- // object stream flag. Used to make read(n) ignore n and to
- // make all the buffer merging and length checks go away
- this.objectMode = !!options.objectMode;
-
- if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
-
- // the point at which it stops calling _read() to fill the buffer
- // Note: 0 is a valid value, means "don't call _read preemptively ever"
- var hwm = options.highWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
- this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
-
- // cast to ints.
- this.highWaterMark = ~ ~this.highWaterMark;
-
- // A linked list is used to store data chunks instead of an array because the
- // linked list can remove elements from the beginning faster than
- // array.shift()
- this.buffer = new BufferList();
- this.length = 0;
- this.pipes = null;
- this.pipesCount = 0;
- this.flowing = null;
- this.ended = false;
- this.endEmitted = false;
- this.reading = false;
-
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
-
- // whenever we return null, then we set a flag to say
- // that we're awaiting a 'readable' event emission.
- this.needReadable = false;
- this.emittedReadable = false;
- this.readableListening = false;
- this.resumeScheduled = false;
-
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
-
- // when piping, we only care about 'readable' events that happen
- // after read()ing all the bytes and not getting any pushback.
- this.ranOut = false;
-
- // the number of writers that are awaiting a drain event in .pipe()s
- this.awaitDrain = 0;
-
- // if true, a maybeReadMore has been scheduled
- this.readingMore = false;
-
- this.decoder = null;
- this.encoding = null;
- if (options.encoding) {
- if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this.decoder = new StringDecoder(options.encoding);
- this.encoding = options.encoding;
- }
- }
-
- var Duplex;
- function Readable(options) {
- Duplex = Duplex || require('./_stream_duplex');
-
- if (!(this instanceof Readable)) return new Readable(options);
-
- this._readableState = new ReadableState(options, this);
-
- // legacy
- this.readable = true;
-
- if (options && typeof options.read === 'function') this._read = options.read;
-
- Stream.call(this);
- }
-
- // Manually shove something into the read() buffer.
- // This returns true if the highWaterMark has not been hit yet,
- // similar to how Writable.write() returns true if you should
- // write() some more.
- Readable.prototype.push = function (chunk, encoding) {
- var state = this._readableState;
-
- if (!state.objectMode && typeof chunk === 'string') {
- encoding = encoding || state.defaultEncoding;
- if (encoding !== state.encoding) {
- chunk = bufferShim.from(chunk, encoding);
- encoding = '';
- }
- }
-
- return readableAddChunk(this, state, chunk, encoding, false);
- };
-
- // Unshift should *always* be something directly out of read()
- Readable.prototype.unshift = function (chunk) {
- var state = this._readableState;
- return readableAddChunk(this, state, chunk, '', true);
- };
-
- Readable.prototype.isPaused = function () {
- return this._readableState.flowing === false;
- };
-
- function readableAddChunk(stream, state, chunk, encoding, addToFront) {
- var er = chunkInvalid(state, chunk);
- if (er) {
- stream.emit('error', er);
- } else if (chunk === null) {
- state.reading = false;
- onEofChunk(stream, state);
- } else if (state.objectMode || chunk && chunk.length > 0) {
- if (state.ended && !addToFront) {
- var e = new Error('stream.push() after EOF');
- stream.emit('error', e);
- } else if (state.endEmitted && addToFront) {
- var _e = new Error('stream.unshift() after end event');
- stream.emit('error', _e);
- } else {
- var skipAdd;
- if (state.decoder && !addToFront && !encoding) {
- chunk = state.decoder.write(chunk);
- skipAdd = !state.objectMode && chunk.length === 0;
- }
-
- if (!addToFront) state.reading = false;
-
- // Don't add to the buffer if we've decoded to an empty string chunk and
- // we're not in object mode
- if (!skipAdd) {
- // if we want the data now, just emit it.
- if (state.flowing && state.length === 0 && !state.sync) {
- stream.emit('data', chunk);
- stream.read(0);
- } else {
- // update the buffer info.
- state.length += state.objectMode ? 1 : chunk.length;
- if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
-
- if (state.needReadable) emitReadable(stream);
- }
- }
-
- maybeReadMore(stream, state);
- }
- } else if (!addToFront) {
- state.reading = false;
- }
-
- return needMoreData(state);
- }
-
- // if it's past the high water mark, we can push in some more.
- // Also, if we have no data yet, we can stand some
- // more bytes. This is to work around cases where hwm=0,
- // such as the repl. Also, if the push() triggered a
- // readable event, and the user called read(largeNumber) such that
- // needReadable was set, then we ought to push more, so that another
- // 'readable' event will be triggered.
- function needMoreData(state) {
- return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
- }
-
- // backwards compatibility.
- Readable.prototype.setEncoding = function (enc) {
- if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this._readableState.decoder = new StringDecoder(enc);
- this._readableState.encoding = enc;
- return this;
- };
-
- // Don't raise the hwm > 8MB
- var MAX_HWM = 0x800000;
- function computeNewHighWaterMark(n) {
- if (n >= MAX_HWM) {
- n = MAX_HWM;
- } else {
- // Get the next highest power of 2 to prevent increasing hwm excessively in
- // tiny amounts
- n--;
- n |= n >>> 1;
- n |= n >>> 2;
- n |= n >>> 4;
- n |= n >>> 8;
- n |= n >>> 16;
- n++;
- }
- return n;
- }
-
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function howMuchToRead(n, state) {
- if (n <= 0 || state.length === 0 && state.ended) return 0;
- if (state.objectMode) return 1;
- if (n !== n) {
- // Only flow one buffer at a time
- if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
- }
- // If we're asking for more than the current hwm, then raise the hwm.
- if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
- if (n <= state.length) return n;
- // Don't have enough
- if (!state.ended) {
- state.needReadable = true;
- return 0;
- }
- return state.length;
- }
-
- // you can override either this method, or the async _read(n) below.
- Readable.prototype.read = function (n) {
- debug('read', n);
- n = parseInt(n, 10);
- var state = this._readableState;
- var nOrig = n;
-
- if (n !== 0) state.emittedReadable = false;
-
- // if we're doing read(0) to trigger a readable event, but we
- // already have a bunch of data in the buffer, then just trigger
- // the 'readable' event and move on.
- if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
- debug('read: emitReadable', state.length, state.ended);
- if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
- return null;
- }
-
- n = howMuchToRead(n, state);
-
- // if we've ended, and we're now clear, then finish it up.
- if (n === 0 && state.ended) {
- if (state.length === 0) endReadable(this);
- return null;
- }
-
- // All the actual chunk generation logic needs to be
- // *below* the call to _read. The reason is that in certain
- // synthetic stream cases, such as passthrough streams, _read
- // may be a completely synchronous operation which may change
- // the state of the read buffer, providing enough data when
- // before there was *not* enough.
- //
- // So, the steps are:
- // 1. Figure out what the state of things will be after we do
- // a read from the buffer.
- //
- // 2. If that resulting state will trigger a _read, then call _read.
- // Note that this may be asynchronous, or synchronous. Yes, it is
- // deeply ugly to write APIs this way, but that still doesn't mean
- // that the Readable class should behave improperly, as streams are
- // designed to be sync/async agnostic.
- // Take note if the _read call is sync or async (ie, if the read call
- // has returned yet), so that we know whether or not it's safe to emit
- // 'readable' etc.
- //
- // 3. Actually pull the requested chunks out of the buffer and return.
-
- // if we need a readable event, then we need to do some reading.
- var doRead = state.needReadable;
- debug('need readable', doRead);
-
- // if we currently have less than the highWaterMark, then also read some
- if (state.length === 0 || state.length - n < state.highWaterMark) {
- doRead = true;
- debug('length less than watermark', doRead);
- }
-
- // however, if we've ended, then there's no point, and if we're already
- // reading, then it's unnecessary.
- if (state.ended || state.reading) {
- doRead = false;
- debug('reading or ended', doRead);
- } else if (doRead) {
- debug('do read');
- state.reading = true;
- state.sync = true;
- // if the length is currently zero, then we *need* a readable event.
- if (state.length === 0) state.needReadable = true;
- // call internal read method
- this._read(state.highWaterMark);
- state.sync = false;
- // If _read pushed data synchronously, then `reading` will be false,
- // and we need to re-evaluate how much data we can return to the user.
- if (!state.reading) n = howMuchToRead(nOrig, state);
- }
-
- var ret;
- if (n > 0) ret = fromList(n, state);else ret = null;
-
- if (ret === null) {
- state.needReadable = true;
- n = 0;
- } else {
- state.length -= n;
- }
-
- if (state.length === 0) {
- // If we have nothing in the buffer, then we want to know
- // as soon as we *do* get something into the buffer.
- if (!state.ended) state.needReadable = true;
-
- // If we tried to read() past the EOF, then emit end on the next tick.
- if (nOrig !== n && state.ended) endReadable(this);
- }
-
- if (ret !== null) this.emit('data', ret);
-
- return ret;
- };
-
- function chunkInvalid(state, chunk) {
- var er = null;
- if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- return er;
- }
-
- function onEofChunk(stream, state) {
- if (state.ended) return;
- if (state.decoder) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) {
- state.buffer.push(chunk);
- state.length += state.objectMode ? 1 : chunk.length;
- }
- }
- state.ended = true;
-
- // emit 'readable' now to make sure it gets picked up.
- emitReadable(stream);
- }
-
- // Don't emit readable right away in sync mode, because this can trigger
- // another read() call => stack overflow. This way, it might trigger
- // a nextTick recursion warning, but that's not so bad.
- function emitReadable(stream) {
- var state = stream._readableState;
- state.needReadable = false;
- if (!state.emittedReadable) {
- debug('emitReadable', state.flowing);
- state.emittedReadable = true;
- if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
- }
- }
-
- function emitReadable_(stream) {
- debug('emit readable');
- stream.emit('readable');
- flow(stream);
- }
-
- // at this point, the user has presumably seen the 'readable' event,
- // and called read() to consume some data. that may have triggered
- // in turn another _read(n) call, in which case reading = true if
- // it's in progress.
- // However, if we're not ended, or reading, and the length < hwm,
- // then go ahead and try to read some more preemptively.
- function maybeReadMore(stream, state) {
- if (!state.readingMore) {
- state.readingMore = true;
- processNextTick(maybeReadMore_, stream, state);
- }
- }
-
- function maybeReadMore_(stream, state) {
- var len = state.length;
- while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
- debug('maybeReadMore read 0');
- stream.read(0);
- if (len === state.length)
- // didn't get any data, stop spinning.
- break;else len = state.length;
- }
- state.readingMore = false;
- }
-
- // abstract method. to be overridden in specific implementation classes.
- // call cb(er, data) where data is <= n in length.
- // for virtual (non-string, non-buffer) streams, "length" is somewhat
- // arbitrary, and perhaps not very meaningful.
- Readable.prototype._read = function (n) {
- this.emit('error', new Error('not implemented'));
- };
-
- Readable.prototype.pipe = function (dest, pipeOpts) {
- var src = this;
- var state = this._readableState;
-
- switch (state.pipesCount) {
- case 0:
- state.pipes = dest;
- break;
- case 1:
- state.pipes = [state.pipes, dest];
- break;
- default:
- state.pipes.push(dest);
- break;
- }
- state.pipesCount += 1;
- debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
-
- var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
-
- var endFn = doEnd ? onend : cleanup;
- if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
-
- dest.on('unpipe', onunpipe);
- function onunpipe(readable) {
- debug('onunpipe');
- if (readable === src) {
- cleanup();
- }
- }
-
- function onend() {
- debug('onend');
- dest.end();
- }
-
- // when the dest drains, it reduces the awaitDrain counter
- // on the source. This would be more elegant with a .once()
- // handler in flow(), but adding and removing repeatedly is
- // too slow.
- var ondrain = pipeOnDrain(src);
- dest.on('drain', ondrain);
-
- var cleanedUp = false;
- function cleanup() {
- debug('cleanup');
- // cleanup event handlers once the pipe is broken
- dest.removeListener('close', onclose);
- dest.removeListener('finish', onfinish);
- dest.removeListener('drain', ondrain);
- dest.removeListener('error', onerror);
- dest.removeListener('unpipe', onunpipe);
- src.removeListener('end', onend);
- src.removeListener('end', cleanup);
- src.removeListener('data', ondata);
-
- cleanedUp = true;
-
- // if the reader is waiting for a drain event from this
- // specific writer, then it would cause it to never start
- // flowing again.
- // So, if this is awaiting a drain, then we just call it now.
- // If we don't know, then assume that we are waiting for one.
- if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
- }
-
- // If the user pushes more data while we're writing to dest then we'll end up
- // in ondata again. However, we only want to increase awaitDrain once because
- // dest will only emit one 'drain' event for the multiple writes.
- // => Introduce a guard on increasing awaitDrain.
- var increasedAwaitDrain = false;
- src.on('data', ondata);
- function ondata(chunk) {
- debug('ondata');
- increasedAwaitDrain = false;
- var ret = dest.write(chunk);
- if (false === ret && !increasedAwaitDrain) {
- // If the user unpiped during `dest.write()`, it is possible
- // to get stuck in a permanently paused state if that write
- // also returned false.
- // => Check whether `dest` is still a piping destination.
- if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
- debug('false write response, pause', src._readableState.awaitDrain);
- src._readableState.awaitDrain++;
- increasedAwaitDrain = true;
- }
- src.pause();
- }
- }
-
- // if the dest has an error, then stop piping into it.
- // however, don't suppress the throwing behavior for this.
- function onerror(er) {
- debug('onerror', er);
- unpipe();
- dest.removeListener('error', onerror);
- if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
- }
-
- // Make sure our error handler is attached before userland ones.
- prependListener(dest, 'error', onerror);
-
- // Both close and finish should trigger unpipe, but only once.
- function onclose() {
- dest.removeListener('finish', onfinish);
- unpipe();
- }
- dest.once('close', onclose);
- function onfinish() {
- debug('onfinish');
- dest.removeListener('close', onclose);
- unpipe();
- }
- dest.once('finish', onfinish);
-
- function unpipe() {
- debug('unpipe');
- src.unpipe(dest);
- }
-
- // tell the dest that it's being piped to
- dest.emit('pipe', src);
-
- // start the flow if it hasn't been started already.
- if (!state.flowing) {
- debug('pipe resume');
- src.resume();
- }
-
- return dest;
- };
-
- function pipeOnDrain(src) {
- return function () {
- var state = src._readableState;
- debug('pipeOnDrain', state.awaitDrain);
- if (state.awaitDrain) state.awaitDrain--;
- if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
- state.flowing = true;
- flow(src);
- }
- };
- }
-
- Readable.prototype.unpipe = function (dest) {
- var state = this._readableState;
-
- // if we're not piping anywhere, then do nothing.
- if (state.pipesCount === 0) return this;
-
- // just one destination. most common case.
- if (state.pipesCount === 1) {
- // passed in one, but it's not the right one.
- if (dest && dest !== state.pipes) return this;
-
- if (!dest) dest = state.pipes;
-
- // got a match.
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
- if (dest) dest.emit('unpipe', this);
- return this;
- }
-
- // slow case. multiple pipe destinations.
-
- if (!dest) {
- // remove all.
- var dests = state.pipes;
- var len = state.pipesCount;
- state.pipes = null;
- state.pipesCount = 0;
- state.flowing = false;
-
- for (var _i = 0; _i < len; _i++) {
- dests[_i].emit('unpipe', this);
- }return this;
- }
-
- // try to find the right one.
- var i = indexOf(state.pipes, dest);
- if (i === -1) return this;
-
- state.pipes.splice(i, 1);
- state.pipesCount -= 1;
- if (state.pipesCount === 1) state.pipes = state.pipes[0];
-
- dest.emit('unpipe', this);
-
- return this;
- };
-
- // set up data events if they are asked for
- // Ensure readable listeners eventually get something
- Readable.prototype.on = function (ev, fn) {
- var res = Stream.prototype.on.call(this, ev, fn);
-
- if (ev === 'data') {
- // Start flowing on next tick if stream isn't explicitly paused
- if (this._readableState.flowing !== false) this.resume();
- } else if (ev === 'readable') {
- var state = this._readableState;
- if (!state.endEmitted && !state.readableListening) {
- state.readableListening = state.needReadable = true;
- state.emittedReadable = false;
- if (!state.reading) {
- processNextTick(nReadingNextTick, this);
- } else if (state.length) {
- emitReadable(this, state);
- }
- }
- }
-
- return res;
- };
- Readable.prototype.addListener = Readable.prototype.on;
-
- function nReadingNextTick(self) {
- debug('readable nexttick read 0');
- self.read(0);
- }
-
- // pause() and resume() are remnants of the legacy readable stream API
- // If the user uses them, then switch into old mode.
- Readable.prototype.resume = function () {
- var state = this._readableState;
- if (!state.flowing) {
- debug('resume');
- state.flowing = true;
- resume(this, state);
- }
- return this;
- };
-
- function resume(stream, state) {
- if (!state.resumeScheduled) {
- state.resumeScheduled = true;
- processNextTick(resume_, stream, state);
- }
- }
-
- function resume_(stream, state) {
- if (!state.reading) {
- debug('resume read 0');
- stream.read(0);
- }
-
- state.resumeScheduled = false;
- state.awaitDrain = 0;
- stream.emit('resume');
- flow(stream);
- if (state.flowing && !state.reading) stream.read(0);
- }
-
- Readable.prototype.pause = function () {
- debug('call pause flowing=%j', this._readableState.flowing);
- if (false !== this._readableState.flowing) {
- debug('pause');
- this._readableState.flowing = false;
- this.emit('pause');
- }
- return this;
- };
-
- function flow(stream) {
- var state = stream._readableState;
- debug('flow', state.flowing);
- while (state.flowing && stream.read() !== null) {}
- }
-
- // wrap an old-style stream as the async data source.
- // This is *not* part of the readable stream interface.
- // It is an ugly unfortunate mess of history.
- Readable.prototype.wrap = function (stream) {
- var state = this._readableState;
- var paused = false;
-
- var self = this;
- stream.on('end', function () {
- debug('wrapped end');
- if (state.decoder && !state.ended) {
- var chunk = state.decoder.end();
- if (chunk && chunk.length) self.push(chunk);
- }
-
- self.push(null);
- });
-
- stream.on('data', function (chunk) {
- debug('wrapped data');
- if (state.decoder) chunk = state.decoder.write(chunk);
-
- // don't skip over falsy values in objectMode
- if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
-
- var ret = self.push(chunk);
- if (!ret) {
- paused = true;
- stream.pause();
- }
- });
-
- // proxy all the other methods.
- // important when wrapping filters and duplexes.
- for (var i in stream) {
- if (this[i] === undefined && typeof stream[i] === 'function') {
- this[i] = function (method) {
- return function () {
- return stream[method].apply(stream, arguments);
- };
- }(i);
- }
- }
-
- // proxy certain important events.
- var events = ['error', 'close', 'destroy', 'pause', 'resume'];
- forEach(events, function (ev) {
- stream.on(ev, self.emit.bind(self, ev));
- });
-
- // when we try to consume some more bytes, simply unpause the
- // underlying stream.
- self._read = function (n) {
- debug('wrapped _read', n);
- if (paused) {
- paused = false;
- stream.resume();
- }
- };
-
- return self;
- };
-
- // exposed for testing purposes only.
- Readable._fromList = fromList;
-
- // Pluck off n bytes from an array of buffers.
- // Length is the combined lengths of all the buffers in the list.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function fromList(n, state) {
- // nothing buffered
- if (state.length === 0) return null;
-
- var ret;
- if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
- // read it all, truncate the list
- if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
- state.buffer.clear();
- } else {
- // read part of list
- ret = fromListPartial(n, state.buffer, state.decoder);
- }
-
- return ret;
- }
-
- // Extracts only enough buffered data to satisfy the amount requested.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function fromListPartial(n, list, hasStrings) {
- var ret;
- if (n < list.head.data.length) {
- // slice is the same for buffers and strings
- ret = list.head.data.slice(0, n);
- list.head.data = list.head.data.slice(n);
- } else if (n === list.head.data.length) {
- // first chunk is a perfect match
- ret = list.shift();
- } else {
- // result spans more than one buffer
- ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
- }
- return ret;
- }
-
- // Copies a specified amount of characters from the list of buffered data
- // chunks.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function copyFromBufferString(n, list) {
- var p = list.head;
- var c = 1;
- var ret = p.data;
- n -= ret.length;
- while (p = p.next) {
- var str = p.data;
- var nb = n > str.length ? str.length : n;
- if (nb === str.length) ret += str;else ret += str.slice(0, n);
- n -= nb;
- if (n === 0) {
- if (nb === str.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = str.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
- }
-
- // Copies a specified amount of bytes from the list of buffered data chunks.
- // This function is designed to be inlinable, so please take care when making
- // changes to the function body.
- function copyFromBuffer(n, list) {
- var ret = bufferShim.allocUnsafe(n);
- var p = list.head;
- var c = 1;
- p.data.copy(ret);
- n -= p.data.length;
- while (p = p.next) {
- var buf = p.data;
- var nb = n > buf.length ? buf.length : n;
- buf.copy(ret, ret.length - n, 0, nb);
- n -= nb;
- if (n === 0) {
- if (nb === buf.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = buf.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
- }
-
- function endReadable(stream) {
- var state = stream._readableState;
-
- // If we get here before consuming all the bytes, then that is a
- // bug in node. Should never happen.
- if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
-
- if (!state.endEmitted) {
- state.ended = true;
- processNextTick(endReadableNT, state, stream);
- }
- }
-
- function endReadableNT(state, stream) {
- // Check that we didn't get one last unshift.
- if (!state.endEmitted && state.length === 0) {
- state.endEmitted = true;
- stream.readable = false;
- stream.emit('end');
- }
- }
-
- function forEach(xs, f) {
- for (var i = 0, l = xs.length; i < l; i++) {
- f(xs[i], i);
- }
- }
-
- function indexOf(xs, x) {
- for (var i = 0, l = xs.length; i < l; i++) {
- if (xs[i] === x) return i;
- }
- return -1;
- }
- }).call(this,require('_process'))
- },{"./_stream_duplex":24,"./internal/streams/BufferList":29,"_process":22,"buffer":7,"buffer-shims":6,"core-util-is":9,"events":14,"inherits":16,"isarray":18,"process-nextick-args":21,"string_decoder/":44,"util":5}],27:[function(require,module,exports){
- // a transform stream is a readable/writable stream where you do
- // something with the data. Sometimes it's called a "filter",
- // but that's not a great name for it, since that implies a thing where
- // some bits pass through, and others are simply ignored. (That would
- // be a valid example of a transform, of course.)
- //
- // While the output is causally related to the input, it's not a
- // necessarily symmetric or synchronous transformation. For example,
- // a zlib stream might take multiple plain-text writes(), and then
- // emit a single compressed chunk some time in the future.
- //
- // Here's how this works:
- //
- // The Transform stream has all the aspects of the readable and writable
- // stream classes. When you write(chunk), that calls _write(chunk,cb)
- // internally, and returns false if there's a lot of pending writes
- // buffered up. When you call read(), that calls _read(n) until
- // there's enough pending readable data buffered up.
- //
- // In a transform stream, the written data is placed in a buffer. When
- // _read(n) is called, it transforms the queued up data, calling the
- // buffered _write cb's as it consumes chunks. If consuming a single
- // written chunk would result in multiple output chunks, then the first
- // outputted bit calls the readcb, and subsequent chunks just go into
- // the read buffer, and will cause it to emit 'readable' if necessary.
- //
- // This way, back-pressure is actually determined by the reading side,
- // since _read has to be called to start processing a new chunk. However,
- // a pathological inflate type of transform can cause excessive buffering
- // here. For example, imagine a stream where every byte of input is
- // interpreted as an integer from 0-255, and then results in that many
- // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
- // 1kb of data being output. In this case, you could write a very small
- // amount of input, and end up with a very large amount of output. In
- // such a pathological inflating mechanism, there'd be no way to tell
- // the system to stop doing the transform. A single 4MB write could
- // cause the system to run out of memory.
- //
- // However, even in such a pathological case, only a single written chunk
- // would be consumed, and then the rest would wait (un-transformed) until
- // the results of the previous transformed chunk were consumed.
-
- 'use strict';
-
- module.exports = Transform;
-
- var Duplex = require('./_stream_duplex');
-
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
-
- util.inherits(Transform, Duplex);
-
- function TransformState(stream) {
- this.afterTransform = function (er, data) {
- return afterTransform(stream, er, data);
- };
-
- this.needTransform = false;
- this.transforming = false;
- this.writecb = null;
- this.writechunk = null;
- this.writeencoding = null;
- }
-
- function afterTransform(stream, er, data) {
- var ts = stream._transformState;
- ts.transforming = false;
-
- var cb = ts.writecb;
-
- if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
-
- ts.writechunk = null;
- ts.writecb = null;
-
- if (data !== null && data !== undefined) stream.push(data);
-
- cb(er);
-
- var rs = stream._readableState;
- rs.reading = false;
- if (rs.needReadable || rs.length < rs.highWaterMark) {
- stream._read(rs.highWaterMark);
- }
- }
-
- function Transform(options) {
- if (!(this instanceof Transform)) return new Transform(options);
-
- Duplex.call(this, options);
-
- this._transformState = new TransformState(this);
-
- // when the writable side finishes, then flush out anything remaining.
- var stream = this;
-
- // start out asking for a readable event once data is transformed.
- this._readableState.needReadable = true;
-
- // we have implemented the _read method, and done the other things
- // that Readable wants before the first _read call, so unset the
- // sync guard flag.
- this._readableState.sync = false;
-
- if (options) {
- if (typeof options.transform === 'function') this._transform = options.transform;
-
- if (typeof options.flush === 'function') this._flush = options.flush;
- }
-
- this.once('prefinish', function () {
- if (typeof this._flush === 'function') this._flush(function (er) {
- done(stream, er);
- });else done(stream);
- });
- }
-
- Transform.prototype.push = function (chunk, encoding) {
- this._transformState.needTransform = false;
- return Duplex.prototype.push.call(this, chunk, encoding);
- };
-
- // This is the part where you do stuff!
- // override this function in implementation classes.
- // 'chunk' is an input chunk.
- //
- // Call `push(newChunk)` to pass along transformed output
- // to the readable side. You may call 'push' zero or more times.
- //
- // Call `cb(err)` when you are done with this chunk. If you pass
- // an error, then that'll put the hurt on the whole operation. If you
- // never call cb(), then you'll never get another chunk.
- Transform.prototype._transform = function (chunk, encoding, cb) {
- throw new Error('Not implemented');
- };
-
- Transform.prototype._write = function (chunk, encoding, cb) {
- var ts = this._transformState;
- ts.writecb = cb;
- ts.writechunk = chunk;
- ts.writeencoding = encoding;
- if (!ts.transforming) {
- var rs = this._readableState;
- if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
- }
- };
-
- // Doesn't matter what the args are here.
- // _transform does all the work.
- // That we got here means that the readable side wants more data.
- Transform.prototype._read = function (n) {
- var ts = this._transformState;
-
- if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
- ts.transforming = true;
- this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
- } else {
- // mark that we need a transform, so that any data that comes in
- // will get processed, now that we've asked for it.
- ts.needTransform = true;
- }
- };
-
- function done(stream, er) {
- if (er) return stream.emit('error', er);
-
- // if there's nothing in the write buffer, then that means
- // that nothing more will ever be provided
- var ws = stream._writableState;
- var ts = stream._transformState;
-
- if (ws.length) throw new Error('Calling transform done when ws.length != 0');
-
- if (ts.transforming) throw new Error('Calling transform done when still transforming');
-
- return stream.push(null);
- }
- },{"./_stream_duplex":24,"core-util-is":9,"inherits":16}],28:[function(require,module,exports){
- (function (process){
- // A bit simpler than readable streams.
- // Implement an async ._write(chunk, encoding, cb), and it'll handle all
- // the drain event emission and buffering.
-
- 'use strict';
-
- module.exports = Writable;
-
- /*<replacement>*/
- var processNextTick = require('process-nextick-args');
- /*</replacement>*/
-
- /*<replacement>*/
- var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
- /*</replacement>*/
-
- Writable.WritableState = WritableState;
-
- /*<replacement>*/
- var util = require('core-util-is');
- util.inherits = require('inherits');
- /*</replacement>*/
-
- /*<replacement>*/
- var internalUtil = {
- deprecate: require('util-deprecate')
- };
- /*</replacement>*/
-
- /*<replacement>*/
- var Stream;
- (function () {
- try {
- Stream = require('st' + 'ream');
- } catch (_) {} finally {
- if (!Stream) Stream = require('events').EventEmitter;
- }
- })();
- /*</replacement>*/
-
- var Buffer = require('buffer').Buffer;
- /*<replacement>*/
- var bufferShim = require('buffer-shims');
- /*</replacement>*/
-
- util.inherits(Writable, Stream);
-
- function nop() {}
-
- function WriteReq(chunk, encoding, cb) {
- this.chunk = chunk;
- this.encoding = encoding;
- this.callback = cb;
- this.next = null;
- }
-
- var Duplex;
- function WritableState(options, stream) {
- Duplex = Duplex || require('./_stream_duplex');
-
- options = options || {};
-
- // object stream flag to indicate whether or not this stream
- // contains buffers or objects.
- this.objectMode = !!options.objectMode;
-
- if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
-
- // the point at which write() starts returning false
- // Note: 0 is a valid value, means that we always return false if
- // the entire buffer is not flushed immediately on write()
- var hwm = options.highWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
- this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
-
- // cast to ints.
- this.highWaterMark = ~ ~this.highWaterMark;
-
- this.needDrain = false;
- // at the start of calling end()
- this.ending = false;
- // when end() has been called, and returned
- this.ended = false;
- // when 'finish' is emitted
- this.finished = false;
-
- // should we decode strings into buffers before passing to _write?
- // this is here so that some node-core streams can optimize string
- // handling at a lower level.
- var noDecode = options.decodeStrings === false;
- this.decodeStrings = !noDecode;
-
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
-
- // not an actual buffer we keep track of, but a measurement
- // of how much we're waiting to get pushed to some underlying
- // socket or file.
- this.length = 0;
-
- // a flag to see when we're in the middle of a write.
- this.writing = false;
-
- // when true all writes will be buffered until .uncork() call
- this.corked = 0;
-
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
-
- // a flag to know if we're processing previously buffered items, which
- // may call the _write() callback in the same tick, so that we don't
- // end up in an overlapped onwrite situation.
- this.bufferProcessing = false;
-
- // the callback that's passed to _write(chunk,cb)
- this.onwrite = function (er) {
- onwrite(stream, er);
- };
-
- // the callback that the user supplies to write(chunk,encoding,cb)
- this.writecb = null;
-
- // the amount that is being written when _write is called.
- this.writelen = 0;
-
- this.bufferedRequest = null;
- this.lastBufferedRequest = null;
-
- // number of pending user-supplied write callbacks
- // this must be 0 before 'finish' can be emitted
- this.pendingcb = 0;
-
- // emit prefinish if the only thing we're waiting for is _write cbs
- // This is relevant for synchronous Transform streams
- this.prefinished = false;
-
- // True if the error was already emitted and should not be thrown again
- this.errorEmitted = false;
-
- // count buffered requests
- this.bufferedRequestCount = 0;
-
- // allocate the first CorkedRequest, there is always
- // one allocated and free to use, and we maintain at most two
- this.corkedRequestsFree = new CorkedRequest(this);
- }
-
- WritableState.prototype.getBuffer = function writableStateGetBuffer() {
- var current = this.bufferedRequest;
- var out = [];
- while (current) {
- out.push(current);
- current = current.next;
- }
- return out;
- };
-
- (function () {
- try {
- Object.defineProperty(WritableState.prototype, 'buffer', {
- get: internalUtil.deprecate(function () {
- return this.getBuffer();
- }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
- });
- } catch (_) {}
- })();
-
- var Duplex;
- function Writable(options) {
- Duplex = Duplex || require('./_stream_duplex');
-
- // Writable ctor is applied to Duplexes, though they're not
- // instanceof Writable, they're instanceof Readable.
- if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);
-
- this._writableState = new WritableState(options, this);
-
- // legacy.
- this.writable = true;
-
- if (options) {
- if (typeof options.write === 'function') this._write = options.write;
-
- if (typeof options.writev === 'function') this._writev = options.writev;
- }
-
- Stream.call(this);
- }
-
- // Otherwise people can pipe Writable streams, which is just wrong.
- Writable.prototype.pipe = function () {
- this.emit('error', new Error('Cannot pipe, not readable'));
- };
-
- function writeAfterEnd(stream, cb) {
- var er = new Error('write after end');
- // TODO: defer error events consistently everywhere, not just the cb
- stream.emit('error', er);
- processNextTick(cb, er);
- }
-
- // If we get something that is not a buffer, string, null, or undefined,
- // and we're not in objectMode, then that's an error.
- // Otherwise stream chunks are all considered to be of length=1, and the
- // watermarks determine how many objects to keep in the buffer, rather than
- // how many bytes or characters.
- function validChunk(stream, state, chunk, cb) {
- var valid = true;
- var er = false;
- // Always throw error if a null is written
- // if we are not in object mode then throw
- // if it is not a buffer, string, or undefined.
- if (chunk === null) {
- er = new TypeError('May not write null values to stream');
- } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- if (er) {
- stream.emit('error', er);
- processNextTick(cb, er);
- valid = false;
- }
- return valid;
- }
-
- Writable.prototype.write = function (chunk, encoding, cb) {
- var state = this._writableState;
- var ret = false;
-
- if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
- }
-
- if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
-
- if (typeof cb !== 'function') cb = nop;
-
- if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {
- state.pendingcb++;
- ret = writeOrBuffer(this, state, chunk, encoding, cb);
- }
-
- return ret;
- };
-
- Writable.prototype.cork = function () {
- var state = this._writableState;
-
- state.corked++;
- };
-
- Writable.prototype.uncork = function () {
- var state = this._writableState;
-
- if (state.corked) {
- state.corked--;
-
- if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
- }
- };
-
- Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
- // node::ParseEncoding() requires lower case.
- if (typeof encoding === 'string') encoding = encoding.toLowerCase();
- if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
- this._writableState.defaultEncoding = encoding;
- return this;
- };
-
- function decodeChunk(state, chunk, encoding) {
- if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
- chunk = bufferShim.from(chunk, encoding);
- }
- return chunk;
- }
-
- // if we're already writing something, then just put this
- // in the queue, and wait our turn. Otherwise, call _write
- // If we return false, then we need a drain event, so set that flag.
- function writeOrBuffer(stream, state, chunk, encoding, cb) {
- chunk = decodeChunk(state, chunk, encoding);
-
- if (Buffer.isBuffer(chunk)) encoding = 'buffer';
- var len = state.objectMode ? 1 : chunk.length;
-
- state.length += len;
-
- var ret = state.length < state.highWaterMark;
- // we must ensure that previous needDrain will not be reset to false.
- if (!ret) state.needDrain = true;
-
- if (state.writing || state.corked) {
- var last = state.lastBufferedRequest;
- state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
- if (last) {
- last.next = state.lastBufferedRequest;
- } else {
- state.bufferedRequest = state.lastBufferedRequest;
- }
- state.bufferedRequestCount += 1;
- } else {
- doWrite(stream, state, false, len, chunk, encoding, cb);
- }
-
- return ret;
- }
-
- function doWrite(stream, state, writev, len, chunk, encoding, cb) {
- state.writelen = len;
- state.writecb = cb;
- state.writing = true;
- state.sync = true;
- if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
- state.sync = false;
- }
-
- function onwriteError(stream, state, sync, er, cb) {
- --state.pendingcb;
- if (sync) processNextTick(cb, er);else cb(er);
-
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
- }
-
- function onwriteStateUpdate(state) {
- state.writing = false;
- state.writecb = null;
- state.length -= state.writelen;
- state.writelen = 0;
- }
-
- function onwrite(stream, er) {
- var state = stream._writableState;
- var sync = state.sync;
- var cb = state.writecb;
-
- onwriteStateUpdate(state);
-
- if (er) onwriteError(stream, state, sync, er, cb);else {
- // Check if we're actually ready to finish, but don't emit yet
- var finished = needFinish(state);
-
- if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
- clearBuffer(stream, state);
- }
-
- if (sync) {
- /*<replacement>*/
- asyncWrite(afterWrite, stream, state, finished, cb);
- /*</replacement>*/
- } else {
- afterWrite(stream, state, finished, cb);
- }
- }
- }
-
- function afterWrite(stream, state, finished, cb) {
- if (!finished) onwriteDrain(stream, state);
- state.pendingcb--;
- cb();
- finishMaybe(stream, state);
- }
-
- // Must force callback to be called on nextTick, so that we don't
- // emit 'drain' before the write() consumer gets the 'false' return
- // value, and has a chance to attach a 'drain' listener.
- function onwriteDrain(stream, state) {
- if (state.length === 0 && state.needDrain) {
- state.needDrain = false;
- stream.emit('drain');
- }
- }
-
- // if there's something in the buffer waiting, then process it
- function clearBuffer(stream, state) {
- state.bufferProcessing = true;
- var entry = state.bufferedRequest;
-
- if (stream._writev && entry && entry.next) {
- // Fast case, write everything using _writev()
- var l = state.bufferedRequestCount;
- var buffer = new Array(l);
- var holder = state.corkedRequestsFree;
- holder.entry = entry;
-
- var count = 0;
- while (entry) {
- buffer[count] = entry;
- entry = entry.next;
- count += 1;
- }
-
- doWrite(stream, state, true, state.length, buffer, '', holder.finish);
-
- // doWrite is almost always async, defer these to save a bit of time
- // as the hot path ends with doWrite
- state.pendingcb++;
- state.lastBufferedRequest = null;
- if (holder.next) {
- state.corkedRequestsFree = holder.next;
- holder.next = null;
- } else {
- state.corkedRequestsFree = new CorkedRequest(state);
- }
- } else {
- // Slow case, write chunks one-by-one
- while (entry) {
- var chunk = entry.chunk;
- var encoding = entry.encoding;
- var cb = entry.callback;
- var len = state.objectMode ? 1 : chunk.length;
-
- doWrite(stream, state, false, len, chunk, encoding, cb);
- entry = entry.next;
- // if we didn't call the onwrite immediately, then
- // it means that we need to wait until it does.
- // also, that means that the chunk and cb are currently
- // being processed, so move the buffer counter past them.
- if (state.writing) {
- break;
- }
- }
-
- if (entry === null) state.lastBufferedRequest = null;
- }
-
- state.bufferedRequestCount = 0;
- state.bufferedRequest = entry;
- state.bufferProcessing = false;
- }
-
- Writable.prototype._write = function (chunk, encoding, cb) {
- cb(new Error('not implemented'));
- };
-
- Writable.prototype._writev = null;
-
- Writable.prototype.end = function (chunk, encoding, cb) {
- var state = this._writableState;
-
- if (typeof chunk === 'function') {
- cb = chunk;
- chunk = null;
- encoding = null;
- } else if (typeof encoding === 'function') {
- cb = encoding;
- encoding = null;
- }
-
- if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
-
- // .end() fully uncorks
- if (state.corked) {
- state.corked = 1;
- this.uncork();
- }
-
- // ignore unnecessary end() calls.
- if (!state.ending && !state.finished) endWritable(this, state, cb);
- };
-
- function needFinish(state) {
- return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
- }
-
- function prefinish(stream, state) {
- if (!state.prefinished) {
- state.prefinished = true;
- stream.emit('prefinish');
- }
- }
-
- function finishMaybe(stream, state) {
- var need = needFinish(state);
- if (need) {
- if (state.pendingcb === 0) {
- prefinish(stream, state);
- state.finished = true;
- stream.emit('finish');
- } else {
- prefinish(stream, state);
- }
- }
- return need;
- }
-
- function endWritable(stream, state, cb) {
- state.ending = true;
- finishMaybe(stream, state);
- if (cb) {
- if (state.finished) processNextTick(cb);else stream.once('finish', cb);
- }
- state.ended = true;
- stream.writable = false;
- }
-
- // It seems a linked list but it is not
- // there will be only 2 of these for each stream
- function CorkedRequest(state) {
- var _this = this;
-
- this.next = null;
- this.entry = null;
-
- this.finish = function (err) {
- var entry = _this.entry;
- _this.entry = null;
- while (entry) {
- var cb = entry.callback;
- state.pendingcb--;
- cb(err);
- entry = entry.next;
- }
- if (state.corkedRequestsFree) {
- state.corkedRequestsFree.next = _this;
- } else {
- state.corkedRequestsFree = _this;
- }
- };
- }
- }).call(this,require('_process'))
- },{"./_stream_duplex":24,"_process":22,"buffer":7,"buffer-shims":6,"core-util-is":9,"events":14,"inherits":16,"process-nextick-args":21,"util-deprecate":45}],29:[function(require,module,exports){
- 'use strict';
-
- var Buffer = require('buffer').Buffer;
- /*<replacement>*/
- var bufferShim = require('buffer-shims');
- /*</replacement>*/
-
- module.exports = BufferList;
-
- function BufferList() {
- this.head = null;
- this.tail = null;
- this.length = 0;
- }
-
- BufferList.prototype.push = function (v) {
- var entry = { data: v, next: null };
- if (this.length > 0) this.tail.next = entry;else this.head = entry;
- this.tail = entry;
- ++this.length;
- };
-
- BufferList.prototype.unshift = function (v) {
- var entry = { data: v, next: this.head };
- if (this.length === 0) this.tail = entry;
- this.head = entry;
- ++this.length;
- };
-
- BufferList.prototype.shift = function () {
- if (this.length === 0) return;
- var ret = this.head.data;
- if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
- --this.length;
- return ret;
- };
-
- BufferList.prototype.clear = function () {
- this.head = this.tail = null;
- this.length = 0;
- };
-
- BufferList.prototype.join = function (s) {
- if (this.length === 0) return '';
- var p = this.head;
- var ret = '' + p.data;
- while (p = p.next) {
- ret += s + p.data;
- }return ret;
- };
-
- BufferList.prototype.concat = function (n) {
- if (this.length === 0) return bufferShim.alloc(0);
- if (this.length === 1) return this.head.data;
- var ret = bufferShim.allocUnsafe(n >>> 0);
- var p = this.head;
- var i = 0;
- while (p) {
- p.data.copy(ret, i);
- i += p.data.length;
- p = p.next;
- }
- return ret;
- };
- },{"buffer":7,"buffer-shims":6}],30:[function(require,module,exports){
- module.exports = require("./lib/_stream_passthrough.js")
-
- },{"./lib/_stream_passthrough.js":25}],31:[function(require,module,exports){
- (function (process){
- var Stream = (function (){
- try {
- return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
- } catch(_){}
- }());
- exports = module.exports = require('./lib/_stream_readable.js');
- exports.Stream = Stream || exports;
- exports.Readable = exports;
- exports.Writable = require('./lib/_stream_writable.js');
- exports.Duplex = require('./lib/_stream_duplex.js');
- exports.Transform = require('./lib/_stream_transform.js');
- exports.PassThrough = require('./lib/_stream_passthrough.js');
-
- if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {
- module.exports = Stream;
- }
-
- }).call(this,require('_process'))
- },{"./lib/_stream_duplex.js":24,"./lib/_stream_passthrough.js":25,"./lib/_stream_readable.js":26,"./lib/_stream_transform.js":27,"./lib/_stream_writable.js":28,"_process":22}],32:[function(require,module,exports){
- module.exports = require("./lib/_stream_transform.js")
-
- },{"./lib/_stream_transform.js":27}],33:[function(require,module,exports){
- module.exports = require("./lib/_stream_writable.js")
-
- },{"./lib/_stream_writable.js":28}],34:[function(require,module,exports){
- (function (Buffer){
- /*
- CryptoJS v3.1.2
- code.google.com/p/crypto-js
- (c) 2009-2013 by Jeff Mott. All rights reserved.
- code.google.com/p/crypto-js/wiki/License
- */
- /** @preserve
- (c) 2012 by Cédric Mesnil. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
-
- - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
- // constants table
- var zl = [
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
- 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
- 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
- 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
- 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
- ]
-
- var zr = [
- 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
- 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
- 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
- 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
- 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
- ]
-
- var sl = [
- 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
- 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
- 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
- 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
- 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
- ]
-
- var sr = [
- 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
- 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
- 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
- 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
- 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
- ]
-
- var hl = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]
- var hr = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]
-
- function bytesToWords (bytes) {
- var words = []
- for (var i = 0, b = 0; i < bytes.length; i++, b += 8) {
- words[b >>> 5] |= bytes[i] << (24 - b % 32)
- }
- return words
- }
-
- function wordsToBytes (words) {
- var bytes = []
- for (var b = 0; b < words.length * 32; b += 8) {
- bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF)
- }
- return bytes
- }
-
- function processBlock (H, M, offset) {
- // swap endian
- for (var i = 0; i < 16; i++) {
- var offset_i = offset + i
- var M_offset_i = M[offset_i]
-
- // Swap
- M[offset_i] = (
- (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
- (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
- )
- }
-
- // Working variables
- var al, bl, cl, dl, el
- var ar, br, cr, dr, er
-
- ar = al = H[0]
- br = bl = H[1]
- cr = cl = H[2]
- dr = dl = H[3]
- er = el = H[4]
-
- // computation
- var t
- for (i = 0; i < 80; i += 1) {
- t = (al + M[offset + zl[i]]) | 0
- if (i < 16) {
- t += f1(bl, cl, dl) + hl[0]
- } else if (i < 32) {
- t += f2(bl, cl, dl) + hl[1]
- } else if (i < 48) {
- t += f3(bl, cl, dl) + hl[2]
- } else if (i < 64) {
- t += f4(bl, cl, dl) + hl[3]
- } else {// if (i<80) {
- t += f5(bl, cl, dl) + hl[4]
- }
- t = t | 0
- t = rotl(t, sl[i])
- t = (t + el) | 0
- al = el
- el = dl
- dl = rotl(cl, 10)
- cl = bl
- bl = t
-
- t = (ar + M[offset + zr[i]]) | 0
- if (i < 16) {
- t += f5(br, cr, dr) + hr[0]
- } else if (i < 32) {
- t += f4(br, cr, dr) + hr[1]
- } else if (i < 48) {
- t += f3(br, cr, dr) + hr[2]
- } else if (i < 64) {
- t += f2(br, cr, dr) + hr[3]
- } else {// if (i<80) {
- t += f1(br, cr, dr) + hr[4]
- }
-
- t = t | 0
- t = rotl(t, sr[i])
- t = (t + er) | 0
- ar = er
- er = dr
- dr = rotl(cr, 10)
- cr = br
- br = t
- }
-
- // intermediate hash value
- t = (H[1] + cl + dr) | 0
- H[1] = (H[2] + dl + er) | 0
- H[2] = (H[3] + el + ar) | 0
- H[3] = (H[4] + al + br) | 0
- H[4] = (H[0] + bl + cr) | 0
- H[0] = t
- }
-
- function f1 (x, y, z) {
- return ((x) ^ (y) ^ (z))
- }
-
- function f2 (x, y, z) {
- return (((x) & (y)) | ((~x) & (z)))
- }
-
- function f3 (x, y, z) {
- return (((x) | (~(y))) ^ (z))
- }
-
- function f4 (x, y, z) {
- return (((x) & (z)) | ((y) & (~(z))))
- }
-
- function f5 (x, y, z) {
- return ((x) ^ ((y) | (~(z))))
- }
-
- function rotl (x, n) {
- return (x << n) | (x >>> (32 - n))
- }
-
- function ripemd160 (message) {
- var H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
-
- if (typeof message === 'string') {
- message = new Buffer(message, 'utf8')
- }
-
- var m = bytesToWords(message)
-
- var nBitsLeft = message.length * 8
- var nBitsTotal = message.length * 8
-
- // Add padding
- m[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32)
- m[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
- (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
- (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
- )
-
- for (var i = 0; i < m.length; i += 16) {
- processBlock(H, m, i)
- }
-
- // swap endian
- for (i = 0; i < 5; i++) {
- // shortcut
- var H_i = H[i]
-
- // Swap
- H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
- (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00)
- }
-
- var digestbytes = wordsToBytes(H)
- return new Buffer(digestbytes)
- }
-
- module.exports = ripemd160
-
- }).call(this,require("buffer").Buffer)
- },{"buffer":7}],35:[function(require,module,exports){
- (function (Buffer){
- // prototype class for hash functions
- function Hash (blockSize, finalSize) {
- this._block = new Buffer(blockSize)
- this._finalSize = finalSize
- this._blockSize = blockSize
- this._len = 0
- this._s = 0
- }
-
- Hash.prototype.update = function (data, enc) {
- if (typeof data === 'string') {
- enc = enc || 'utf8'
- data = new Buffer(data, enc)
- }
-
- var l = this._len += data.length
- var s = this._s || 0
- var f = 0
- var buffer = this._block
-
- while (s < l) {
- var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize))
- var ch = (t - f)
-
- for (var i = 0; i < ch; i++) {
- buffer[(s % this._blockSize) + i] = data[i + f]
- }
-
- s += ch
- f += ch
-
- if ((s % this._blockSize) === 0) {
- this._update(buffer)
- }
- }
- this._s = s
-
- return this
- }
-
- Hash.prototype.digest = function (enc) {
- // Suppose the length of the message M, in bits, is l
- var l = this._len * 8
-
- // Append the bit 1 to the end of the message
- this._block[this._len % this._blockSize] = 0x80
-
- // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize
- this._block.fill(0, this._len % this._blockSize + 1)
-
- if (l % (this._blockSize * 8) >= this._finalSize * 8) {
- this._update(this._block)
- this._block.fill(0)
- }
-
- // to this append the block which is equal to the number l written in binary
- // TODO: handle case where l is > Math.pow(2, 29)
- this._block.writeInt32BE(l, this._blockSize - 4)
-
- var hash = this._update(this._block) || this._hash()
-
- return enc ? hash.toString(enc) : hash
- }
-
- Hash.prototype._update = function () {
- throw new Error('_update must be implemented by subclass')
- }
-
- module.exports = Hash
-
- }).call(this,require("buffer").Buffer)
- },{"buffer":7}],36:[function(require,module,exports){
- var exports = module.exports = function SHA (algorithm) {
- algorithm = algorithm.toLowerCase()
-
- var Algorithm = exports[algorithm]
- if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
-
- return new Algorithm()
- }
-
- exports.sha = require('./sha')
- exports.sha1 = require('./sha1')
- exports.sha224 = require('./sha224')
- exports.sha256 = require('./sha256')
- exports.sha384 = require('./sha384')
- exports.sha512 = require('./sha512')
-
- },{"./sha":37,"./sha1":38,"./sha224":39,"./sha256":40,"./sha384":41,"./sha512":42}],37:[function(require,module,exports){
- (function (Buffer){
- /*
- * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
- * in FIPS PUB 180-1
- * This source code is derived from sha1.js of the same repository.
- * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
- * operation was added.
- */
-
- var inherits = require('inherits')
- var Hash = require('./hash')
-
- var K = [
- 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
- ]
-
- var W = new Array(80)
-
- function Sha () {
- this.init()
- this._w = W
-
- Hash.call(this, 64, 56)
- }
-
- inherits(Sha, Hash)
-
- Sha.prototype.init = function () {
- this._a = 0x67452301
- this._b = 0xefcdab89
- this._c = 0x98badcfe
- this._d = 0x10325476
- this._e = 0xc3d2e1f0
-
- return this
- }
-
- function rotl5 (num) {
- return (num << 5) | (num >>> 27)
- }
-
- function rotl30 (num) {
- return (num << 30) | (num >>> 2)
- }
-
- function ft (s, b, c, d) {
- if (s === 0) return (b & c) | ((~b) & d)
- if (s === 2) return (b & c) | (b & d) | (c & d)
- return b ^ c ^ d
- }
-
- Sha.prototype._update = function (M) {
- var W = this._w
-
- var a = this._a | 0
- var b = this._b | 0
- var c = this._c | 0
- var d = this._d | 0
- var e = this._e | 0
-
- for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
- for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
-
- for (var j = 0; j < 80; ++j) {
- var s = ~~(j / 20)
- var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
-
- e = d
- d = c
- c = rotl30(b)
- b = a
- a = t
- }
-
- this._a = (a + this._a) | 0
- this._b = (b + this._b) | 0
- this._c = (c + this._c) | 0
- this._d = (d + this._d) | 0
- this._e = (e + this._e) | 0
- }
-
- Sha.prototype._hash = function () {
- var H = new Buffer(20)
-
- H.writeInt32BE(this._a | 0, 0)
- H.writeInt32BE(this._b | 0, 4)
- H.writeInt32BE(this._c | 0, 8)
- H.writeInt32BE(this._d | 0, 12)
- H.writeInt32BE(this._e | 0, 16)
-
- return H
- }
-
- module.exports = Sha
-
- }).call(this,require("buffer").Buffer)
- },{"./hash":35,"buffer":7,"inherits":16}],38:[function(require,module,exports){
- (function (Buffer){
- /*
- * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
- * in FIPS PUB 180-1
- * Version 2.1a Copyright Paul Johnston 2000 - 2002.
- * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
- * Distributed under the BSD License
- * See http://pajhome.org.uk/crypt/md5 for details.
- */
-
- var inherits = require('inherits')
- var Hash = require('./hash')
-
- var K = [
- 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
- ]
-
- var W = new Array(80)
-
- function Sha1 () {
- this.init()
- this._w = W
-
- Hash.call(this, 64, 56)
- }
-
- inherits(Sha1, Hash)
-
- Sha1.prototype.init = function () {
- this._a = 0x67452301
- this._b = 0xefcdab89
- this._c = 0x98badcfe
- this._d = 0x10325476
- this._e = 0xc3d2e1f0
-
- return this
- }
-
- function rotl1 (num) {
- return (num << 1) | (num >>> 31)
- }
-
- function rotl5 (num) {
- return (num << 5) | (num >>> 27)
- }
-
- function rotl30 (num) {
- return (num << 30) | (num >>> 2)
- }
-
- function ft (s, b, c, d) {
- if (s === 0) return (b & c) | ((~b) & d)
- if (s === 2) return (b & c) | (b & d) | (c & d)
- return b ^ c ^ d
- }
-
- Sha1.prototype._update = function (M) {
- var W = this._w
-
- var a = this._a | 0
- var b = this._b | 0
- var c = this._c | 0
- var d = this._d | 0
- var e = this._e | 0
-
- for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
- for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
-
- for (var j = 0; j < 80; ++j) {
- var s = ~~(j / 20)
- var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
-
- e = d
- d = c
- c = rotl30(b)
- b = a
- a = t
- }
-
- this._a = (a + this._a) | 0
- this._b = (b + this._b) | 0
- this._c = (c + this._c) | 0
- this._d = (d + this._d) | 0
- this._e = (e + this._e) | 0
- }
-
- Sha1.prototype._hash = function () {
- var H = new Buffer(20)
-
- H.writeInt32BE(this._a | 0, 0)
- H.writeInt32BE(this._b | 0, 4)
- H.writeInt32BE(this._c | 0, 8)
- H.writeInt32BE(this._d | 0, 12)
- H.writeInt32BE(this._e | 0, 16)
-
- return H
- }
-
- module.exports = Sha1
-
- }).call(this,require("buffer").Buffer)
- },{"./hash":35,"buffer":7,"inherits":16}],39:[function(require,module,exports){
- (function (Buffer){
- /**
- * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
- * in FIPS 180-2
- * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
- * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
- *
- */
-
- var inherits = require('inherits')
- var Sha256 = require('./sha256')
- var Hash = require('./hash')
-
- var W = new Array(64)
-
- function Sha224 () {
- this.init()
-
- this._w = W // new Array(64)
-
- Hash.call(this, 64, 56)
- }
-
- inherits(Sha224, Sha256)
-
- Sha224.prototype.init = function () {
- this._a = 0xc1059ed8
- this._b = 0x367cd507
- this._c = 0x3070dd17
- this._d = 0xf70e5939
- this._e = 0xffc00b31
- this._f = 0x68581511
- this._g = 0x64f98fa7
- this._h = 0xbefa4fa4
-
- return this
- }
-
- Sha224.prototype._hash = function () {
- var H = new Buffer(28)
-
- H.writeInt32BE(this._a, 0)
- H.writeInt32BE(this._b, 4)
- H.writeInt32BE(this._c, 8)
- H.writeInt32BE(this._d, 12)
- H.writeInt32BE(this._e, 16)
- H.writeInt32BE(this._f, 20)
- H.writeInt32BE(this._g, 24)
-
- return H
- }
-
- module.exports = Sha224
-
- }).call(this,require("buffer").Buffer)
- },{"./hash":35,"./sha256":40,"buffer":7,"inherits":16}],40:[function(require,module,exports){
- (function (Buffer){
- /**
- * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
- * in FIPS 180-2
- * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
- * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
- *
- */
-
- var inherits = require('inherits')
- var Hash = require('./hash')
-
- var K = [
- 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
- 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
- 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
- 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
- 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
- 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
- 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
- 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
- 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
- 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
- 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
- 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
- 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
- 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
- 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
- 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
- ]
-
- var W = new Array(64)
-
- function Sha256 () {
- this.init()
-
- this._w = W // new Array(64)
-
- Hash.call(this, 64, 56)
- }
-
- inherits(Sha256, Hash)
-
- Sha256.prototype.init = function () {
- this._a = 0x6a09e667
- this._b = 0xbb67ae85
- this._c = 0x3c6ef372
- this._d = 0xa54ff53a
- this._e = 0x510e527f
- this._f = 0x9b05688c
- this._g = 0x1f83d9ab
- this._h = 0x5be0cd19
-
- return this
- }
-
- function ch (x, y, z) {
- return z ^ (x & (y ^ z))
- }
-
- function maj (x, y, z) {
- return (x & y) | (z & (x | y))
- }
-
- function sigma0 (x) {
- return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
- }
-
- function sigma1 (x) {
- return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
- }
-
- function gamma0 (x) {
- return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
- }
-
- function gamma1 (x) {
- return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
- }
-
- Sha256.prototype._update = function (M) {
- var W = this._w
-
- var a = this._a | 0
- var b = this._b | 0
- var c = this._c | 0
- var d = this._d | 0
- var e = this._e | 0
- var f = this._f | 0
- var g = this._g | 0
- var h = this._h | 0
-
- for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
- for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
-
- for (var j = 0; j < 64; ++j) {
- var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
- var T2 = (sigma0(a) + maj(a, b, c)) | 0
-
- h = g
- g = f
- f = e
- e = (d + T1) | 0
- d = c
- c = b
- b = a
- a = (T1 + T2) | 0
- }
-
- this._a = (a + this._a) | 0
- this._b = (b + this._b) | 0
- this._c = (c + this._c) | 0
- this._d = (d + this._d) | 0
- this._e = (e + this._e) | 0
- this._f = (f + this._f) | 0
- this._g = (g + this._g) | 0
- this._h = (h + this._h) | 0
- }
-
- Sha256.prototype._hash = function () {
- var H = new Buffer(32)
-
- H.writeInt32BE(this._a, 0)
- H.writeInt32BE(this._b, 4)
- H.writeInt32BE(this._c, 8)
- H.writeInt32BE(this._d, 12)
- H.writeInt32BE(this._e, 16)
- H.writeInt32BE(this._f, 20)
- H.writeInt32BE(this._g, 24)
- H.writeInt32BE(this._h, 28)
-
- return H
- }
-
- module.exports = Sha256
-
- }).call(this,require("buffer").Buffer)
- },{"./hash":35,"buffer":7,"inherits":16}],41:[function(require,module,exports){
- (function (Buffer){
- var inherits = require('inherits')
- var SHA512 = require('./sha512')
- var Hash = require('./hash')
-
- var W = new Array(160)
-
- function Sha384 () {
- this.init()
- this._w = W
-
- Hash.call(this, 128, 112)
- }
-
- inherits(Sha384, SHA512)
-
- Sha384.prototype.init = function () {
- this._ah = 0xcbbb9d5d
- this._bh = 0x629a292a
- this._ch = 0x9159015a
- this._dh = 0x152fecd8
- this._eh = 0x67332667
- this._fh = 0x8eb44a87
- this._gh = 0xdb0c2e0d
- this._hh = 0x47b5481d
-
- this._al = 0xc1059ed8
- this._bl = 0x367cd507
- this._cl = 0x3070dd17
- this._dl = 0xf70e5939
- this._el = 0xffc00b31
- this._fl = 0x68581511
- this._gl = 0x64f98fa7
- this._hl = 0xbefa4fa4
-
- return this
- }
-
- Sha384.prototype._hash = function () {
- var H = new Buffer(48)
-
- function writeInt64BE (h, l, offset) {
- H.writeInt32BE(h, offset)
- H.writeInt32BE(l, offset + 4)
- }
-
- writeInt64BE(this._ah, this._al, 0)
- writeInt64BE(this._bh, this._bl, 8)
- writeInt64BE(this._ch, this._cl, 16)
- writeInt64BE(this._dh, this._dl, 24)
- writeInt64BE(this._eh, this._el, 32)
- writeInt64BE(this._fh, this._fl, 40)
-
- return H
- }
-
- module.exports = Sha384
-
- }).call(this,require("buffer").Buffer)
- },{"./hash":35,"./sha512":42,"buffer":7,"inherits":16}],42:[function(require,module,exports){
- (function (Buffer){
- var inherits = require('inherits')
- var Hash = require('./hash')
-
- var K = [
- 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
- 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
- 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
- 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
- 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
- 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
- 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
- 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
- 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
- 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
- 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
- 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
- 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
- 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
- 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
- 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
- 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
- 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
- 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
- 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
- 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
- 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
- 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
- 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
- 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
- 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
- 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
- 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
- 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
- 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
- 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
- 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
- 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
- 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
- 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
- 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
- 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
- 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
- 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
- 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
- ]
-
- var W = new Array(160)
-
- function Sha512 () {
- this.init()
- this._w = W
-
- Hash.call(this, 128, 112)
- }
-
- inherits(Sha512, Hash)
-
- Sha512.prototype.init = function () {
- this._ah = 0x6a09e667
- this._bh = 0xbb67ae85
- this._ch = 0x3c6ef372
- this._dh = 0xa54ff53a
- this._eh = 0x510e527f
- this._fh = 0x9b05688c
- this._gh = 0x1f83d9ab
- this._hh = 0x5be0cd19
-
- this._al = 0xf3bcc908
- this._bl = 0x84caa73b
- this._cl = 0xfe94f82b
- this._dl = 0x5f1d36f1
- this._el = 0xade682d1
- this._fl = 0x2b3e6c1f
- this._gl = 0xfb41bd6b
- this._hl = 0x137e2179
-
- return this
- }
-
- function Ch (x, y, z) {
- return z ^ (x & (y ^ z))
- }
-
- function maj (x, y, z) {
- return (x & y) | (z & (x | y))
- }
-
- function sigma0 (x, xl) {
- return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
- }
-
- function sigma1 (x, xl) {
- return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
- }
-
- function Gamma0 (x, xl) {
- return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
- }
-
- function Gamma0l (x, xl) {
- return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
- }
-
- function Gamma1 (x, xl) {
- return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
- }
-
- function Gamma1l (x, xl) {
- return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
- }
-
- function getCarry (a, b) {
- return (a >>> 0) < (b >>> 0) ? 1 : 0
- }
-
- Sha512.prototype._update = function (M) {
- var W = this._w
-
- var ah = this._ah | 0
- var bh = this._bh | 0
- var ch = this._ch | 0
- var dh = this._dh | 0
- var eh = this._eh | 0
- var fh = this._fh | 0
- var gh = this._gh | 0
- var hh = this._hh | 0
-
- var al = this._al | 0
- var bl = this._bl | 0
- var cl = this._cl | 0
- var dl = this._dl | 0
- var el = this._el | 0
- var fl = this._fl | 0
- var gl = this._gl | 0
- var hl = this._hl | 0
-
- for (var i = 0; i < 32; i += 2) {
- W[i] = M.readInt32BE(i * 4)
- W[i + 1] = M.readInt32BE(i * 4 + 4)
- }
- for (; i < 160; i += 2) {
- var xh = W[i - 15 * 2]
- var xl = W[i - 15 * 2 + 1]
- var gamma0 = Gamma0(xh, xl)
- var gamma0l = Gamma0l(xl, xh)
-
- xh = W[i - 2 * 2]
- xl = W[i - 2 * 2 + 1]
- var gamma1 = Gamma1(xh, xl)
- var gamma1l = Gamma1l(xl, xh)
-
- // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
- var Wi7h = W[i - 7 * 2]
- var Wi7l = W[i - 7 * 2 + 1]
-
- var Wi16h = W[i - 16 * 2]
- var Wi16l = W[i - 16 * 2 + 1]
-
- var Wil = (gamma0l + Wi7l) | 0
- var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
- Wil = (Wil + gamma1l) | 0
- Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
- Wil = (Wil + Wi16l) | 0
- Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
-
- W[i] = Wih
- W[i + 1] = Wil
- }
-
- for (var j = 0; j < 160; j += 2) {
- Wih = W[j]
- Wil = W[j + 1]
-
- var majh = maj(ah, bh, ch)
- var majl = maj(al, bl, cl)
-
- var sigma0h = sigma0(ah, al)
- var sigma0l = sigma0(al, ah)
- var sigma1h = sigma1(eh, el)
- var sigma1l = sigma1(el, eh)
-
- // t1 = h + sigma1 + ch + K[j] + W[j]
- var Kih = K[j]
- var Kil = K[j + 1]
-
- var chh = Ch(eh, fh, gh)
- var chl = Ch(el, fl, gl)
-
- var t1l = (hl + sigma1l) | 0
- var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
- t1l = (t1l + chl) | 0
- t1h = (t1h + chh + getCarry(t1l, chl)) | 0
- t1l = (t1l + Kil) | 0
- t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
- t1l = (t1l + Wil) | 0
- t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
-
- // t2 = sigma0 + maj
- var t2l = (sigma0l + majl) | 0
- var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
-
- hh = gh
- hl = gl
- gh = fh
- gl = fl
- fh = eh
- fl = el
- el = (dl + t1l) | 0
- eh = (dh + t1h + getCarry(el, dl)) | 0
- dh = ch
- dl = cl
- ch = bh
- cl = bl
- bh = ah
- bl = al
- al = (t1l + t2l) | 0
- ah = (t1h + t2h + getCarry(al, t1l)) | 0
- }
-
- this._al = (this._al + al) | 0
- this._bl = (this._bl + bl) | 0
- this._cl = (this._cl + cl) | 0
- this._dl = (this._dl + dl) | 0
- this._el = (this._el + el) | 0
- this._fl = (this._fl + fl) | 0
- this._gl = (this._gl + gl) | 0
- this._hl = (this._hl + hl) | 0
-
- this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
- this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
- this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
- this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
- this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
- this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
- this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
- this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
- }
-
- Sha512.prototype._hash = function () {
- var H = new Buffer(64)
-
- function writeInt64BE (h, l, offset) {
- H.writeInt32BE(h, offset)
- H.writeInt32BE(l, offset + 4)
- }
-
- writeInt64BE(this._ah, this._al, 0)
- writeInt64BE(this._bh, this._bl, 8)
- writeInt64BE(this._ch, this._cl, 16)
- writeInt64BE(this._dh, this._dl, 24)
- writeInt64BE(this._eh, this._el, 32)
- writeInt64BE(this._fh, this._fl, 40)
- writeInt64BE(this._gh, this._gl, 48)
- writeInt64BE(this._hh, this._hl, 56)
-
- return H
- }
-
- module.exports = Sha512
-
- }).call(this,require("buffer").Buffer)
- },{"./hash":35,"buffer":7,"inherits":16}],43:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
-
- module.exports = Stream;
-
- var EE = require('events').EventEmitter;
- var inherits = require('inherits');
-
- inherits(Stream, EE);
- Stream.Readable = require('readable-stream/readable.js');
- Stream.Writable = require('readable-stream/writable.js');
- Stream.Duplex = require('readable-stream/duplex.js');
- Stream.Transform = require('readable-stream/transform.js');
- Stream.PassThrough = require('readable-stream/passthrough.js');
-
- // Backwards-compat with node 0.4.x
- Stream.Stream = Stream;
-
-
-
- // old-style streams. Note that the pipe method (the only relevant
- // part of this class) is overridden in the Readable class.
-
- function Stream() {
- EE.call(this);
- }
-
- Stream.prototype.pipe = function(dest, options) {
- var source = this;
-
- function ondata(chunk) {
- if (dest.writable) {
- if (false === dest.write(chunk) && source.pause) {
- source.pause();
- }
- }
- }
-
- source.on('data', ondata);
-
- function ondrain() {
- if (source.readable && source.resume) {
- source.resume();
- }
- }
-
- dest.on('drain', ondrain);
-
- // If the 'end' option is not supplied, dest.end() will be called when
- // source gets the 'end' or 'close' events. Only dest.end() once.
- if (!dest._isStdio && (!options || options.end !== false)) {
- source.on('end', onend);
- source.on('close', onclose);
- }
-
- var didOnEnd = false;
- function onend() {
- if (didOnEnd) return;
- didOnEnd = true;
-
- dest.end();
- }
-
-
- function onclose() {
- if (didOnEnd) return;
- didOnEnd = true;
-
- if (typeof dest.destroy === 'function') dest.destroy();
- }
-
- // don't leave dangling pipes when there are errors.
- function onerror(er) {
- cleanup();
- if (EE.listenerCount(this, 'error') === 0) {
- throw er; // Unhandled stream error in pipe.
- }
- }
-
- source.on('error', onerror);
- dest.on('error', onerror);
-
- // remove all the event listeners that were added.
- function cleanup() {
- source.removeListener('data', ondata);
- dest.removeListener('drain', ondrain);
-
- source.removeListener('end', onend);
- source.removeListener('close', onclose);
-
- source.removeListener('error', onerror);
- dest.removeListener('error', onerror);
-
- source.removeListener('end', cleanup);
- source.removeListener('close', cleanup);
-
- dest.removeListener('close', cleanup);
- }
-
- source.on('end', cleanup);
- source.on('close', cleanup);
-
- dest.on('close', cleanup);
-
- dest.emit('pipe', source);
-
- // Allow for unix-like usage: A.pipe(B).pipe(C)
- return dest;
- };
-
- },{"events":14,"inherits":16,"readable-stream/duplex.js":23,"readable-stream/passthrough.js":30,"readable-stream/readable.js":31,"readable-stream/transform.js":32,"readable-stream/writable.js":33}],44:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // Permission is hereby granted, free of charge, to any person obtaining a
- // copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to permit
- // persons to whom the Software is furnished to do so, subject to the
- // following conditions:
- //
- // The above copyright notice and this permission notice shall be included
- // in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
- // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
- // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
- // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
- // USE OR OTHER DEALINGS IN THE SOFTWARE.
-
- var Buffer = require('buffer').Buffer;
-
- var isBufferEncoding = Buffer.isEncoding
- || function(encoding) {
- switch (encoding && encoding.toLowerCase()) {
- case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
- default: return false;
- }
- }
-
-
- function assertEncoding(encoding) {
- if (encoding && !isBufferEncoding(encoding)) {
- throw new Error('Unknown encoding: ' + encoding);
- }
- }
-
- // StringDecoder provides an interface for efficiently splitting a series of
- // buffers into a series of JS strings without breaking apart multi-byte
- // characters. CESU-8 is handled as part of the UTF-8 encoding.
- //
- // @TODO Handling all encodings inside a single object makes it very difficult
- // to reason about this code, so it should be split up in the future.
- // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
- // points as used by CESU-8.
- var StringDecoder = exports.StringDecoder = function(encoding) {
- this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
- assertEncoding(encoding);
- switch (this.encoding) {
- case 'utf8':
- // CESU-8 represents each of Surrogate Pair by 3-bytes
- this.surrogateSize = 3;
- break;
- case 'ucs2':
- case 'utf16le':
- // UTF-16 represents each of Surrogate Pair by 2-bytes
- this.surrogateSize = 2;
- this.detectIncompleteChar = utf16DetectIncompleteChar;
- break;
- case 'base64':
- // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
- this.surrogateSize = 3;
- this.detectIncompleteChar = base64DetectIncompleteChar;
- break;
- default:
- this.write = passThroughWrite;
- return;
- }
-
- // Enough space to store all bytes of a single character. UTF-8 needs 4
- // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
- this.charBuffer = new Buffer(6);
- // Number of bytes received for the current incomplete multi-byte character.
- this.charReceived = 0;
- // Number of bytes expected for the current incomplete multi-byte character.
- this.charLength = 0;
- };
-
-
- // write decodes the given buffer and returns it as JS string that is
- // guaranteed to not contain any partial multi-byte characters. Any partial
- // character found at the end of the buffer is buffered up, and will be
- // returned when calling write again with the remaining bytes.
- //
- // Note: Converting a Buffer containing an orphan surrogate to a String
- // currently works, but converting a String to a Buffer (via `new Buffer`, or
- // Buffer#write) will replace incomplete surrogates with the unicode
- // replacement character. See https://codereview.chromium.org/121173009/ .
- StringDecoder.prototype.write = function(buffer) {
- var charStr = '';
- // if our last write ended with an incomplete multibyte character
- while (this.charLength) {
- // determine how many remaining bytes this buffer has to offer for this char
- var available = (buffer.length >= this.charLength - this.charReceived) ?
- this.charLength - this.charReceived :
- buffer.length;
-
- // add the new bytes to the char buffer
- buffer.copy(this.charBuffer, this.charReceived, 0, available);
- this.charReceived += available;
-
- if (this.charReceived < this.charLength) {
- // still not enough chars in this buffer? wait for more ...
- return '';
- }
-
- // remove bytes belonging to the current character from the buffer
- buffer = buffer.slice(available, buffer.length);
-
- // get the character that was split
- charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
-
- // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
- var charCode = charStr.charCodeAt(charStr.length - 1);
- if (charCode >= 0xD800 && charCode <= 0xDBFF) {
- this.charLength += this.surrogateSize;
- charStr = '';
- continue;
- }
- this.charReceived = this.charLength = 0;
-
- // if there are no more bytes in this buffer, just emit our char
- if (buffer.length === 0) {
- return charStr;
- }
- break;
- }
-
- // determine and set charLength / charReceived
- this.detectIncompleteChar(buffer);
-
- var end = buffer.length;
- if (this.charLength) {
- // buffer the incomplete character bytes we got
- buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
- end -= this.charReceived;
- }
-
- charStr += buffer.toString(this.encoding, 0, end);
-
- var end = charStr.length - 1;
- var charCode = charStr.charCodeAt(end);
- // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
- if (charCode >= 0xD800 && charCode <= 0xDBFF) {
- var size = this.surrogateSize;
- this.charLength += size;
- this.charReceived += size;
- this.charBuffer.copy(this.charBuffer, size, 0, size);
- buffer.copy(this.charBuffer, 0, 0, size);
- return charStr.substring(0, end);
- }
-
- // or just emit the charStr
- return charStr;
- };
-
- // detectIncompleteChar determines if there is an incomplete UTF-8 character at
- // the end of the given buffer. If so, it sets this.charLength to the byte
- // length that character, and sets this.charReceived to the number of bytes
- // that are available for this character.
- StringDecoder.prototype.detectIncompleteChar = function(buffer) {
- // determine how many bytes we have to check at the end of this buffer
- var i = (buffer.length >= 3) ? 3 : buffer.length;
-
- // Figure out if one of the last i bytes of our buffer announces an
- // incomplete char.
- for (; i > 0; i--) {
- var c = buffer[buffer.length - i];
-
- // See http://en.wikipedia.org/wiki/UTF-8#Description
-
- // 110XXXXX
- if (i == 1 && c >> 5 == 0x06) {
- this.charLength = 2;
- break;
- }
-
- // 1110XXXX
- if (i <= 2 && c >> 4 == 0x0E) {
- this.charLength = 3;
- break;
- }
-
- // 11110XXX
- if (i <= 3 && c >> 3 == 0x1E) {
- this.charLength = 4;
- break;
- }
- }
- this.charReceived = i;
- };
-
- StringDecoder.prototype.end = function(buffer) {
- var res = '';
- if (buffer && buffer.length)
- res = this.write(buffer);
-
- if (this.charReceived) {
- var cr = this.charReceived;
- var buf = this.charBuffer;
- var enc = this.encoding;
- res += buf.slice(0, cr).toString(enc);
- }
-
- return res;
- };
-
- function passThroughWrite(buffer) {
- return buffer.toString(this.encoding);
- }
-
- function utf16DetectIncompleteChar(buffer) {
- this.charReceived = buffer.length % 2;
- this.charLength = this.charReceived ? 2 : 0;
- }
-
- function base64DetectIncompleteChar(buffer) {
- this.charReceived = buffer.length % 3;
- this.charLength = this.charReceived ? 3 : 0;
- }
-
- },{"buffer":7}],45:[function(require,module,exports){
- (function (global){
-
- /**
- * Module exports.
- */
-
- module.exports = deprecate;
-
- /**
- * Mark that a method should not be used.
- * Returns a modified function which warns once by default.
- *
- * If `localStorage.noDeprecation = true` is set, then it is a no-op.
- *
- * If `localStorage.throwDeprecation = true` is set, then deprecated functions
- * will throw an Error when invoked.
- *
- * If `localStorage.traceDeprecation = true` is set, then deprecated functions
- * will invoke `console.trace()` instead of `console.error()`.
- *
- * @param {Function} fn - the function to deprecate
- * @param {String} msg - the string to print to the console when `fn` is invoked
- * @returns {Function} a new "deprecated" version of `fn`
- * @api public
- */
-
- function deprecate (fn, msg) {
- if (config('noDeprecation')) {
- return fn;
- }
-
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (config('throwDeprecation')) {
- throw new Error(msg);
- } else if (config('traceDeprecation')) {
- console.trace(msg);
- } else {
- console.warn(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
-
- return deprecated;
- }
-
- /**
- * Checks `localStorage` for boolean values for the given `name`.
- *
- * @param {String} name
- * @returns {Boolean}
- * @api private
- */
-
- function config (name) {
- // accessing global.localStorage can trigger a DOMException in sandboxed iframes
- try {
- if (!global.localStorage) return false;
- } catch (_) {
- return false;
- }
- var val = global.localStorage[name];
- if (null == val) return false;
- return String(val).toLowerCase() === 'true';
- }
-
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],46:[function(require,module,exports){
- (function (Buffer){
- var pbkdf2 = require('pbkdf2');
- var createHMAC = require('create-hmac');
- var Promise = require("bluebird");
-
-
- module.exports = {
- encryptLogin: encryptLogin,
- renderPassword: renderPassword,
- createFingerprint: createFingerprint,
- _deriveEncryptedLogin: deriveEncryptedLogin,
- _getPasswordTemplate: getPasswordTemplate,
- _prettyPrint: prettyPrint,
- _string2charCodes: string2charCodes,
- _getCharType: getCharType,
- _getPasswordChar: getPasswordChar,
- _createHmac: createHmac,
- };
-
-
- function encryptLogin(login, masterPassword, options) {
- var _options = options !== undefined ? options : {};
- var iterations = _options.iterations || 8192;
- var keylen = _options.keylen || 32;
-
- return new Promise(function (resolve, reject) {
- if (!login || !masterPassword) {
- reject('login and master password parameters could not be empty');
- }
- pbkdf2.pbkdf2(masterPassword, login, iterations, keylen, 'sha256', function (error, key) {
- if (error) {
- reject('error in pbkdf2');
- } else {
- resolve(key.toString('hex'));
- }
- });
- })
- }
-
- function renderPassword(encryptedLogin, site, passwordOptions) {
- return deriveEncryptedLogin(encryptedLogin, site, passwordOptions).then(function (derivedEncryptedLogin) {
- var template = passwordOptions.template || getPasswordTemplate(passwordOptions);
- return prettyPrint(derivedEncryptedLogin, template);
- });
- }
-
- function createHmac(encryptedLogin, salt) {
- return new Promise(function (resolve) {
- resolve(createHMAC('sha256', new Buffer(encryptedLogin)).update(salt).digest('hex'));
- });
- }
-
- function deriveEncryptedLogin(encryptedLogin, site, options) {
- var _options = options !== undefined ? options : {};
- var length = _options.length || 12;
- var counter = _options.counter || 1;
-
- var salt = site + counter.toString();
- return createHmac(encryptedLogin, salt).then(function (derivedHash) {
- return derivedHash.substring(0, length);
- });
- }
-
- function getPasswordTemplate(passwordTypes) {
- var templates = {
- lowercase: 'vc',
- uppercase: 'VC',
- numbers: 'n',
- symbols: 's',
- };
- var returnedTemplate = '';
- Object.keys(templates).forEach(function (template) {
- if (passwordTypes.hasOwnProperty(template) && passwordTypes[template]) {
- returnedTemplate += templates[template]
- }
- });
- return returnedTemplate;
- }
-
- function prettyPrint(hash, template) {
- var password = '';
-
- string2charCodes(hash).forEach(function (charCode, index) {
- var charType = getCharType(template, index);
- password += getPasswordChar(charType, charCode);
- });
- return password;
- }
-
- function string2charCodes(text) {
- var charCodes = [];
- for (var i = 0; i < text.length; i++) {
- charCodes.push(text.charCodeAt(i));
- }
- return charCodes;
- }
-
- function getCharType(template, index) {
- return template[index % template.length];
- }
-
- function getPasswordChar(charType, index) {
- var passwordsChars = {
- V: 'AEIOUY',
- C: 'BCDFGHJKLMNPQRSTVWXZ',
- v: 'aeiouy',
- c: 'bcdfghjklmnpqrstvwxz',
- A: 'AEIOUYBCDFGHJKLMNPQRSTVWXZ',
- a: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz',
- n: '0123456789',
- s: '@&%?,=[]_:-+*$#!\'^~;()/.',
- x: 'AEIOUYaeiouyBCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz0123456789@&%?,=[]_:-+*$#!\'^~;()/.'
- };
- var passwordChar = passwordsChars[charType];
- return passwordChar[index % passwordChar.length];
- }
-
- function createFingerprint(str) {
- return new Promise(function (resolve) {
- resolve(createHMAC('sha256', new Buffer(str)).digest('hex'))
- });
- }
- }).call(this,require("buffer").Buffer)
- },{"bluebird":4,"buffer":7,"create-hmac":13,"pbkdf2":19}],47:[function(require,module,exports){
- var Promise = require("bluebird");
- var pbkdf2 = require('pbkdf2');
- var bigInt = require("big-integer");
-
- module.exports = {
- generatePassword: generatePassword,
- _calcEntropy: calcEntropy,
- _getSetOfCharacters: getSetOfCharacters,
- _renderPassword: renderPassword
- };
-
- function generatePassword(site, login, masterPassword, passwordProfile) {
- return calcEntropy(site, login, masterPassword, passwordProfile).then(function (entropy) {
- var setOfCharacters = getSetOfCharacters(passwordProfile);
- return renderPassword(entropy, setOfCharacters, passwordProfile)
- });
- }
-
- function calcEntropy(site, login, masterPassword, passwordProfile) {
- return new Promise(function (resolve, reject) {
- var salt = site + login + passwordProfile.counter.toString(16);
- var iterations = passwordProfile.iterations || 100000;
- var keylen = passwordProfile.keylen || 32;
- var digest = passwordProfile.digest || 'sha256';
- pbkdf2.pbkdf2(masterPassword, salt, iterations, keylen, digest, function (error, key) {
- if (error) {
- reject('error in pbkdf2');
- } else {
- resolve(key.toString('hex'));
- }
- });
- });
- }
-
- function getSetOfCharacters(passwordProfile) {
- var subsetOfCharacters = {
- lowercase: 'abcdefghijklmnopqrstuvwxyz',
- uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
- digits: '0123456789',
- symbols: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
- };
-
- if (typeof passwordProfile === 'undefined') {
- return subsetOfCharacters.lowercase + subsetOfCharacters.uppercase + subsetOfCharacters.digits;
- }
-
- var setOfCharacters = '';
- ['lowercase', 'uppercase', 'digits', 'symbols'].forEach(function (subset) {
- if (passwordProfile.hasOwnProperty(subset) && passwordProfile[subset]) {
- setOfCharacters += subsetOfCharacters[subset]
- }
- });
- return setOfCharacters;
- }
-
- function consumeEntropy(generatedPassword, quotient, setOfCharacters, maxLength) {
- if (generatedPassword.length >= maxLength) {
- return generatedPassword
- }
- var longDivision = quotient.divmod(setOfCharacters.length);
- generatedPassword += setOfCharacters[longDivision.remainder];
- return consumeEntropy(generatedPassword, longDivision.quotient, setOfCharacters, maxLength)
- }
-
- function renderPassword(entropy, setOfCharacters, passwordProfile) {
- var _passwordProfile = passwordProfile !== undefined ? passwordProfile : {};
- var length = _passwordProfile.length || 14;
- return consumeEntropy('', bigInt(entropy, 16), setOfCharacters, length);
- }
-
- },{"big-integer":3,"bluebird":4,"pbkdf2":19}]},{},[1])(1)
- });
|