bluebird.js 179 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778
  1. /* @preserve
  2. * The MIT License (MIT)
  3. *
  4. * Copyright (c) 2013-2018 Petka Antonov
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. *
  24. */
  25. /**
  26. * bluebird build version 3.7.2
  27. * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
  28. */
  29. !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){
  30. "use strict";
  31. module.exports = function(Promise) {
  32. var SomePromiseArray = Promise._SomePromiseArray;
  33. function any(promises) {
  34. var ret = new SomePromiseArray(promises);
  35. var promise = ret.promise();
  36. ret.setHowMany(1);
  37. ret.setUnwrap();
  38. ret.init();
  39. return promise;
  40. }
  41. Promise.any = function (promises) {
  42. return any(promises);
  43. };
  44. Promise.prototype.any = function () {
  45. return any(this);
  46. };
  47. };
  48. },{}],2:[function(_dereq_,module,exports){
  49. "use strict";
  50. var firstLineError;
  51. try {throw new Error(); } catch (e) {firstLineError = e;}
  52. var schedule = _dereq_("./schedule");
  53. var Queue = _dereq_("./queue");
  54. function Async() {
  55. this._customScheduler = false;
  56. this._isTickUsed = false;
  57. this._lateQueue = new Queue(16);
  58. this._normalQueue = new Queue(16);
  59. this._haveDrainedQueues = false;
  60. var self = this;
  61. this.drainQueues = function () {
  62. self._drainQueues();
  63. };
  64. this._schedule = schedule;
  65. }
  66. Async.prototype.setScheduler = function(fn) {
  67. var prev = this._schedule;
  68. this._schedule = fn;
  69. this._customScheduler = true;
  70. return prev;
  71. };
  72. Async.prototype.hasCustomScheduler = function() {
  73. return this._customScheduler;
  74. };
  75. Async.prototype.haveItemsQueued = function () {
  76. return this._isTickUsed || this._haveDrainedQueues;
  77. };
  78. Async.prototype.fatalError = function(e, isNode) {
  79. if (isNode) {
  80. process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
  81. "\n");
  82. process.exit(2);
  83. } else {
  84. this.throwLater(e);
  85. }
  86. };
  87. Async.prototype.throwLater = function(fn, arg) {
  88. if (arguments.length === 1) {
  89. arg = fn;
  90. fn = function () { throw arg; };
  91. }
  92. if (typeof setTimeout !== "undefined") {
  93. setTimeout(function() {
  94. fn(arg);
  95. }, 0);
  96. } else try {
  97. this._schedule(function() {
  98. fn(arg);
  99. });
  100. } catch (e) {
  101. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  102. }
  103. };
  104. function AsyncInvokeLater(fn, receiver, arg) {
  105. this._lateQueue.push(fn, receiver, arg);
  106. this._queueTick();
  107. }
  108. function AsyncInvoke(fn, receiver, arg) {
  109. this._normalQueue.push(fn, receiver, arg);
  110. this._queueTick();
  111. }
  112. function AsyncSettlePromises(promise) {
  113. this._normalQueue._pushOne(promise);
  114. this._queueTick();
  115. }
  116. Async.prototype.invokeLater = AsyncInvokeLater;
  117. Async.prototype.invoke = AsyncInvoke;
  118. Async.prototype.settlePromises = AsyncSettlePromises;
  119. function _drainQueue(queue) {
  120. while (queue.length() > 0) {
  121. _drainQueueStep(queue);
  122. }
  123. }
  124. function _drainQueueStep(queue) {
  125. var fn = queue.shift();
  126. if (typeof fn !== "function") {
  127. fn._settlePromises();
  128. } else {
  129. var receiver = queue.shift();
  130. var arg = queue.shift();
  131. fn.call(receiver, arg);
  132. }
  133. }
  134. Async.prototype._drainQueues = function () {
  135. _drainQueue(this._normalQueue);
  136. this._reset();
  137. this._haveDrainedQueues = true;
  138. _drainQueue(this._lateQueue);
  139. };
  140. Async.prototype._queueTick = function () {
  141. if (!this._isTickUsed) {
  142. this._isTickUsed = true;
  143. this._schedule(this.drainQueues);
  144. }
  145. };
  146. Async.prototype._reset = function () {
  147. this._isTickUsed = false;
  148. };
  149. module.exports = Async;
  150. module.exports.firstLineError = firstLineError;
  151. },{"./queue":26,"./schedule":29}],3:[function(_dereq_,module,exports){
  152. "use strict";
  153. module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
  154. var calledBind = false;
  155. var rejectThis = function(_, e) {
  156. this._reject(e);
  157. };
  158. var targetRejected = function(e, context) {
  159. context.promiseRejectionQueued = true;
  160. context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
  161. };
  162. var bindingResolved = function(thisArg, context) {
  163. if (((this._bitField & 50397184) === 0)) {
  164. this._resolveCallback(context.target);
  165. }
  166. };
  167. var bindingRejected = function(e, context) {
  168. if (!context.promiseRejectionQueued) this._reject(e);
  169. };
  170. Promise.prototype.bind = function (thisArg) {
  171. if (!calledBind) {
  172. calledBind = true;
  173. Promise.prototype._propagateFrom = debug.propagateFromFunction();
  174. Promise.prototype._boundValue = debug.boundValueFunction();
  175. }
  176. var maybePromise = tryConvertToPromise(thisArg);
  177. var ret = new Promise(INTERNAL);
  178. ret._propagateFrom(this, 1);
  179. var target = this._target();
  180. ret._setBoundTo(maybePromise);
  181. if (maybePromise instanceof Promise) {
  182. var context = {
  183. promiseRejectionQueued: false,
  184. promise: ret,
  185. target: target,
  186. bindingPromise: maybePromise
  187. };
  188. target._then(INTERNAL, targetRejected, undefined, ret, context);
  189. maybePromise._then(
  190. bindingResolved, bindingRejected, undefined, ret, context);
  191. ret._setOnCancel(maybePromise);
  192. } else {
  193. ret._resolveCallback(target);
  194. }
  195. return ret;
  196. };
  197. Promise.prototype._setBoundTo = function (obj) {
  198. if (obj !== undefined) {
  199. this._bitField = this._bitField | 2097152;
  200. this._boundTo = obj;
  201. } else {
  202. this._bitField = this._bitField & (~2097152);
  203. }
  204. };
  205. Promise.prototype._isBound = function () {
  206. return (this._bitField & 2097152) === 2097152;
  207. };
  208. Promise.bind = function (thisArg, value) {
  209. return Promise.resolve(value).bind(thisArg);
  210. };
  211. };
  212. },{}],4:[function(_dereq_,module,exports){
  213. "use strict";
  214. var old;
  215. if (typeof Promise !== "undefined") old = Promise;
  216. function noConflict() {
  217. try { if (Promise === bluebird) Promise = old; }
  218. catch (e) {}
  219. return bluebird;
  220. }
  221. var bluebird = _dereq_("./promise")();
  222. bluebird.noConflict = noConflict;
  223. module.exports = bluebird;
  224. },{"./promise":22}],5:[function(_dereq_,module,exports){
  225. "use strict";
  226. var cr = Object.create;
  227. if (cr) {
  228. var callerCache = cr(null);
  229. var getterCache = cr(null);
  230. callerCache[" size"] = getterCache[" size"] = 0;
  231. }
  232. module.exports = function(Promise) {
  233. var util = _dereq_("./util");
  234. var canEvaluate = util.canEvaluate;
  235. var isIdentifier = util.isIdentifier;
  236. var getMethodCaller;
  237. var getGetter;
  238. if (!true) {
  239. var makeMethodCaller = function (methodName) {
  240. return new Function("ensureMethod", " \n\
  241. return function(obj) { \n\
  242. 'use strict' \n\
  243. var len = this.length; \n\
  244. ensureMethod(obj, 'methodName'); \n\
  245. switch(len) { \n\
  246. case 1: return obj.methodName(this[0]); \n\
  247. case 2: return obj.methodName(this[0], this[1]); \n\
  248. case 3: return obj.methodName(this[0], this[1], this[2]); \n\
  249. case 0: return obj.methodName(); \n\
  250. default: \n\
  251. return obj.methodName.apply(obj, this); \n\
  252. } \n\
  253. }; \n\
  254. ".replace(/methodName/g, methodName))(ensureMethod);
  255. };
  256. var makeGetter = function (propertyName) {
  257. return new Function("obj", " \n\
  258. 'use strict'; \n\
  259. return obj.propertyName; \n\
  260. ".replace("propertyName", propertyName));
  261. };
  262. var getCompiled = function(name, compiler, cache) {
  263. var ret = cache[name];
  264. if (typeof ret !== "function") {
  265. if (!isIdentifier(name)) {
  266. return null;
  267. }
  268. ret = compiler(name);
  269. cache[name] = ret;
  270. cache[" size"]++;
  271. if (cache[" size"] > 512) {
  272. var keys = Object.keys(cache);
  273. for (var i = 0; i < 256; ++i) delete cache[keys[i]];
  274. cache[" size"] = keys.length - 256;
  275. }
  276. }
  277. return ret;
  278. };
  279. getMethodCaller = function(name) {
  280. return getCompiled(name, makeMethodCaller, callerCache);
  281. };
  282. getGetter = function(name) {
  283. return getCompiled(name, makeGetter, getterCache);
  284. };
  285. }
  286. function ensureMethod(obj, methodName) {
  287. var fn;
  288. if (obj != null) fn = obj[methodName];
  289. if (typeof fn !== "function") {
  290. var message = "Object " + util.classString(obj) + " has no method '" +
  291. util.toString(methodName) + "'";
  292. throw new Promise.TypeError(message);
  293. }
  294. return fn;
  295. }
  296. function caller(obj) {
  297. var methodName = this.pop();
  298. var fn = ensureMethod(obj, methodName);
  299. return fn.apply(obj, this);
  300. }
  301. Promise.prototype.call = function (methodName) {
  302. var args = [].slice.call(arguments, 1);;
  303. if (!true) {
  304. if (canEvaluate) {
  305. var maybeCaller = getMethodCaller(methodName);
  306. if (maybeCaller !== null) {
  307. return this._then(
  308. maybeCaller, undefined, undefined, args, undefined);
  309. }
  310. }
  311. }
  312. args.push(methodName);
  313. return this._then(caller, undefined, undefined, args, undefined);
  314. };
  315. function namedGetter(obj) {
  316. return obj[this];
  317. }
  318. function indexedGetter(obj) {
  319. var index = +this;
  320. if (index < 0) index = Math.max(0, index + obj.length);
  321. return obj[index];
  322. }
  323. Promise.prototype.get = function (propertyName) {
  324. var isIndex = (typeof propertyName === "number");
  325. var getter;
  326. if (!isIndex) {
  327. if (canEvaluate) {
  328. var maybeGetter = getGetter(propertyName);
  329. getter = maybeGetter !== null ? maybeGetter : namedGetter;
  330. } else {
  331. getter = namedGetter;
  332. }
  333. } else {
  334. getter = indexedGetter;
  335. }
  336. return this._then(getter, undefined, undefined, propertyName, undefined);
  337. };
  338. };
  339. },{"./util":36}],6:[function(_dereq_,module,exports){
  340. "use strict";
  341. module.exports = function(Promise, PromiseArray, apiRejection, debug) {
  342. var util = _dereq_("./util");
  343. var tryCatch = util.tryCatch;
  344. var errorObj = util.errorObj;
  345. var async = Promise._async;
  346. Promise.prototype["break"] = Promise.prototype.cancel = function() {
  347. if (!debug.cancellation()) return this._warn("cancellation is disabled");
  348. var promise = this;
  349. var child = promise;
  350. while (promise._isCancellable()) {
  351. if (!promise._cancelBy(child)) {
  352. if (child._isFollowing()) {
  353. child._followee().cancel();
  354. } else {
  355. child._cancelBranched();
  356. }
  357. break;
  358. }
  359. var parent = promise._cancellationParent;
  360. if (parent == null || !parent._isCancellable()) {
  361. if (promise._isFollowing()) {
  362. promise._followee().cancel();
  363. } else {
  364. promise._cancelBranched();
  365. }
  366. break;
  367. } else {
  368. if (promise._isFollowing()) promise._followee().cancel();
  369. promise._setWillBeCancelled();
  370. child = promise;
  371. promise = parent;
  372. }
  373. }
  374. };
  375. Promise.prototype._branchHasCancelled = function() {
  376. this._branchesRemainingToCancel--;
  377. };
  378. Promise.prototype._enoughBranchesHaveCancelled = function() {
  379. return this._branchesRemainingToCancel === undefined ||
  380. this._branchesRemainingToCancel <= 0;
  381. };
  382. Promise.prototype._cancelBy = function(canceller) {
  383. if (canceller === this) {
  384. this._branchesRemainingToCancel = 0;
  385. this._invokeOnCancel();
  386. return true;
  387. } else {
  388. this._branchHasCancelled();
  389. if (this._enoughBranchesHaveCancelled()) {
  390. this._invokeOnCancel();
  391. return true;
  392. }
  393. }
  394. return false;
  395. };
  396. Promise.prototype._cancelBranched = function() {
  397. if (this._enoughBranchesHaveCancelled()) {
  398. this._cancel();
  399. }
  400. };
  401. Promise.prototype._cancel = function() {
  402. if (!this._isCancellable()) return;
  403. this._setCancelled();
  404. async.invoke(this._cancelPromises, this, undefined);
  405. };
  406. Promise.prototype._cancelPromises = function() {
  407. if (this._length() > 0) this._settlePromises();
  408. };
  409. Promise.prototype._unsetOnCancel = function() {
  410. this._onCancelField = undefined;
  411. };
  412. Promise.prototype._isCancellable = function() {
  413. return this.isPending() && !this._isCancelled();
  414. };
  415. Promise.prototype.isCancellable = function() {
  416. return this.isPending() && !this.isCancelled();
  417. };
  418. Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
  419. if (util.isArray(onCancelCallback)) {
  420. for (var i = 0; i < onCancelCallback.length; ++i) {
  421. this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
  422. }
  423. } else if (onCancelCallback !== undefined) {
  424. if (typeof onCancelCallback === "function") {
  425. if (!internalOnly) {
  426. var e = tryCatch(onCancelCallback).call(this._boundValue());
  427. if (e === errorObj) {
  428. this._attachExtraTrace(e.e);
  429. async.throwLater(e.e);
  430. }
  431. }
  432. } else {
  433. onCancelCallback._resultCancelled(this);
  434. }
  435. }
  436. };
  437. Promise.prototype._invokeOnCancel = function() {
  438. var onCancelCallback = this._onCancel();
  439. this._unsetOnCancel();
  440. async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
  441. };
  442. Promise.prototype._invokeInternalOnCancel = function() {
  443. if (this._isCancellable()) {
  444. this._doInvokeOnCancel(this._onCancel(), true);
  445. this._unsetOnCancel();
  446. }
  447. };
  448. Promise.prototype._resultCancelled = function() {
  449. this.cancel();
  450. };
  451. };
  452. },{"./util":36}],7:[function(_dereq_,module,exports){
  453. "use strict";
  454. module.exports = function(NEXT_FILTER) {
  455. var util = _dereq_("./util");
  456. var getKeys = _dereq_("./es5").keys;
  457. var tryCatch = util.tryCatch;
  458. var errorObj = util.errorObj;
  459. function catchFilter(instances, cb, promise) {
  460. return function(e) {
  461. var boundTo = promise._boundValue();
  462. predicateLoop: for (var i = 0; i < instances.length; ++i) {
  463. var item = instances[i];
  464. if (item === Error ||
  465. (item != null && item.prototype instanceof Error)) {
  466. if (e instanceof item) {
  467. return tryCatch(cb).call(boundTo, e);
  468. }
  469. } else if (typeof item === "function") {
  470. var matchesPredicate = tryCatch(item).call(boundTo, e);
  471. if (matchesPredicate === errorObj) {
  472. return matchesPredicate;
  473. } else if (matchesPredicate) {
  474. return tryCatch(cb).call(boundTo, e);
  475. }
  476. } else if (util.isObject(e)) {
  477. var keys = getKeys(item);
  478. for (var j = 0; j < keys.length; ++j) {
  479. var key = keys[j];
  480. if (item[key] != e[key]) {
  481. continue predicateLoop;
  482. }
  483. }
  484. return tryCatch(cb).call(boundTo, e);
  485. }
  486. }
  487. return NEXT_FILTER;
  488. };
  489. }
  490. return catchFilter;
  491. };
  492. },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
  493. "use strict";
  494. module.exports = function(Promise) {
  495. var longStackTraces = false;
  496. var contextStack = [];
  497. Promise.prototype._promiseCreated = function() {};
  498. Promise.prototype._pushContext = function() {};
  499. Promise.prototype._popContext = function() {return null;};
  500. Promise._peekContext = Promise.prototype._peekContext = function() {};
  501. function Context() {
  502. this._trace = new Context.CapturedTrace(peekContext());
  503. }
  504. Context.prototype._pushContext = function () {
  505. if (this._trace !== undefined) {
  506. this._trace._promiseCreated = null;
  507. contextStack.push(this._trace);
  508. }
  509. };
  510. Context.prototype._popContext = function () {
  511. if (this._trace !== undefined) {
  512. var trace = contextStack.pop();
  513. var ret = trace._promiseCreated;
  514. trace._promiseCreated = null;
  515. return ret;
  516. }
  517. return null;
  518. };
  519. function createContext() {
  520. if (longStackTraces) return new Context();
  521. }
  522. function peekContext() {
  523. var lastIndex = contextStack.length - 1;
  524. if (lastIndex >= 0) {
  525. return contextStack[lastIndex];
  526. }
  527. return undefined;
  528. }
  529. Context.CapturedTrace = null;
  530. Context.create = createContext;
  531. Context.deactivateLongStackTraces = function() {};
  532. Context.activateLongStackTraces = function() {
  533. var Promise_pushContext = Promise.prototype._pushContext;
  534. var Promise_popContext = Promise.prototype._popContext;
  535. var Promise_PeekContext = Promise._peekContext;
  536. var Promise_peekContext = Promise.prototype._peekContext;
  537. var Promise_promiseCreated = Promise.prototype._promiseCreated;
  538. Context.deactivateLongStackTraces = function() {
  539. Promise.prototype._pushContext = Promise_pushContext;
  540. Promise.prototype._popContext = Promise_popContext;
  541. Promise._peekContext = Promise_PeekContext;
  542. Promise.prototype._peekContext = Promise_peekContext;
  543. Promise.prototype._promiseCreated = Promise_promiseCreated;
  544. longStackTraces = false;
  545. };
  546. longStackTraces = true;
  547. Promise.prototype._pushContext = Context.prototype._pushContext;
  548. Promise.prototype._popContext = Context.prototype._popContext;
  549. Promise._peekContext = Promise.prototype._peekContext = peekContext;
  550. Promise.prototype._promiseCreated = function() {
  551. var ctx = this._peekContext();
  552. if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
  553. };
  554. };
  555. return Context;
  556. };
  557. },{}],9:[function(_dereq_,module,exports){
  558. "use strict";
  559. module.exports = function(Promise, Context,
  560. enableAsyncHooks, disableAsyncHooks) {
  561. var async = Promise._async;
  562. var Warning = _dereq_("./errors").Warning;
  563. var util = _dereq_("./util");
  564. var es5 = _dereq_("./es5");
  565. var canAttachTrace = util.canAttachTrace;
  566. var unhandledRejectionHandled;
  567. var possiblyUnhandledRejection;
  568. var bluebirdFramePattern =
  569. /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
  570. var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
  571. var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
  572. var stackFramePattern = null;
  573. var formatStack = null;
  574. var indentStackFrames = false;
  575. var printWarning;
  576. var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
  577. (true ||
  578. util.env("BLUEBIRD_DEBUG") ||
  579. util.env("NODE_ENV") === "development"));
  580. var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
  581. (debugging || util.env("BLUEBIRD_WARNINGS")));
  582. var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
  583. (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
  584. var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
  585. (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
  586. var deferUnhandledRejectionCheck;
  587. (function() {
  588. var promises = [];
  589. function unhandledRejectionCheck() {
  590. for (var i = 0; i < promises.length; ++i) {
  591. promises[i]._notifyUnhandledRejection();
  592. }
  593. unhandledRejectionClear();
  594. }
  595. function unhandledRejectionClear() {
  596. promises.length = 0;
  597. }
  598. deferUnhandledRejectionCheck = function(promise) {
  599. promises.push(promise);
  600. setTimeout(unhandledRejectionCheck, 1);
  601. };
  602. es5.defineProperty(Promise, "_unhandledRejectionCheck", {
  603. value: unhandledRejectionCheck
  604. });
  605. es5.defineProperty(Promise, "_unhandledRejectionClear", {
  606. value: unhandledRejectionClear
  607. });
  608. })();
  609. Promise.prototype.suppressUnhandledRejections = function() {
  610. var target = this._target();
  611. target._bitField = ((target._bitField & (~1048576)) |
  612. 524288);
  613. };
  614. Promise.prototype._ensurePossibleRejectionHandled = function () {
  615. if ((this._bitField & 524288) !== 0) return;
  616. this._setRejectionIsUnhandled();
  617. deferUnhandledRejectionCheck(this);
  618. };
  619. Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
  620. fireRejectionEvent("rejectionHandled",
  621. unhandledRejectionHandled, undefined, this);
  622. };
  623. Promise.prototype._setReturnedNonUndefined = function() {
  624. this._bitField = this._bitField | 268435456;
  625. };
  626. Promise.prototype._returnedNonUndefined = function() {
  627. return (this._bitField & 268435456) !== 0;
  628. };
  629. Promise.prototype._notifyUnhandledRejection = function () {
  630. if (this._isRejectionUnhandled()) {
  631. var reason = this._settledValue();
  632. this._setUnhandledRejectionIsNotified();
  633. fireRejectionEvent("unhandledRejection",
  634. possiblyUnhandledRejection, reason, this);
  635. }
  636. };
  637. Promise.prototype._setUnhandledRejectionIsNotified = function () {
  638. this._bitField = this._bitField | 262144;
  639. };
  640. Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
  641. this._bitField = this._bitField & (~262144);
  642. };
  643. Promise.prototype._isUnhandledRejectionNotified = function () {
  644. return (this._bitField & 262144) > 0;
  645. };
  646. Promise.prototype._setRejectionIsUnhandled = function () {
  647. this._bitField = this._bitField | 1048576;
  648. };
  649. Promise.prototype._unsetRejectionIsUnhandled = function () {
  650. this._bitField = this._bitField & (~1048576);
  651. if (this._isUnhandledRejectionNotified()) {
  652. this._unsetUnhandledRejectionIsNotified();
  653. this._notifyUnhandledRejectionIsHandled();
  654. }
  655. };
  656. Promise.prototype._isRejectionUnhandled = function () {
  657. return (this._bitField & 1048576) > 0;
  658. };
  659. Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
  660. return warn(message, shouldUseOwnTrace, promise || this);
  661. };
  662. Promise.onPossiblyUnhandledRejection = function (fn) {
  663. var context = Promise._getContext();
  664. possiblyUnhandledRejection = util.contextBind(context, fn);
  665. };
  666. Promise.onUnhandledRejectionHandled = function (fn) {
  667. var context = Promise._getContext();
  668. unhandledRejectionHandled = util.contextBind(context, fn);
  669. };
  670. var disableLongStackTraces = function() {};
  671. Promise.longStackTraces = function () {
  672. if (async.haveItemsQueued() && !config.longStackTraces) {
  673. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  674. }
  675. if (!config.longStackTraces && longStackTracesIsSupported()) {
  676. var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
  677. var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
  678. var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
  679. config.longStackTraces = true;
  680. disableLongStackTraces = function() {
  681. if (async.haveItemsQueued() && !config.longStackTraces) {
  682. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  683. }
  684. Promise.prototype._captureStackTrace = Promise_captureStackTrace;
  685. Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
  686. Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
  687. Context.deactivateLongStackTraces();
  688. config.longStackTraces = false;
  689. };
  690. Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
  691. Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
  692. Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
  693. Context.activateLongStackTraces();
  694. }
  695. };
  696. Promise.hasLongStackTraces = function () {
  697. return config.longStackTraces && longStackTracesIsSupported();
  698. };
  699. var legacyHandlers = {
  700. unhandledrejection: {
  701. before: function() {
  702. var ret = util.global.onunhandledrejection;
  703. util.global.onunhandledrejection = null;
  704. return ret;
  705. },
  706. after: function(fn) {
  707. util.global.onunhandledrejection = fn;
  708. }
  709. },
  710. rejectionhandled: {
  711. before: function() {
  712. var ret = util.global.onrejectionhandled;
  713. util.global.onrejectionhandled = null;
  714. return ret;
  715. },
  716. after: function(fn) {
  717. util.global.onrejectionhandled = fn;
  718. }
  719. }
  720. };
  721. var fireDomEvent = (function() {
  722. var dispatch = function(legacy, e) {
  723. if (legacy) {
  724. var fn;
  725. try {
  726. fn = legacy.before();
  727. return !util.global.dispatchEvent(e);
  728. } finally {
  729. legacy.after(fn);
  730. }
  731. } else {
  732. return !util.global.dispatchEvent(e);
  733. }
  734. };
  735. try {
  736. if (typeof CustomEvent === "function") {
  737. var event = new CustomEvent("CustomEvent");
  738. util.global.dispatchEvent(event);
  739. return function(name, event) {
  740. name = name.toLowerCase();
  741. var eventData = {
  742. detail: event,
  743. cancelable: true
  744. };
  745. var domEvent = new CustomEvent(name, eventData);
  746. es5.defineProperty(
  747. domEvent, "promise", {value: event.promise});
  748. es5.defineProperty(
  749. domEvent, "reason", {value: event.reason});
  750. return dispatch(legacyHandlers[name], domEvent);
  751. };
  752. } else if (typeof Event === "function") {
  753. var event = new Event("CustomEvent");
  754. util.global.dispatchEvent(event);
  755. return function(name, event) {
  756. name = name.toLowerCase();
  757. var domEvent = new Event(name, {
  758. cancelable: true
  759. });
  760. domEvent.detail = event;
  761. es5.defineProperty(domEvent, "promise", {value: event.promise});
  762. es5.defineProperty(domEvent, "reason", {value: event.reason});
  763. return dispatch(legacyHandlers[name], domEvent);
  764. };
  765. } else {
  766. var event = document.createEvent("CustomEvent");
  767. event.initCustomEvent("testingtheevent", false, true, {});
  768. util.global.dispatchEvent(event);
  769. return function(name, event) {
  770. name = name.toLowerCase();
  771. var domEvent = document.createEvent("CustomEvent");
  772. domEvent.initCustomEvent(name, false, true,
  773. event);
  774. return dispatch(legacyHandlers[name], domEvent);
  775. };
  776. }
  777. } catch (e) {}
  778. return function() {
  779. return false;
  780. };
  781. })();
  782. var fireGlobalEvent = (function() {
  783. if (util.isNode) {
  784. return function() {
  785. return process.emit.apply(process, arguments);
  786. };
  787. } else {
  788. if (!util.global) {
  789. return function() {
  790. return false;
  791. };
  792. }
  793. return function(name) {
  794. var methodName = "on" + name.toLowerCase();
  795. var method = util.global[methodName];
  796. if (!method) return false;
  797. method.apply(util.global, [].slice.call(arguments, 1));
  798. return true;
  799. };
  800. }
  801. })();
  802. function generatePromiseLifecycleEventObject(name, promise) {
  803. return {promise: promise};
  804. }
  805. var eventToObjectGenerator = {
  806. promiseCreated: generatePromiseLifecycleEventObject,
  807. promiseFulfilled: generatePromiseLifecycleEventObject,
  808. promiseRejected: generatePromiseLifecycleEventObject,
  809. promiseResolved: generatePromiseLifecycleEventObject,
  810. promiseCancelled: generatePromiseLifecycleEventObject,
  811. promiseChained: function(name, promise, child) {
  812. return {promise: promise, child: child};
  813. },
  814. warning: function(name, warning) {
  815. return {warning: warning};
  816. },
  817. unhandledRejection: function (name, reason, promise) {
  818. return {reason: reason, promise: promise};
  819. },
  820. rejectionHandled: generatePromiseLifecycleEventObject
  821. };
  822. var activeFireEvent = function (name) {
  823. var globalEventFired = false;
  824. try {
  825. globalEventFired = fireGlobalEvent.apply(null, arguments);
  826. } catch (e) {
  827. async.throwLater(e);
  828. globalEventFired = true;
  829. }
  830. var domEventFired = false;
  831. try {
  832. domEventFired = fireDomEvent(name,
  833. eventToObjectGenerator[name].apply(null, arguments));
  834. } catch (e) {
  835. async.throwLater(e);
  836. domEventFired = true;
  837. }
  838. return domEventFired || globalEventFired;
  839. };
  840. Promise.config = function(opts) {
  841. opts = Object(opts);
  842. if ("longStackTraces" in opts) {
  843. if (opts.longStackTraces) {
  844. Promise.longStackTraces();
  845. } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
  846. disableLongStackTraces();
  847. }
  848. }
  849. if ("warnings" in opts) {
  850. var warningsOption = opts.warnings;
  851. config.warnings = !!warningsOption;
  852. wForgottenReturn = config.warnings;
  853. if (util.isObject(warningsOption)) {
  854. if ("wForgottenReturn" in warningsOption) {
  855. wForgottenReturn = !!warningsOption.wForgottenReturn;
  856. }
  857. }
  858. }
  859. if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
  860. if (async.haveItemsQueued()) {
  861. throw new Error(
  862. "cannot enable cancellation after promises are in use");
  863. }
  864. Promise.prototype._clearCancellationData =
  865. cancellationClearCancellationData;
  866. Promise.prototype._propagateFrom = cancellationPropagateFrom;
  867. Promise.prototype._onCancel = cancellationOnCancel;
  868. Promise.prototype._setOnCancel = cancellationSetOnCancel;
  869. Promise.prototype._attachCancellationCallback =
  870. cancellationAttachCancellationCallback;
  871. Promise.prototype._execute = cancellationExecute;
  872. propagateFromFunction = cancellationPropagateFrom;
  873. config.cancellation = true;
  874. }
  875. if ("monitoring" in opts) {
  876. if (opts.monitoring && !config.monitoring) {
  877. config.monitoring = true;
  878. Promise.prototype._fireEvent = activeFireEvent;
  879. } else if (!opts.monitoring && config.monitoring) {
  880. config.monitoring = false;
  881. Promise.prototype._fireEvent = defaultFireEvent;
  882. }
  883. }
  884. if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) {
  885. var prev = config.asyncHooks;
  886. var cur = !!opts.asyncHooks;
  887. if (prev !== cur) {
  888. config.asyncHooks = cur;
  889. if (cur) {
  890. enableAsyncHooks();
  891. } else {
  892. disableAsyncHooks();
  893. }
  894. }
  895. }
  896. return Promise;
  897. };
  898. function defaultFireEvent() { return false; }
  899. Promise.prototype._fireEvent = defaultFireEvent;
  900. Promise.prototype._execute = function(executor, resolve, reject) {
  901. try {
  902. executor(resolve, reject);
  903. } catch (e) {
  904. return e;
  905. }
  906. };
  907. Promise.prototype._onCancel = function () {};
  908. Promise.prototype._setOnCancel = function (handler) { ; };
  909. Promise.prototype._attachCancellationCallback = function(onCancel) {
  910. ;
  911. };
  912. Promise.prototype._captureStackTrace = function () {};
  913. Promise.prototype._attachExtraTrace = function () {};
  914. Promise.prototype._dereferenceTrace = function () {};
  915. Promise.prototype._clearCancellationData = function() {};
  916. Promise.prototype._propagateFrom = function (parent, flags) {
  917. ;
  918. ;
  919. };
  920. function cancellationExecute(executor, resolve, reject) {
  921. var promise = this;
  922. try {
  923. executor(resolve, reject, function(onCancel) {
  924. if (typeof onCancel !== "function") {
  925. throw new TypeError("onCancel must be a function, got: " +
  926. util.toString(onCancel));
  927. }
  928. promise._attachCancellationCallback(onCancel);
  929. });
  930. } catch (e) {
  931. return e;
  932. }
  933. }
  934. function cancellationAttachCancellationCallback(onCancel) {
  935. if (!this._isCancellable()) return this;
  936. var previousOnCancel = this._onCancel();
  937. if (previousOnCancel !== undefined) {
  938. if (util.isArray(previousOnCancel)) {
  939. previousOnCancel.push(onCancel);
  940. } else {
  941. this._setOnCancel([previousOnCancel, onCancel]);
  942. }
  943. } else {
  944. this._setOnCancel(onCancel);
  945. }
  946. }
  947. function cancellationOnCancel() {
  948. return this._onCancelField;
  949. }
  950. function cancellationSetOnCancel(onCancel) {
  951. this._onCancelField = onCancel;
  952. }
  953. function cancellationClearCancellationData() {
  954. this._cancellationParent = undefined;
  955. this._onCancelField = undefined;
  956. }
  957. function cancellationPropagateFrom(parent, flags) {
  958. if ((flags & 1) !== 0) {
  959. this._cancellationParent = parent;
  960. var branchesRemainingToCancel = parent._branchesRemainingToCancel;
  961. if (branchesRemainingToCancel === undefined) {
  962. branchesRemainingToCancel = 0;
  963. }
  964. parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
  965. }
  966. if ((flags & 2) !== 0 && parent._isBound()) {
  967. this._setBoundTo(parent._boundTo);
  968. }
  969. }
  970. function bindingPropagateFrom(parent, flags) {
  971. if ((flags & 2) !== 0 && parent._isBound()) {
  972. this._setBoundTo(parent._boundTo);
  973. }
  974. }
  975. var propagateFromFunction = bindingPropagateFrom;
  976. function boundValueFunction() {
  977. var ret = this._boundTo;
  978. if (ret !== undefined) {
  979. if (ret instanceof Promise) {
  980. if (ret.isFulfilled()) {
  981. return ret.value();
  982. } else {
  983. return undefined;
  984. }
  985. }
  986. }
  987. return ret;
  988. }
  989. function longStackTracesCaptureStackTrace() {
  990. this._trace = new CapturedTrace(this._peekContext());
  991. }
  992. function longStackTracesAttachExtraTrace(error, ignoreSelf) {
  993. if (canAttachTrace(error)) {
  994. var trace = this._trace;
  995. if (trace !== undefined) {
  996. if (ignoreSelf) trace = trace._parent;
  997. }
  998. if (trace !== undefined) {
  999. trace.attachExtraTrace(error);
  1000. } else if (!error.__stackCleaned__) {
  1001. var parsed = parseStackAndMessage(error);
  1002. util.notEnumerableProp(error, "stack",
  1003. parsed.message + "\n" + parsed.stack.join("\n"));
  1004. util.notEnumerableProp(error, "__stackCleaned__", true);
  1005. }
  1006. }
  1007. }
  1008. function longStackTracesDereferenceTrace() {
  1009. this._trace = undefined;
  1010. }
  1011. function checkForgottenReturns(returnValue, promiseCreated, name, promise,
  1012. parent) {
  1013. if (returnValue === undefined && promiseCreated !== null &&
  1014. wForgottenReturn) {
  1015. if (parent !== undefined && parent._returnedNonUndefined()) return;
  1016. if ((promise._bitField & 65535) === 0) return;
  1017. if (name) name = name + " ";
  1018. var handlerLine = "";
  1019. var creatorLine = "";
  1020. if (promiseCreated._trace) {
  1021. var traceLines = promiseCreated._trace.stack.split("\n");
  1022. var stack = cleanStack(traceLines);
  1023. for (var i = stack.length - 1; i >= 0; --i) {
  1024. var line = stack[i];
  1025. if (!nodeFramePattern.test(line)) {
  1026. var lineMatches = line.match(parseLinePattern);
  1027. if (lineMatches) {
  1028. handlerLine = "at " + lineMatches[1] +
  1029. ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
  1030. }
  1031. break;
  1032. }
  1033. }
  1034. if (stack.length > 0) {
  1035. var firstUserLine = stack[0];
  1036. for (var i = 0; i < traceLines.length; ++i) {
  1037. if (traceLines[i] === firstUserLine) {
  1038. if (i > 0) {
  1039. creatorLine = "\n" + traceLines[i - 1];
  1040. }
  1041. break;
  1042. }
  1043. }
  1044. }
  1045. }
  1046. var msg = "a promise was created in a " + name +
  1047. "handler " + handlerLine + "but was not returned from it, " +
  1048. "see http://goo.gl/rRqMUw" +
  1049. creatorLine;
  1050. promise._warn(msg, true, promiseCreated);
  1051. }
  1052. }
  1053. function deprecated(name, replacement) {
  1054. var message = name +
  1055. " is deprecated and will be removed in a future version.";
  1056. if (replacement) message += " Use " + replacement + " instead.";
  1057. return warn(message);
  1058. }
  1059. function warn(message, shouldUseOwnTrace, promise) {
  1060. if (!config.warnings) return;
  1061. var warning = new Warning(message);
  1062. var ctx;
  1063. if (shouldUseOwnTrace) {
  1064. promise._attachExtraTrace(warning);
  1065. } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
  1066. ctx.attachExtraTrace(warning);
  1067. } else {
  1068. var parsed = parseStackAndMessage(warning);
  1069. warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
  1070. }
  1071. if (!activeFireEvent("warning", warning)) {
  1072. formatAndLogError(warning, "", true);
  1073. }
  1074. }
  1075. function reconstructStack(message, stacks) {
  1076. for (var i = 0; i < stacks.length - 1; ++i) {
  1077. stacks[i].push("From previous event:");
  1078. stacks[i] = stacks[i].join("\n");
  1079. }
  1080. if (i < stacks.length) {
  1081. stacks[i] = stacks[i].join("\n");
  1082. }
  1083. return message + "\n" + stacks.join("\n");
  1084. }
  1085. function removeDuplicateOrEmptyJumps(stacks) {
  1086. for (var i = 0; i < stacks.length; ++i) {
  1087. if (stacks[i].length === 0 ||
  1088. ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
  1089. stacks.splice(i, 1);
  1090. i--;
  1091. }
  1092. }
  1093. }
  1094. function removeCommonRoots(stacks) {
  1095. var current = stacks[0];
  1096. for (var i = 1; i < stacks.length; ++i) {
  1097. var prev = stacks[i];
  1098. var currentLastIndex = current.length - 1;
  1099. var currentLastLine = current[currentLastIndex];
  1100. var commonRootMeetPoint = -1;
  1101. for (var j = prev.length - 1; j >= 0; --j) {
  1102. if (prev[j] === currentLastLine) {
  1103. commonRootMeetPoint = j;
  1104. break;
  1105. }
  1106. }
  1107. for (var j = commonRootMeetPoint; j >= 0; --j) {
  1108. var line = prev[j];
  1109. if (current[currentLastIndex] === line) {
  1110. current.pop();
  1111. currentLastIndex--;
  1112. } else {
  1113. break;
  1114. }
  1115. }
  1116. current = prev;
  1117. }
  1118. }
  1119. function cleanStack(stack) {
  1120. var ret = [];
  1121. for (var i = 0; i < stack.length; ++i) {
  1122. var line = stack[i];
  1123. var isTraceLine = " (No stack trace)" === line ||
  1124. stackFramePattern.test(line);
  1125. var isInternalFrame = isTraceLine && shouldIgnore(line);
  1126. if (isTraceLine && !isInternalFrame) {
  1127. if (indentStackFrames && line.charAt(0) !== " ") {
  1128. line = " " + line;
  1129. }
  1130. ret.push(line);
  1131. }
  1132. }
  1133. return ret;
  1134. }
  1135. function stackFramesAsArray(error) {
  1136. var stack = error.stack.replace(/\s+$/g, "").split("\n");
  1137. for (var i = 0; i < stack.length; ++i) {
  1138. var line = stack[i];
  1139. if (" (No stack trace)" === line || stackFramePattern.test(line)) {
  1140. break;
  1141. }
  1142. }
  1143. if (i > 0 && error.name != "SyntaxError") {
  1144. stack = stack.slice(i);
  1145. }
  1146. return stack;
  1147. }
  1148. function parseStackAndMessage(error) {
  1149. var stack = error.stack;
  1150. var message = error.toString();
  1151. stack = typeof stack === "string" && stack.length > 0
  1152. ? stackFramesAsArray(error) : [" (No stack trace)"];
  1153. return {
  1154. message: message,
  1155. stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
  1156. };
  1157. }
  1158. function formatAndLogError(error, title, isSoft) {
  1159. if (typeof console !== "undefined") {
  1160. var message;
  1161. if (util.isObject(error)) {
  1162. var stack = error.stack;
  1163. message = title + formatStack(stack, error);
  1164. } else {
  1165. message = title + String(error);
  1166. }
  1167. if (typeof printWarning === "function") {
  1168. printWarning(message, isSoft);
  1169. } else if (typeof console.log === "function" ||
  1170. typeof console.log === "object") {
  1171. console.log(message);
  1172. }
  1173. }
  1174. }
  1175. function fireRejectionEvent(name, localHandler, reason, promise) {
  1176. var localEventFired = false;
  1177. try {
  1178. if (typeof localHandler === "function") {
  1179. localEventFired = true;
  1180. if (name === "rejectionHandled") {
  1181. localHandler(promise);
  1182. } else {
  1183. localHandler(reason, promise);
  1184. }
  1185. }
  1186. } catch (e) {
  1187. async.throwLater(e);
  1188. }
  1189. if (name === "unhandledRejection") {
  1190. if (!activeFireEvent(name, reason, promise) && !localEventFired) {
  1191. formatAndLogError(reason, "Unhandled rejection ");
  1192. }
  1193. } else {
  1194. activeFireEvent(name, promise);
  1195. }
  1196. }
  1197. function formatNonError(obj) {
  1198. var str;
  1199. if (typeof obj === "function") {
  1200. str = "[function " +
  1201. (obj.name || "anonymous") +
  1202. "]";
  1203. } else {
  1204. str = obj && typeof obj.toString === "function"
  1205. ? obj.toString() : util.toString(obj);
  1206. var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
  1207. if (ruselessToString.test(str)) {
  1208. try {
  1209. var newStr = JSON.stringify(obj);
  1210. str = newStr;
  1211. }
  1212. catch(e) {
  1213. }
  1214. }
  1215. if (str.length === 0) {
  1216. str = "(empty array)";
  1217. }
  1218. }
  1219. return ("(<" + snip(str) + ">, no stack trace)");
  1220. }
  1221. function snip(str) {
  1222. var maxChars = 41;
  1223. if (str.length < maxChars) {
  1224. return str;
  1225. }
  1226. return str.substr(0, maxChars - 3) + "...";
  1227. }
  1228. function longStackTracesIsSupported() {
  1229. return typeof captureStackTrace === "function";
  1230. }
  1231. var shouldIgnore = function() { return false; };
  1232. var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
  1233. function parseLineInfo(line) {
  1234. var matches = line.match(parseLineInfoRegex);
  1235. if (matches) {
  1236. return {
  1237. fileName: matches[1],
  1238. line: parseInt(matches[2], 10)
  1239. };
  1240. }
  1241. }
  1242. function setBounds(firstLineError, lastLineError) {
  1243. if (!longStackTracesIsSupported()) return;
  1244. var firstStackLines = (firstLineError.stack || "").split("\n");
  1245. var lastStackLines = (lastLineError.stack || "").split("\n");
  1246. var firstIndex = -1;
  1247. var lastIndex = -1;
  1248. var firstFileName;
  1249. var lastFileName;
  1250. for (var i = 0; i < firstStackLines.length; ++i) {
  1251. var result = parseLineInfo(firstStackLines[i]);
  1252. if (result) {
  1253. firstFileName = result.fileName;
  1254. firstIndex = result.line;
  1255. break;
  1256. }
  1257. }
  1258. for (var i = 0; i < lastStackLines.length; ++i) {
  1259. var result = parseLineInfo(lastStackLines[i]);
  1260. if (result) {
  1261. lastFileName = result.fileName;
  1262. lastIndex = result.line;
  1263. break;
  1264. }
  1265. }
  1266. if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
  1267. firstFileName !== lastFileName || firstIndex >= lastIndex) {
  1268. return;
  1269. }
  1270. shouldIgnore = function(line) {
  1271. if (bluebirdFramePattern.test(line)) return true;
  1272. var info = parseLineInfo(line);
  1273. if (info) {
  1274. if (info.fileName === firstFileName &&
  1275. (firstIndex <= info.line && info.line <= lastIndex)) {
  1276. return true;
  1277. }
  1278. }
  1279. return false;
  1280. };
  1281. }
  1282. function CapturedTrace(parent) {
  1283. this._parent = parent;
  1284. this._promisesCreated = 0;
  1285. var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
  1286. captureStackTrace(this, CapturedTrace);
  1287. if (length > 32) this.uncycle();
  1288. }
  1289. util.inherits(CapturedTrace, Error);
  1290. Context.CapturedTrace = CapturedTrace;
  1291. CapturedTrace.prototype.uncycle = function() {
  1292. var length = this._length;
  1293. if (length < 2) return;
  1294. var nodes = [];
  1295. var stackToIndex = {};
  1296. for (var i = 0, node = this; node !== undefined; ++i) {
  1297. nodes.push(node);
  1298. node = node._parent;
  1299. }
  1300. length = this._length = i;
  1301. for (var i = length - 1; i >= 0; --i) {
  1302. var stack = nodes[i].stack;
  1303. if (stackToIndex[stack] === undefined) {
  1304. stackToIndex[stack] = i;
  1305. }
  1306. }
  1307. for (var i = 0; i < length; ++i) {
  1308. var currentStack = nodes[i].stack;
  1309. var index = stackToIndex[currentStack];
  1310. if (index !== undefined && index !== i) {
  1311. if (index > 0) {
  1312. nodes[index - 1]._parent = undefined;
  1313. nodes[index - 1]._length = 1;
  1314. }
  1315. nodes[i]._parent = undefined;
  1316. nodes[i]._length = 1;
  1317. var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
  1318. if (index < length - 1) {
  1319. cycleEdgeNode._parent = nodes[index + 1];
  1320. cycleEdgeNode._parent.uncycle();
  1321. cycleEdgeNode._length =
  1322. cycleEdgeNode._parent._length + 1;
  1323. } else {
  1324. cycleEdgeNode._parent = undefined;
  1325. cycleEdgeNode._length = 1;
  1326. }
  1327. var currentChildLength = cycleEdgeNode._length + 1;
  1328. for (var j = i - 2; j >= 0; --j) {
  1329. nodes[j]._length = currentChildLength;
  1330. currentChildLength++;
  1331. }
  1332. return;
  1333. }
  1334. }
  1335. };
  1336. CapturedTrace.prototype.attachExtraTrace = function(error) {
  1337. if (error.__stackCleaned__) return;
  1338. this.uncycle();
  1339. var parsed = parseStackAndMessage(error);
  1340. var message = parsed.message;
  1341. var stacks = [parsed.stack];
  1342. var trace = this;
  1343. while (trace !== undefined) {
  1344. stacks.push(cleanStack(trace.stack.split("\n")));
  1345. trace = trace._parent;
  1346. }
  1347. removeCommonRoots(stacks);
  1348. removeDuplicateOrEmptyJumps(stacks);
  1349. util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
  1350. util.notEnumerableProp(error, "__stackCleaned__", true);
  1351. };
  1352. var captureStackTrace = (function stackDetection() {
  1353. var v8stackFramePattern = /^\s*at\s*/;
  1354. var v8stackFormatter = function(stack, error) {
  1355. if (typeof stack === "string") return stack;
  1356. if (error.name !== undefined &&
  1357. error.message !== undefined) {
  1358. return error.toString();
  1359. }
  1360. return formatNonError(error);
  1361. };
  1362. if (typeof Error.stackTraceLimit === "number" &&
  1363. typeof Error.captureStackTrace === "function") {
  1364. Error.stackTraceLimit += 6;
  1365. stackFramePattern = v8stackFramePattern;
  1366. formatStack = v8stackFormatter;
  1367. var captureStackTrace = Error.captureStackTrace;
  1368. shouldIgnore = function(line) {
  1369. return bluebirdFramePattern.test(line);
  1370. };
  1371. return function(receiver, ignoreUntil) {
  1372. Error.stackTraceLimit += 6;
  1373. captureStackTrace(receiver, ignoreUntil);
  1374. Error.stackTraceLimit -= 6;
  1375. };
  1376. }
  1377. var err = new Error();
  1378. if (typeof err.stack === "string" &&
  1379. err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
  1380. stackFramePattern = /@/;
  1381. formatStack = v8stackFormatter;
  1382. indentStackFrames = true;
  1383. return function captureStackTrace(o) {
  1384. o.stack = new Error().stack;
  1385. };
  1386. }
  1387. var hasStackAfterThrow;
  1388. try { throw new Error(); }
  1389. catch(e) {
  1390. hasStackAfterThrow = ("stack" in e);
  1391. }
  1392. if (!("stack" in err) && hasStackAfterThrow &&
  1393. typeof Error.stackTraceLimit === "number") {
  1394. stackFramePattern = v8stackFramePattern;
  1395. formatStack = v8stackFormatter;
  1396. return function captureStackTrace(o) {
  1397. Error.stackTraceLimit += 6;
  1398. try { throw new Error(); }
  1399. catch(e) { o.stack = e.stack; }
  1400. Error.stackTraceLimit -= 6;
  1401. };
  1402. }
  1403. formatStack = function(stack, error) {
  1404. if (typeof stack === "string") return stack;
  1405. if ((typeof error === "object" ||
  1406. typeof error === "function") &&
  1407. error.name !== undefined &&
  1408. error.message !== undefined) {
  1409. return error.toString();
  1410. }
  1411. return formatNonError(error);
  1412. };
  1413. return null;
  1414. })([]);
  1415. if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
  1416. printWarning = function (message) {
  1417. console.warn(message);
  1418. };
  1419. if (util.isNode && process.stderr.isTTY) {
  1420. printWarning = function(message, isSoft) {
  1421. var color = isSoft ? "\u001b[33m" : "\u001b[31m";
  1422. console.warn(color + message + "\u001b[0m\n");
  1423. };
  1424. } else if (!util.isNode && typeof (new Error().stack) === "string") {
  1425. printWarning = function(message, isSoft) {
  1426. console.warn("%c" + message,
  1427. isSoft ? "color: darkorange" : "color: red");
  1428. };
  1429. }
  1430. }
  1431. var config = {
  1432. warnings: warnings,
  1433. longStackTraces: false,
  1434. cancellation: false,
  1435. monitoring: false,
  1436. asyncHooks: false
  1437. };
  1438. if (longStackTraces) Promise.longStackTraces();
  1439. return {
  1440. asyncHooks: function() {
  1441. return config.asyncHooks;
  1442. },
  1443. longStackTraces: function() {
  1444. return config.longStackTraces;
  1445. },
  1446. warnings: function() {
  1447. return config.warnings;
  1448. },
  1449. cancellation: function() {
  1450. return config.cancellation;
  1451. },
  1452. monitoring: function() {
  1453. return config.monitoring;
  1454. },
  1455. propagateFromFunction: function() {
  1456. return propagateFromFunction;
  1457. },
  1458. boundValueFunction: function() {
  1459. return boundValueFunction;
  1460. },
  1461. checkForgottenReturns: checkForgottenReturns,
  1462. setBounds: setBounds,
  1463. warn: warn,
  1464. deprecated: deprecated,
  1465. CapturedTrace: CapturedTrace,
  1466. fireDomEvent: fireDomEvent,
  1467. fireGlobalEvent: fireGlobalEvent
  1468. };
  1469. };
  1470. },{"./errors":12,"./es5":13,"./util":36}],10:[function(_dereq_,module,exports){
  1471. "use strict";
  1472. module.exports = function(Promise) {
  1473. function returner() {
  1474. return this.value;
  1475. }
  1476. function thrower() {
  1477. throw this.reason;
  1478. }
  1479. Promise.prototype["return"] =
  1480. Promise.prototype.thenReturn = function (value) {
  1481. if (value instanceof Promise) value.suppressUnhandledRejections();
  1482. return this._then(
  1483. returner, undefined, undefined, {value: value}, undefined);
  1484. };
  1485. Promise.prototype["throw"] =
  1486. Promise.prototype.thenThrow = function (reason) {
  1487. return this._then(
  1488. thrower, undefined, undefined, {reason: reason}, undefined);
  1489. };
  1490. Promise.prototype.catchThrow = function (reason) {
  1491. if (arguments.length <= 1) {
  1492. return this._then(
  1493. undefined, thrower, undefined, {reason: reason}, undefined);
  1494. } else {
  1495. var _reason = arguments[1];
  1496. var handler = function() {throw _reason;};
  1497. return this.caught(reason, handler);
  1498. }
  1499. };
  1500. Promise.prototype.catchReturn = function (value) {
  1501. if (arguments.length <= 1) {
  1502. if (value instanceof Promise) value.suppressUnhandledRejections();
  1503. return this._then(
  1504. undefined, returner, undefined, {value: value}, undefined);
  1505. } else {
  1506. var _value = arguments[1];
  1507. if (_value instanceof Promise) _value.suppressUnhandledRejections();
  1508. var handler = function() {return _value;};
  1509. return this.caught(value, handler);
  1510. }
  1511. };
  1512. };
  1513. },{}],11:[function(_dereq_,module,exports){
  1514. "use strict";
  1515. module.exports = function(Promise, INTERNAL) {
  1516. var PromiseReduce = Promise.reduce;
  1517. var PromiseAll = Promise.all;
  1518. function promiseAllThis() {
  1519. return PromiseAll(this);
  1520. }
  1521. function PromiseMapSeries(promises, fn) {
  1522. return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
  1523. }
  1524. Promise.prototype.each = function (fn) {
  1525. return PromiseReduce(this, fn, INTERNAL, 0)
  1526. ._then(promiseAllThis, undefined, undefined, this, undefined);
  1527. };
  1528. Promise.prototype.mapSeries = function (fn) {
  1529. return PromiseReduce(this, fn, INTERNAL, INTERNAL);
  1530. };
  1531. Promise.each = function (promises, fn) {
  1532. return PromiseReduce(promises, fn, INTERNAL, 0)
  1533. ._then(promiseAllThis, undefined, undefined, promises, undefined);
  1534. };
  1535. Promise.mapSeries = PromiseMapSeries;
  1536. };
  1537. },{}],12:[function(_dereq_,module,exports){
  1538. "use strict";
  1539. var es5 = _dereq_("./es5");
  1540. var Objectfreeze = es5.freeze;
  1541. var util = _dereq_("./util");
  1542. var inherits = util.inherits;
  1543. var notEnumerableProp = util.notEnumerableProp;
  1544. function subError(nameProperty, defaultMessage) {
  1545. function SubError(message) {
  1546. if (!(this instanceof SubError)) return new SubError(message);
  1547. notEnumerableProp(this, "message",
  1548. typeof message === "string" ? message : defaultMessage);
  1549. notEnumerableProp(this, "name", nameProperty);
  1550. if (Error.captureStackTrace) {
  1551. Error.captureStackTrace(this, this.constructor);
  1552. } else {
  1553. Error.call(this);
  1554. }
  1555. }
  1556. inherits(SubError, Error);
  1557. return SubError;
  1558. }
  1559. var _TypeError, _RangeError;
  1560. var Warning = subError("Warning", "warning");
  1561. var CancellationError = subError("CancellationError", "cancellation error");
  1562. var TimeoutError = subError("TimeoutError", "timeout error");
  1563. var AggregateError = subError("AggregateError", "aggregate error");
  1564. try {
  1565. _TypeError = TypeError;
  1566. _RangeError = RangeError;
  1567. } catch(e) {
  1568. _TypeError = subError("TypeError", "type error");
  1569. _RangeError = subError("RangeError", "range error");
  1570. }
  1571. var methods = ("join pop push shift unshift slice filter forEach some " +
  1572. "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
  1573. for (var i = 0; i < methods.length; ++i) {
  1574. if (typeof Array.prototype[methods[i]] === "function") {
  1575. AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
  1576. }
  1577. }
  1578. es5.defineProperty(AggregateError.prototype, "length", {
  1579. value: 0,
  1580. configurable: false,
  1581. writable: true,
  1582. enumerable: true
  1583. });
  1584. AggregateError.prototype["isOperational"] = true;
  1585. var level = 0;
  1586. AggregateError.prototype.toString = function() {
  1587. var indent = Array(level * 4 + 1).join(" ");
  1588. var ret = "\n" + indent + "AggregateError of:" + "\n";
  1589. level++;
  1590. indent = Array(level * 4 + 1).join(" ");
  1591. for (var i = 0; i < this.length; ++i) {
  1592. var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
  1593. var lines = str.split("\n");
  1594. for (var j = 0; j < lines.length; ++j) {
  1595. lines[j] = indent + lines[j];
  1596. }
  1597. str = lines.join("\n");
  1598. ret += str + "\n";
  1599. }
  1600. level--;
  1601. return ret;
  1602. };
  1603. function OperationalError(message) {
  1604. if (!(this instanceof OperationalError))
  1605. return new OperationalError(message);
  1606. notEnumerableProp(this, "name", "OperationalError");
  1607. notEnumerableProp(this, "message", message);
  1608. this.cause = message;
  1609. this["isOperational"] = true;
  1610. if (message instanceof Error) {
  1611. notEnumerableProp(this, "message", message.message);
  1612. notEnumerableProp(this, "stack", message.stack);
  1613. } else if (Error.captureStackTrace) {
  1614. Error.captureStackTrace(this, this.constructor);
  1615. }
  1616. }
  1617. inherits(OperationalError, Error);
  1618. var errorTypes = Error["__BluebirdErrorTypes__"];
  1619. if (!errorTypes) {
  1620. errorTypes = Objectfreeze({
  1621. CancellationError: CancellationError,
  1622. TimeoutError: TimeoutError,
  1623. OperationalError: OperationalError,
  1624. RejectionError: OperationalError,
  1625. AggregateError: AggregateError
  1626. });
  1627. es5.defineProperty(Error, "__BluebirdErrorTypes__", {
  1628. value: errorTypes,
  1629. writable: false,
  1630. enumerable: false,
  1631. configurable: false
  1632. });
  1633. }
  1634. module.exports = {
  1635. Error: Error,
  1636. TypeError: _TypeError,
  1637. RangeError: _RangeError,
  1638. CancellationError: errorTypes.CancellationError,
  1639. OperationalError: errorTypes.OperationalError,
  1640. TimeoutError: errorTypes.TimeoutError,
  1641. AggregateError: errorTypes.AggregateError,
  1642. Warning: Warning
  1643. };
  1644. },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
  1645. var isES5 = (function(){
  1646. "use strict";
  1647. return this === undefined;
  1648. })();
  1649. if (isES5) {
  1650. module.exports = {
  1651. freeze: Object.freeze,
  1652. defineProperty: Object.defineProperty,
  1653. getDescriptor: Object.getOwnPropertyDescriptor,
  1654. keys: Object.keys,
  1655. names: Object.getOwnPropertyNames,
  1656. getPrototypeOf: Object.getPrototypeOf,
  1657. isArray: Array.isArray,
  1658. isES5: isES5,
  1659. propertyIsWritable: function(obj, prop) {
  1660. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  1661. return !!(!descriptor || descriptor.writable || descriptor.set);
  1662. }
  1663. };
  1664. } else {
  1665. var has = {}.hasOwnProperty;
  1666. var str = {}.toString;
  1667. var proto = {}.constructor.prototype;
  1668. var ObjectKeys = function (o) {
  1669. var ret = [];
  1670. for (var key in o) {
  1671. if (has.call(o, key)) {
  1672. ret.push(key);
  1673. }
  1674. }
  1675. return ret;
  1676. };
  1677. var ObjectGetDescriptor = function(o, key) {
  1678. return {value: o[key]};
  1679. };
  1680. var ObjectDefineProperty = function (o, key, desc) {
  1681. o[key] = desc.value;
  1682. return o;
  1683. };
  1684. var ObjectFreeze = function (obj) {
  1685. return obj;
  1686. };
  1687. var ObjectGetPrototypeOf = function (obj) {
  1688. try {
  1689. return Object(obj).constructor.prototype;
  1690. }
  1691. catch (e) {
  1692. return proto;
  1693. }
  1694. };
  1695. var ArrayIsArray = function (obj) {
  1696. try {
  1697. return str.call(obj) === "[object Array]";
  1698. }
  1699. catch(e) {
  1700. return false;
  1701. }
  1702. };
  1703. module.exports = {
  1704. isArray: ArrayIsArray,
  1705. keys: ObjectKeys,
  1706. names: ObjectKeys,
  1707. defineProperty: ObjectDefineProperty,
  1708. getDescriptor: ObjectGetDescriptor,
  1709. freeze: ObjectFreeze,
  1710. getPrototypeOf: ObjectGetPrototypeOf,
  1711. isES5: isES5,
  1712. propertyIsWritable: function() {
  1713. return true;
  1714. }
  1715. };
  1716. }
  1717. },{}],14:[function(_dereq_,module,exports){
  1718. "use strict";
  1719. module.exports = function(Promise, INTERNAL) {
  1720. var PromiseMap = Promise.map;
  1721. Promise.prototype.filter = function (fn, options) {
  1722. return PromiseMap(this, fn, options, INTERNAL);
  1723. };
  1724. Promise.filter = function (promises, fn, options) {
  1725. return PromiseMap(promises, fn, options, INTERNAL);
  1726. };
  1727. };
  1728. },{}],15:[function(_dereq_,module,exports){
  1729. "use strict";
  1730. module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
  1731. var util = _dereq_("./util");
  1732. var CancellationError = Promise.CancellationError;
  1733. var errorObj = util.errorObj;
  1734. var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
  1735. function PassThroughHandlerContext(promise, type, handler) {
  1736. this.promise = promise;
  1737. this.type = type;
  1738. this.handler = handler;
  1739. this.called = false;
  1740. this.cancelPromise = null;
  1741. }
  1742. PassThroughHandlerContext.prototype.isFinallyHandler = function() {
  1743. return this.type === 0;
  1744. };
  1745. function FinallyHandlerCancelReaction(finallyHandler) {
  1746. this.finallyHandler = finallyHandler;
  1747. }
  1748. FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
  1749. checkCancel(this.finallyHandler);
  1750. };
  1751. function checkCancel(ctx, reason) {
  1752. if (ctx.cancelPromise != null) {
  1753. if (arguments.length > 1) {
  1754. ctx.cancelPromise._reject(reason);
  1755. } else {
  1756. ctx.cancelPromise._cancel();
  1757. }
  1758. ctx.cancelPromise = null;
  1759. return true;
  1760. }
  1761. return false;
  1762. }
  1763. function succeed() {
  1764. return finallyHandler.call(this, this.promise._target()._settledValue());
  1765. }
  1766. function fail(reason) {
  1767. if (checkCancel(this, reason)) return;
  1768. errorObj.e = reason;
  1769. return errorObj;
  1770. }
  1771. function finallyHandler(reasonOrValue) {
  1772. var promise = this.promise;
  1773. var handler = this.handler;
  1774. if (!this.called) {
  1775. this.called = true;
  1776. var ret = this.isFinallyHandler()
  1777. ? handler.call(promise._boundValue())
  1778. : handler.call(promise._boundValue(), reasonOrValue);
  1779. if (ret === NEXT_FILTER) {
  1780. return ret;
  1781. } else if (ret !== undefined) {
  1782. promise._setReturnedNonUndefined();
  1783. var maybePromise = tryConvertToPromise(ret, promise);
  1784. if (maybePromise instanceof Promise) {
  1785. if (this.cancelPromise != null) {
  1786. if (maybePromise._isCancelled()) {
  1787. var reason =
  1788. new CancellationError("late cancellation observer");
  1789. promise._attachExtraTrace(reason);
  1790. errorObj.e = reason;
  1791. return errorObj;
  1792. } else if (maybePromise.isPending()) {
  1793. maybePromise._attachCancellationCallback(
  1794. new FinallyHandlerCancelReaction(this));
  1795. }
  1796. }
  1797. return maybePromise._then(
  1798. succeed, fail, undefined, this, undefined);
  1799. }
  1800. }
  1801. }
  1802. if (promise.isRejected()) {
  1803. checkCancel(this);
  1804. errorObj.e = reasonOrValue;
  1805. return errorObj;
  1806. } else {
  1807. checkCancel(this);
  1808. return reasonOrValue;
  1809. }
  1810. }
  1811. Promise.prototype._passThrough = function(handler, type, success, fail) {
  1812. if (typeof handler !== "function") return this.then();
  1813. return this._then(success,
  1814. fail,
  1815. undefined,
  1816. new PassThroughHandlerContext(this, type, handler),
  1817. undefined);
  1818. };
  1819. Promise.prototype.lastly =
  1820. Promise.prototype["finally"] = function (handler) {
  1821. return this._passThrough(handler,
  1822. 0,
  1823. finallyHandler,
  1824. finallyHandler);
  1825. };
  1826. Promise.prototype.tap = function (handler) {
  1827. return this._passThrough(handler, 1, finallyHandler);
  1828. };
  1829. Promise.prototype.tapCatch = function (handlerOrPredicate) {
  1830. var len = arguments.length;
  1831. if(len === 1) {
  1832. return this._passThrough(handlerOrPredicate,
  1833. 1,
  1834. undefined,
  1835. finallyHandler);
  1836. } else {
  1837. var catchInstances = new Array(len - 1),
  1838. j = 0, i;
  1839. for (i = 0; i < len - 1; ++i) {
  1840. var item = arguments[i];
  1841. if (util.isObject(item)) {
  1842. catchInstances[j++] = item;
  1843. } else {
  1844. return Promise.reject(new TypeError(
  1845. "tapCatch statement predicate: "
  1846. + "expecting an object but got " + util.classString(item)
  1847. ));
  1848. }
  1849. }
  1850. catchInstances.length = j;
  1851. var handler = arguments[i];
  1852. return this._passThrough(catchFilter(catchInstances, handler, this),
  1853. 1,
  1854. undefined,
  1855. finallyHandler);
  1856. }
  1857. };
  1858. return PassThroughHandlerContext;
  1859. };
  1860. },{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){
  1861. "use strict";
  1862. module.exports = function(Promise,
  1863. apiRejection,
  1864. INTERNAL,
  1865. tryConvertToPromise,
  1866. Proxyable,
  1867. debug) {
  1868. var errors = _dereq_("./errors");
  1869. var TypeError = errors.TypeError;
  1870. var util = _dereq_("./util");
  1871. var errorObj = util.errorObj;
  1872. var tryCatch = util.tryCatch;
  1873. var yieldHandlers = [];
  1874. function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
  1875. for (var i = 0; i < yieldHandlers.length; ++i) {
  1876. traceParent._pushContext();
  1877. var result = tryCatch(yieldHandlers[i])(value);
  1878. traceParent._popContext();
  1879. if (result === errorObj) {
  1880. traceParent._pushContext();
  1881. var ret = Promise.reject(errorObj.e);
  1882. traceParent._popContext();
  1883. return ret;
  1884. }
  1885. var maybePromise = tryConvertToPromise(result, traceParent);
  1886. if (maybePromise instanceof Promise) return maybePromise;
  1887. }
  1888. return null;
  1889. }
  1890. function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
  1891. if (debug.cancellation()) {
  1892. var internal = new Promise(INTERNAL);
  1893. var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
  1894. this._promise = internal.lastly(function() {
  1895. return _finallyPromise;
  1896. });
  1897. internal._captureStackTrace();
  1898. internal._setOnCancel(this);
  1899. } else {
  1900. var promise = this._promise = new Promise(INTERNAL);
  1901. promise._captureStackTrace();
  1902. }
  1903. this._stack = stack;
  1904. this._generatorFunction = generatorFunction;
  1905. this._receiver = receiver;
  1906. this._generator = undefined;
  1907. this._yieldHandlers = typeof yieldHandler === "function"
  1908. ? [yieldHandler].concat(yieldHandlers)
  1909. : yieldHandlers;
  1910. this._yieldedPromise = null;
  1911. this._cancellationPhase = false;
  1912. }
  1913. util.inherits(PromiseSpawn, Proxyable);
  1914. PromiseSpawn.prototype._isResolved = function() {
  1915. return this._promise === null;
  1916. };
  1917. PromiseSpawn.prototype._cleanup = function() {
  1918. this._promise = this._generator = null;
  1919. if (debug.cancellation() && this._finallyPromise !== null) {
  1920. this._finallyPromise._fulfill();
  1921. this._finallyPromise = null;
  1922. }
  1923. };
  1924. PromiseSpawn.prototype._promiseCancelled = function() {
  1925. if (this._isResolved()) return;
  1926. var implementsReturn = typeof this._generator["return"] !== "undefined";
  1927. var result;
  1928. if (!implementsReturn) {
  1929. var reason = new Promise.CancellationError(
  1930. "generator .return() sentinel");
  1931. Promise.coroutine.returnSentinel = reason;
  1932. this._promise._attachExtraTrace(reason);
  1933. this._promise._pushContext();
  1934. result = tryCatch(this._generator["throw"]).call(this._generator,
  1935. reason);
  1936. this._promise._popContext();
  1937. } else {
  1938. this._promise._pushContext();
  1939. result = tryCatch(this._generator["return"]).call(this._generator,
  1940. undefined);
  1941. this._promise._popContext();
  1942. }
  1943. this._cancellationPhase = true;
  1944. this._yieldedPromise = null;
  1945. this._continue(result);
  1946. };
  1947. PromiseSpawn.prototype._promiseFulfilled = function(value) {
  1948. this._yieldedPromise = null;
  1949. this._promise._pushContext();
  1950. var result = tryCatch(this._generator.next).call(this._generator, value);
  1951. this._promise._popContext();
  1952. this._continue(result);
  1953. };
  1954. PromiseSpawn.prototype._promiseRejected = function(reason) {
  1955. this._yieldedPromise = null;
  1956. this._promise._attachExtraTrace(reason);
  1957. this._promise._pushContext();
  1958. var result = tryCatch(this._generator["throw"])
  1959. .call(this._generator, reason);
  1960. this._promise._popContext();
  1961. this._continue(result);
  1962. };
  1963. PromiseSpawn.prototype._resultCancelled = function() {
  1964. if (this._yieldedPromise instanceof Promise) {
  1965. var promise = this._yieldedPromise;
  1966. this._yieldedPromise = null;
  1967. promise.cancel();
  1968. }
  1969. };
  1970. PromiseSpawn.prototype.promise = function () {
  1971. return this._promise;
  1972. };
  1973. PromiseSpawn.prototype._run = function () {
  1974. this._generator = this._generatorFunction.call(this._receiver);
  1975. this._receiver =
  1976. this._generatorFunction = undefined;
  1977. this._promiseFulfilled(undefined);
  1978. };
  1979. PromiseSpawn.prototype._continue = function (result) {
  1980. var promise = this._promise;
  1981. if (result === errorObj) {
  1982. this._cleanup();
  1983. if (this._cancellationPhase) {
  1984. return promise.cancel();
  1985. } else {
  1986. return promise._rejectCallback(result.e, false);
  1987. }
  1988. }
  1989. var value = result.value;
  1990. if (result.done === true) {
  1991. this._cleanup();
  1992. if (this._cancellationPhase) {
  1993. return promise.cancel();
  1994. } else {
  1995. return promise._resolveCallback(value);
  1996. }
  1997. } else {
  1998. var maybePromise = tryConvertToPromise(value, this._promise);
  1999. if (!(maybePromise instanceof Promise)) {
  2000. maybePromise =
  2001. promiseFromYieldHandler(maybePromise,
  2002. this._yieldHandlers,
  2003. this._promise);
  2004. if (maybePromise === null) {
  2005. this._promiseRejected(
  2006. new TypeError(
  2007. "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) +
  2008. "From coroutine:\u000a" +
  2009. this._stack.split("\n").slice(1, -7).join("\n")
  2010. )
  2011. );
  2012. return;
  2013. }
  2014. }
  2015. maybePromise = maybePromise._target();
  2016. var bitField = maybePromise._bitField;
  2017. ;
  2018. if (((bitField & 50397184) === 0)) {
  2019. this._yieldedPromise = maybePromise;
  2020. maybePromise._proxy(this, null);
  2021. } else if (((bitField & 33554432) !== 0)) {
  2022. Promise._async.invoke(
  2023. this._promiseFulfilled, this, maybePromise._value()
  2024. );
  2025. } else if (((bitField & 16777216) !== 0)) {
  2026. Promise._async.invoke(
  2027. this._promiseRejected, this, maybePromise._reason()
  2028. );
  2029. } else {
  2030. this._promiseCancelled();
  2031. }
  2032. }
  2033. };
  2034. Promise.coroutine = function (generatorFunction, options) {
  2035. if (typeof generatorFunction !== "function") {
  2036. throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  2037. }
  2038. var yieldHandler = Object(options).yieldHandler;
  2039. var PromiseSpawn$ = PromiseSpawn;
  2040. var stack = new Error().stack;
  2041. return function () {
  2042. var generator = generatorFunction.apply(this, arguments);
  2043. var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
  2044. stack);
  2045. var ret = spawn.promise();
  2046. spawn._generator = generator;
  2047. spawn._promiseFulfilled(undefined);
  2048. return ret;
  2049. };
  2050. };
  2051. Promise.coroutine.addYieldHandler = function(fn) {
  2052. if (typeof fn !== "function") {
  2053. throw new TypeError("expecting a function but got " + util.classString(fn));
  2054. }
  2055. yieldHandlers.push(fn);
  2056. };
  2057. Promise.spawn = function (generatorFunction) {
  2058. debug.deprecated("Promise.spawn()", "Promise.coroutine()");
  2059. if (typeof generatorFunction !== "function") {
  2060. return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  2061. }
  2062. var spawn = new PromiseSpawn(generatorFunction, this);
  2063. var ret = spawn.promise();
  2064. spawn._run(Promise.spawn);
  2065. return ret;
  2066. };
  2067. };
  2068. },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
  2069. "use strict";
  2070. module.exports =
  2071. function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) {
  2072. var util = _dereq_("./util");
  2073. var canEvaluate = util.canEvaluate;
  2074. var tryCatch = util.tryCatch;
  2075. var errorObj = util.errorObj;
  2076. var reject;
  2077. if (!true) {
  2078. if (canEvaluate) {
  2079. var thenCallback = function(i) {
  2080. return new Function("value", "holder", " \n\
  2081. 'use strict'; \n\
  2082. holder.pIndex = value; \n\
  2083. holder.checkFulfillment(this); \n\
  2084. ".replace(/Index/g, i));
  2085. };
  2086. var promiseSetter = function(i) {
  2087. return new Function("promise", "holder", " \n\
  2088. 'use strict'; \n\
  2089. holder.pIndex = promise; \n\
  2090. ".replace(/Index/g, i));
  2091. };
  2092. var generateHolderClass = function(total) {
  2093. var props = new Array(total);
  2094. for (var i = 0; i < props.length; ++i) {
  2095. props[i] = "this.p" + (i+1);
  2096. }
  2097. var assignment = props.join(" = ") + " = null;";
  2098. var cancellationCode= "var promise;\n" + props.map(function(prop) {
  2099. return " \n\
  2100. promise = " + prop + "; \n\
  2101. if (promise instanceof Promise) { \n\
  2102. promise.cancel(); \n\
  2103. } \n\
  2104. ";
  2105. }).join("\n");
  2106. var passedArguments = props.join(", ");
  2107. var name = "Holder$" + total;
  2108. var code = "return function(tryCatch, errorObj, Promise, async) { \n\
  2109. 'use strict'; \n\
  2110. function [TheName](fn) { \n\
  2111. [TheProperties] \n\
  2112. this.fn = fn; \n\
  2113. this.asyncNeeded = true; \n\
  2114. this.now = 0; \n\
  2115. } \n\
  2116. \n\
  2117. [TheName].prototype._callFunction = function(promise) { \n\
  2118. promise._pushContext(); \n\
  2119. var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
  2120. promise._popContext(); \n\
  2121. if (ret === errorObj) { \n\
  2122. promise._rejectCallback(ret.e, false); \n\
  2123. } else { \n\
  2124. promise._resolveCallback(ret); \n\
  2125. } \n\
  2126. }; \n\
  2127. \n\
  2128. [TheName].prototype.checkFulfillment = function(promise) { \n\
  2129. var now = ++this.now; \n\
  2130. if (now === [TheTotal]) { \n\
  2131. if (this.asyncNeeded) { \n\
  2132. async.invoke(this._callFunction, this, promise); \n\
  2133. } else { \n\
  2134. this._callFunction(promise); \n\
  2135. } \n\
  2136. \n\
  2137. } \n\
  2138. }; \n\
  2139. \n\
  2140. [TheName].prototype._resultCancelled = function() { \n\
  2141. [CancellationCode] \n\
  2142. }; \n\
  2143. \n\
  2144. return [TheName]; \n\
  2145. }(tryCatch, errorObj, Promise, async); \n\
  2146. ";
  2147. code = code.replace(/\[TheName\]/g, name)
  2148. .replace(/\[TheTotal\]/g, total)
  2149. .replace(/\[ThePassedArguments\]/g, passedArguments)
  2150. .replace(/\[TheProperties\]/g, assignment)
  2151. .replace(/\[CancellationCode\]/g, cancellationCode);
  2152. return new Function("tryCatch", "errorObj", "Promise", "async", code)
  2153. (tryCatch, errorObj, Promise, async);
  2154. };
  2155. var holderClasses = [];
  2156. var thenCallbacks = [];
  2157. var promiseSetters = [];
  2158. for (var i = 0; i < 8; ++i) {
  2159. holderClasses.push(generateHolderClass(i + 1));
  2160. thenCallbacks.push(thenCallback(i + 1));
  2161. promiseSetters.push(promiseSetter(i + 1));
  2162. }
  2163. reject = function (reason) {
  2164. this._reject(reason);
  2165. };
  2166. }}
  2167. Promise.join = function () {
  2168. var last = arguments.length - 1;
  2169. var fn;
  2170. if (last > 0 && typeof arguments[last] === "function") {
  2171. fn = arguments[last];
  2172. if (!true) {
  2173. if (last <= 8 && canEvaluate) {
  2174. var ret = new Promise(INTERNAL);
  2175. ret._captureStackTrace();
  2176. var HolderClass = holderClasses[last - 1];
  2177. var holder = new HolderClass(fn);
  2178. var callbacks = thenCallbacks;
  2179. for (var i = 0; i < last; ++i) {
  2180. var maybePromise = tryConvertToPromise(arguments[i], ret);
  2181. if (maybePromise instanceof Promise) {
  2182. maybePromise = maybePromise._target();
  2183. var bitField = maybePromise._bitField;
  2184. ;
  2185. if (((bitField & 50397184) === 0)) {
  2186. maybePromise._then(callbacks[i], reject,
  2187. undefined, ret, holder);
  2188. promiseSetters[i](maybePromise, holder);
  2189. holder.asyncNeeded = false;
  2190. } else if (((bitField & 33554432) !== 0)) {
  2191. callbacks[i].call(ret,
  2192. maybePromise._value(), holder);
  2193. } else if (((bitField & 16777216) !== 0)) {
  2194. ret._reject(maybePromise._reason());
  2195. } else {
  2196. ret._cancel();
  2197. }
  2198. } else {
  2199. callbacks[i].call(ret, maybePromise, holder);
  2200. }
  2201. }
  2202. if (!ret._isFateSealed()) {
  2203. if (holder.asyncNeeded) {
  2204. var context = Promise._getContext();
  2205. holder.fn = util.contextBind(context, holder.fn);
  2206. }
  2207. ret._setAsyncGuaranteed();
  2208. ret._setOnCancel(holder);
  2209. }
  2210. return ret;
  2211. }
  2212. }
  2213. }
  2214. var args = [].slice.call(arguments);;
  2215. if (fn) args.pop();
  2216. var ret = new PromiseArray(args).promise();
  2217. return fn !== undefined ? ret.spread(fn) : ret;
  2218. };
  2219. };
  2220. },{"./util":36}],18:[function(_dereq_,module,exports){
  2221. "use strict";
  2222. module.exports = function(Promise,
  2223. PromiseArray,
  2224. apiRejection,
  2225. tryConvertToPromise,
  2226. INTERNAL,
  2227. debug) {
  2228. var util = _dereq_("./util");
  2229. var tryCatch = util.tryCatch;
  2230. var errorObj = util.errorObj;
  2231. var async = Promise._async;
  2232. function MappingPromiseArray(promises, fn, limit, _filter) {
  2233. this.constructor$(promises);
  2234. this._promise._captureStackTrace();
  2235. var context = Promise._getContext();
  2236. this._callback = util.contextBind(context, fn);
  2237. this._preservedValues = _filter === INTERNAL
  2238. ? new Array(this.length())
  2239. : null;
  2240. this._limit = limit;
  2241. this._inFlight = 0;
  2242. this._queue = [];
  2243. async.invoke(this._asyncInit, this, undefined);
  2244. if (util.isArray(promises)) {
  2245. for (var i = 0; i < promises.length; ++i) {
  2246. var maybePromise = promises[i];
  2247. if (maybePromise instanceof Promise) {
  2248. maybePromise.suppressUnhandledRejections();
  2249. }
  2250. }
  2251. }
  2252. }
  2253. util.inherits(MappingPromiseArray, PromiseArray);
  2254. MappingPromiseArray.prototype._asyncInit = function() {
  2255. this._init$(undefined, -2);
  2256. };
  2257. MappingPromiseArray.prototype._init = function () {};
  2258. MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
  2259. var values = this._values;
  2260. var length = this.length();
  2261. var preservedValues = this._preservedValues;
  2262. var limit = this._limit;
  2263. if (index < 0) {
  2264. index = (index * -1) - 1;
  2265. values[index] = value;
  2266. if (limit >= 1) {
  2267. this._inFlight--;
  2268. this._drainQueue();
  2269. if (this._isResolved()) return true;
  2270. }
  2271. } else {
  2272. if (limit >= 1 && this._inFlight >= limit) {
  2273. values[index] = value;
  2274. this._queue.push(index);
  2275. return false;
  2276. }
  2277. if (preservedValues !== null) preservedValues[index] = value;
  2278. var promise = this._promise;
  2279. var callback = this._callback;
  2280. var receiver = promise._boundValue();
  2281. promise._pushContext();
  2282. var ret = tryCatch(callback).call(receiver, value, index, length);
  2283. var promiseCreated = promise._popContext();
  2284. debug.checkForgottenReturns(
  2285. ret,
  2286. promiseCreated,
  2287. preservedValues !== null ? "Promise.filter" : "Promise.map",
  2288. promise
  2289. );
  2290. if (ret === errorObj) {
  2291. this._reject(ret.e);
  2292. return true;
  2293. }
  2294. var maybePromise = tryConvertToPromise(ret, this._promise);
  2295. if (maybePromise instanceof Promise) {
  2296. maybePromise = maybePromise._target();
  2297. var bitField = maybePromise._bitField;
  2298. ;
  2299. if (((bitField & 50397184) === 0)) {
  2300. if (limit >= 1) this._inFlight++;
  2301. values[index] = maybePromise;
  2302. maybePromise._proxy(this, (index + 1) * -1);
  2303. return false;
  2304. } else if (((bitField & 33554432) !== 0)) {
  2305. ret = maybePromise._value();
  2306. } else if (((bitField & 16777216) !== 0)) {
  2307. this._reject(maybePromise._reason());
  2308. return true;
  2309. } else {
  2310. this._cancel();
  2311. return true;
  2312. }
  2313. }
  2314. values[index] = ret;
  2315. }
  2316. var totalResolved = ++this._totalResolved;
  2317. if (totalResolved >= length) {
  2318. if (preservedValues !== null) {
  2319. this._filter(values, preservedValues);
  2320. } else {
  2321. this._resolve(values);
  2322. }
  2323. return true;
  2324. }
  2325. return false;
  2326. };
  2327. MappingPromiseArray.prototype._drainQueue = function () {
  2328. var queue = this._queue;
  2329. var limit = this._limit;
  2330. var values = this._values;
  2331. while (queue.length > 0 && this._inFlight < limit) {
  2332. if (this._isResolved()) return;
  2333. var index = queue.pop();
  2334. this._promiseFulfilled(values[index], index);
  2335. }
  2336. };
  2337. MappingPromiseArray.prototype._filter = function (booleans, values) {
  2338. var len = values.length;
  2339. var ret = new Array(len);
  2340. var j = 0;
  2341. for (var i = 0; i < len; ++i) {
  2342. if (booleans[i]) ret[j++] = values[i];
  2343. }
  2344. ret.length = j;
  2345. this._resolve(ret);
  2346. };
  2347. MappingPromiseArray.prototype.preservedValues = function () {
  2348. return this._preservedValues;
  2349. };
  2350. function map(promises, fn, options, _filter) {
  2351. if (typeof fn !== "function") {
  2352. return apiRejection("expecting a function but got " + util.classString(fn));
  2353. }
  2354. var limit = 0;
  2355. if (options !== undefined) {
  2356. if (typeof options === "object" && options !== null) {
  2357. if (typeof options.concurrency !== "number") {
  2358. return Promise.reject(
  2359. new TypeError("'concurrency' must be a number but it is " +
  2360. util.classString(options.concurrency)));
  2361. }
  2362. limit = options.concurrency;
  2363. } else {
  2364. return Promise.reject(new TypeError(
  2365. "options argument must be an object but it is " +
  2366. util.classString(options)));
  2367. }
  2368. }
  2369. limit = typeof limit === "number" &&
  2370. isFinite(limit) && limit >= 1 ? limit : 0;
  2371. return new MappingPromiseArray(promises, fn, limit, _filter).promise();
  2372. }
  2373. Promise.prototype.map = function (fn, options) {
  2374. return map(this, fn, options, null);
  2375. };
  2376. Promise.map = function (promises, fn, options, _filter) {
  2377. return map(promises, fn, options, _filter);
  2378. };
  2379. };
  2380. },{"./util":36}],19:[function(_dereq_,module,exports){
  2381. "use strict";
  2382. module.exports =
  2383. function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
  2384. var util = _dereq_("./util");
  2385. var tryCatch = util.tryCatch;
  2386. Promise.method = function (fn) {
  2387. if (typeof fn !== "function") {
  2388. throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
  2389. }
  2390. return function () {
  2391. var ret = new Promise(INTERNAL);
  2392. ret._captureStackTrace();
  2393. ret._pushContext();
  2394. var value = tryCatch(fn).apply(this, arguments);
  2395. var promiseCreated = ret._popContext();
  2396. debug.checkForgottenReturns(
  2397. value, promiseCreated, "Promise.method", ret);
  2398. ret._resolveFromSyncValue(value);
  2399. return ret;
  2400. };
  2401. };
  2402. Promise.attempt = Promise["try"] = function (fn) {
  2403. if (typeof fn !== "function") {
  2404. return apiRejection("expecting a function but got " + util.classString(fn));
  2405. }
  2406. var ret = new Promise(INTERNAL);
  2407. ret._captureStackTrace();
  2408. ret._pushContext();
  2409. var value;
  2410. if (arguments.length > 1) {
  2411. debug.deprecated("calling Promise.try with more than 1 argument");
  2412. var arg = arguments[1];
  2413. var ctx = arguments[2];
  2414. value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
  2415. : tryCatch(fn).call(ctx, arg);
  2416. } else {
  2417. value = tryCatch(fn)();
  2418. }
  2419. var promiseCreated = ret._popContext();
  2420. debug.checkForgottenReturns(
  2421. value, promiseCreated, "Promise.try", ret);
  2422. ret._resolveFromSyncValue(value);
  2423. return ret;
  2424. };
  2425. Promise.prototype._resolveFromSyncValue = function (value) {
  2426. if (value === util.errorObj) {
  2427. this._rejectCallback(value.e, false);
  2428. } else {
  2429. this._resolveCallback(value, true);
  2430. }
  2431. };
  2432. };
  2433. },{"./util":36}],20:[function(_dereq_,module,exports){
  2434. "use strict";
  2435. var util = _dereq_("./util");
  2436. var maybeWrapAsError = util.maybeWrapAsError;
  2437. var errors = _dereq_("./errors");
  2438. var OperationalError = errors.OperationalError;
  2439. var es5 = _dereq_("./es5");
  2440. function isUntypedError(obj) {
  2441. return obj instanceof Error &&
  2442. es5.getPrototypeOf(obj) === Error.prototype;
  2443. }
  2444. var rErrorKey = /^(?:name|message|stack|cause)$/;
  2445. function wrapAsOperationalError(obj) {
  2446. var ret;
  2447. if (isUntypedError(obj)) {
  2448. ret = new OperationalError(obj);
  2449. ret.name = obj.name;
  2450. ret.message = obj.message;
  2451. ret.stack = obj.stack;
  2452. var keys = es5.keys(obj);
  2453. for (var i = 0; i < keys.length; ++i) {
  2454. var key = keys[i];
  2455. if (!rErrorKey.test(key)) {
  2456. ret[key] = obj[key];
  2457. }
  2458. }
  2459. return ret;
  2460. }
  2461. util.markAsOriginatingFromRejection(obj);
  2462. return obj;
  2463. }
  2464. function nodebackForPromise(promise, multiArgs) {
  2465. return function(err, value) {
  2466. if (promise === null) return;
  2467. if (err) {
  2468. var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
  2469. promise._attachExtraTrace(wrapped);
  2470. promise._reject(wrapped);
  2471. } else if (!multiArgs) {
  2472. promise._fulfill(value);
  2473. } else {
  2474. var args = [].slice.call(arguments, 1);;
  2475. promise._fulfill(args);
  2476. }
  2477. promise = null;
  2478. };
  2479. }
  2480. module.exports = nodebackForPromise;
  2481. },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
  2482. "use strict";
  2483. module.exports = function(Promise) {
  2484. var util = _dereq_("./util");
  2485. var async = Promise._async;
  2486. var tryCatch = util.tryCatch;
  2487. var errorObj = util.errorObj;
  2488. function spreadAdapter(val, nodeback) {
  2489. var promise = this;
  2490. if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
  2491. var ret =
  2492. tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
  2493. if (ret === errorObj) {
  2494. async.throwLater(ret.e);
  2495. }
  2496. }
  2497. function successAdapter(val, nodeback) {
  2498. var promise = this;
  2499. var receiver = promise._boundValue();
  2500. var ret = val === undefined
  2501. ? tryCatch(nodeback).call(receiver, null)
  2502. : tryCatch(nodeback).call(receiver, null, val);
  2503. if (ret === errorObj) {
  2504. async.throwLater(ret.e);
  2505. }
  2506. }
  2507. function errorAdapter(reason, nodeback) {
  2508. var promise = this;
  2509. if (!reason) {
  2510. var newReason = new Error(reason + "");
  2511. newReason.cause = reason;
  2512. reason = newReason;
  2513. }
  2514. var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
  2515. if (ret === errorObj) {
  2516. async.throwLater(ret.e);
  2517. }
  2518. }
  2519. Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
  2520. options) {
  2521. if (typeof nodeback == "function") {
  2522. var adapter = successAdapter;
  2523. if (options !== undefined && Object(options).spread) {
  2524. adapter = spreadAdapter;
  2525. }
  2526. this._then(
  2527. adapter,
  2528. errorAdapter,
  2529. undefined,
  2530. this,
  2531. nodeback
  2532. );
  2533. }
  2534. return this;
  2535. };
  2536. };
  2537. },{"./util":36}],22:[function(_dereq_,module,exports){
  2538. "use strict";
  2539. module.exports = function() {
  2540. var makeSelfResolutionError = function () {
  2541. return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  2542. };
  2543. var reflectHandler = function() {
  2544. return new Promise.PromiseInspection(this._target());
  2545. };
  2546. var apiRejection = function(msg) {
  2547. return Promise.reject(new TypeError(msg));
  2548. };
  2549. function Proxyable() {}
  2550. var UNDEFINED_BINDING = {};
  2551. var util = _dereq_("./util");
  2552. util.setReflectHandler(reflectHandler);
  2553. var getDomain = function() {
  2554. var domain = process.domain;
  2555. if (domain === undefined) {
  2556. return null;
  2557. }
  2558. return domain;
  2559. };
  2560. var getContextDefault = function() {
  2561. return null;
  2562. };
  2563. var getContextDomain = function() {
  2564. return {
  2565. domain: getDomain(),
  2566. async: null
  2567. };
  2568. };
  2569. var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ?
  2570. _dereq_("async_hooks").AsyncResource : null;
  2571. var getContextAsyncHooks = function() {
  2572. return {
  2573. domain: getDomain(),
  2574. async: new AsyncResource("Bluebird::Promise")
  2575. };
  2576. };
  2577. var getContext = util.isNode ? getContextDomain : getContextDefault;
  2578. util.notEnumerableProp(Promise, "_getContext", getContext);
  2579. var enableAsyncHooks = function() {
  2580. getContext = getContextAsyncHooks;
  2581. util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks);
  2582. };
  2583. var disableAsyncHooks = function() {
  2584. getContext = getContextDomain;
  2585. util.notEnumerableProp(Promise, "_getContext", getContextDomain);
  2586. };
  2587. var es5 = _dereq_("./es5");
  2588. var Async = _dereq_("./async");
  2589. var async = new Async();
  2590. es5.defineProperty(Promise, "_async", {value: async});
  2591. var errors = _dereq_("./errors");
  2592. var TypeError = Promise.TypeError = errors.TypeError;
  2593. Promise.RangeError = errors.RangeError;
  2594. var CancellationError = Promise.CancellationError = errors.CancellationError;
  2595. Promise.TimeoutError = errors.TimeoutError;
  2596. Promise.OperationalError = errors.OperationalError;
  2597. Promise.RejectionError = errors.OperationalError;
  2598. Promise.AggregateError = errors.AggregateError;
  2599. var INTERNAL = function(){};
  2600. var APPLY = {};
  2601. var NEXT_FILTER = {};
  2602. var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
  2603. var PromiseArray =
  2604. _dereq_("./promise_array")(Promise, INTERNAL,
  2605. tryConvertToPromise, apiRejection, Proxyable);
  2606. var Context = _dereq_("./context")(Promise);
  2607. /*jshint unused:false*/
  2608. var createContext = Context.create;
  2609. var debug = _dereq_("./debuggability")(Promise, Context,
  2610. enableAsyncHooks, disableAsyncHooks);
  2611. var CapturedTrace = debug.CapturedTrace;
  2612. var PassThroughHandlerContext =
  2613. _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
  2614. var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
  2615. var nodebackForPromise = _dereq_("./nodeback");
  2616. var errorObj = util.errorObj;
  2617. var tryCatch = util.tryCatch;
  2618. function check(self, executor) {
  2619. if (self == null || self.constructor !== Promise) {
  2620. throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  2621. }
  2622. if (typeof executor !== "function") {
  2623. throw new TypeError("expecting a function but got " + util.classString(executor));
  2624. }
  2625. }
  2626. function Promise(executor) {
  2627. if (executor !== INTERNAL) {
  2628. check(this, executor);
  2629. }
  2630. this._bitField = 0;
  2631. this._fulfillmentHandler0 = undefined;
  2632. this._rejectionHandler0 = undefined;
  2633. this._promise0 = undefined;
  2634. this._receiver0 = undefined;
  2635. this._resolveFromExecutor(executor);
  2636. this._promiseCreated();
  2637. this._fireEvent("promiseCreated", this);
  2638. }
  2639. Promise.prototype.toString = function () {
  2640. return "[object Promise]";
  2641. };
  2642. Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
  2643. var len = arguments.length;
  2644. if (len > 1) {
  2645. var catchInstances = new Array(len - 1),
  2646. j = 0, i;
  2647. for (i = 0; i < len - 1; ++i) {
  2648. var item = arguments[i];
  2649. if (util.isObject(item)) {
  2650. catchInstances[j++] = item;
  2651. } else {
  2652. return apiRejection("Catch statement predicate: " +
  2653. "expecting an object but got " + util.classString(item));
  2654. }
  2655. }
  2656. catchInstances.length = j;
  2657. fn = arguments[i];
  2658. if (typeof fn !== "function") {
  2659. throw new TypeError("The last argument to .catch() " +
  2660. "must be a function, got " + util.toString(fn));
  2661. }
  2662. return this.then(undefined, catchFilter(catchInstances, fn, this));
  2663. }
  2664. return this.then(undefined, fn);
  2665. };
  2666. Promise.prototype.reflect = function () {
  2667. return this._then(reflectHandler,
  2668. reflectHandler, undefined, this, undefined);
  2669. };
  2670. Promise.prototype.then = function (didFulfill, didReject) {
  2671. if (debug.warnings() && arguments.length > 0 &&
  2672. typeof didFulfill !== "function" &&
  2673. typeof didReject !== "function") {
  2674. var msg = ".then() only accepts functions but was passed: " +
  2675. util.classString(didFulfill);
  2676. if (arguments.length > 1) {
  2677. msg += ", " + util.classString(didReject);
  2678. }
  2679. this._warn(msg);
  2680. }
  2681. return this._then(didFulfill, didReject, undefined, undefined, undefined);
  2682. };
  2683. Promise.prototype.done = function (didFulfill, didReject) {
  2684. var promise =
  2685. this._then(didFulfill, didReject, undefined, undefined, undefined);
  2686. promise._setIsFinal();
  2687. };
  2688. Promise.prototype.spread = function (fn) {
  2689. if (typeof fn !== "function") {
  2690. return apiRejection("expecting a function but got " + util.classString(fn));
  2691. }
  2692. return this.all()._then(fn, undefined, undefined, APPLY, undefined);
  2693. };
  2694. Promise.prototype.toJSON = function () {
  2695. var ret = {
  2696. isFulfilled: false,
  2697. isRejected: false,
  2698. fulfillmentValue: undefined,
  2699. rejectionReason: undefined
  2700. };
  2701. if (this.isFulfilled()) {
  2702. ret.fulfillmentValue = this.value();
  2703. ret.isFulfilled = true;
  2704. } else if (this.isRejected()) {
  2705. ret.rejectionReason = this.reason();
  2706. ret.isRejected = true;
  2707. }
  2708. return ret;
  2709. };
  2710. Promise.prototype.all = function () {
  2711. if (arguments.length > 0) {
  2712. this._warn(".all() was passed arguments but it does not take any");
  2713. }
  2714. return new PromiseArray(this).promise();
  2715. };
  2716. Promise.prototype.error = function (fn) {
  2717. return this.caught(util.originatesFromRejection, fn);
  2718. };
  2719. Promise.getNewLibraryCopy = module.exports;
  2720. Promise.is = function (val) {
  2721. return val instanceof Promise;
  2722. };
  2723. Promise.fromNode = Promise.fromCallback = function(fn) {
  2724. var ret = new Promise(INTERNAL);
  2725. ret._captureStackTrace();
  2726. var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
  2727. : false;
  2728. var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
  2729. if (result === errorObj) {
  2730. ret._rejectCallback(result.e, true);
  2731. }
  2732. if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
  2733. return ret;
  2734. };
  2735. Promise.all = function (promises) {
  2736. return new PromiseArray(promises).promise();
  2737. };
  2738. Promise.cast = function (obj) {
  2739. var ret = tryConvertToPromise(obj);
  2740. if (!(ret instanceof Promise)) {
  2741. ret = new Promise(INTERNAL);
  2742. ret._captureStackTrace();
  2743. ret._setFulfilled();
  2744. ret._rejectionHandler0 = obj;
  2745. }
  2746. return ret;
  2747. };
  2748. Promise.resolve = Promise.fulfilled = Promise.cast;
  2749. Promise.reject = Promise.rejected = function (reason) {
  2750. var ret = new Promise(INTERNAL);
  2751. ret._captureStackTrace();
  2752. ret._rejectCallback(reason, true);
  2753. return ret;
  2754. };
  2755. Promise.setScheduler = function(fn) {
  2756. if (typeof fn !== "function") {
  2757. throw new TypeError("expecting a function but got " + util.classString(fn));
  2758. }
  2759. return async.setScheduler(fn);
  2760. };
  2761. Promise.prototype._then = function (
  2762. didFulfill,
  2763. didReject,
  2764. _, receiver,
  2765. internalData
  2766. ) {
  2767. var haveInternalData = internalData !== undefined;
  2768. var promise = haveInternalData ? internalData : new Promise(INTERNAL);
  2769. var target = this._target();
  2770. var bitField = target._bitField;
  2771. if (!haveInternalData) {
  2772. promise._propagateFrom(this, 3);
  2773. promise._captureStackTrace();
  2774. if (receiver === undefined &&
  2775. ((this._bitField & 2097152) !== 0)) {
  2776. if (!((bitField & 50397184) === 0)) {
  2777. receiver = this._boundValue();
  2778. } else {
  2779. receiver = target === this ? undefined : this._boundTo;
  2780. }
  2781. }
  2782. this._fireEvent("promiseChained", this, promise);
  2783. }
  2784. var context = getContext();
  2785. if (!((bitField & 50397184) === 0)) {
  2786. var handler, value, settler = target._settlePromiseCtx;
  2787. if (((bitField & 33554432) !== 0)) {
  2788. value = target._rejectionHandler0;
  2789. handler = didFulfill;
  2790. } else if (((bitField & 16777216) !== 0)) {
  2791. value = target._fulfillmentHandler0;
  2792. handler = didReject;
  2793. target._unsetRejectionIsUnhandled();
  2794. } else {
  2795. settler = target._settlePromiseLateCancellationObserver;
  2796. value = new CancellationError("late cancellation observer");
  2797. target._attachExtraTrace(value);
  2798. handler = didReject;
  2799. }
  2800. async.invoke(settler, target, {
  2801. handler: util.contextBind(context, handler),
  2802. promise: promise,
  2803. receiver: receiver,
  2804. value: value
  2805. });
  2806. } else {
  2807. target._addCallbacks(didFulfill, didReject, promise,
  2808. receiver, context);
  2809. }
  2810. return promise;
  2811. };
  2812. Promise.prototype._length = function () {
  2813. return this._bitField & 65535;
  2814. };
  2815. Promise.prototype._isFateSealed = function () {
  2816. return (this._bitField & 117506048) !== 0;
  2817. };
  2818. Promise.prototype._isFollowing = function () {
  2819. return (this._bitField & 67108864) === 67108864;
  2820. };
  2821. Promise.prototype._setLength = function (len) {
  2822. this._bitField = (this._bitField & -65536) |
  2823. (len & 65535);
  2824. };
  2825. Promise.prototype._setFulfilled = function () {
  2826. this._bitField = this._bitField | 33554432;
  2827. this._fireEvent("promiseFulfilled", this);
  2828. };
  2829. Promise.prototype._setRejected = function () {
  2830. this._bitField = this._bitField | 16777216;
  2831. this._fireEvent("promiseRejected", this);
  2832. };
  2833. Promise.prototype._setFollowing = function () {
  2834. this._bitField = this._bitField | 67108864;
  2835. this._fireEvent("promiseResolved", this);
  2836. };
  2837. Promise.prototype._setIsFinal = function () {
  2838. this._bitField = this._bitField | 4194304;
  2839. };
  2840. Promise.prototype._isFinal = function () {
  2841. return (this._bitField & 4194304) > 0;
  2842. };
  2843. Promise.prototype._unsetCancelled = function() {
  2844. this._bitField = this._bitField & (~65536);
  2845. };
  2846. Promise.prototype._setCancelled = function() {
  2847. this._bitField = this._bitField | 65536;
  2848. this._fireEvent("promiseCancelled", this);
  2849. };
  2850. Promise.prototype._setWillBeCancelled = function() {
  2851. this._bitField = this._bitField | 8388608;
  2852. };
  2853. Promise.prototype._setAsyncGuaranteed = function() {
  2854. if (async.hasCustomScheduler()) return;
  2855. var bitField = this._bitField;
  2856. this._bitField = bitField |
  2857. (((bitField & 536870912) >> 2) ^
  2858. 134217728);
  2859. };
  2860. Promise.prototype._setNoAsyncGuarantee = function() {
  2861. this._bitField = (this._bitField | 536870912) &
  2862. (~134217728);
  2863. };
  2864. Promise.prototype._receiverAt = function (index) {
  2865. var ret = index === 0 ? this._receiver0 : this[
  2866. index * 4 - 4 + 3];
  2867. if (ret === UNDEFINED_BINDING) {
  2868. return undefined;
  2869. } else if (ret === undefined && this._isBound()) {
  2870. return this._boundValue();
  2871. }
  2872. return ret;
  2873. };
  2874. Promise.prototype._promiseAt = function (index) {
  2875. return this[
  2876. index * 4 - 4 + 2];
  2877. };
  2878. Promise.prototype._fulfillmentHandlerAt = function (index) {
  2879. return this[
  2880. index * 4 - 4 + 0];
  2881. };
  2882. Promise.prototype._rejectionHandlerAt = function (index) {
  2883. return this[
  2884. index * 4 - 4 + 1];
  2885. };
  2886. Promise.prototype._boundValue = function() {};
  2887. Promise.prototype._migrateCallback0 = function (follower) {
  2888. var bitField = follower._bitField;
  2889. var fulfill = follower._fulfillmentHandler0;
  2890. var reject = follower._rejectionHandler0;
  2891. var promise = follower._promise0;
  2892. var receiver = follower._receiverAt(0);
  2893. if (receiver === undefined) receiver = UNDEFINED_BINDING;
  2894. this._addCallbacks(fulfill, reject, promise, receiver, null);
  2895. };
  2896. Promise.prototype._migrateCallbackAt = function (follower, index) {
  2897. var fulfill = follower._fulfillmentHandlerAt(index);
  2898. var reject = follower._rejectionHandlerAt(index);
  2899. var promise = follower._promiseAt(index);
  2900. var receiver = follower._receiverAt(index);
  2901. if (receiver === undefined) receiver = UNDEFINED_BINDING;
  2902. this._addCallbacks(fulfill, reject, promise, receiver, null);
  2903. };
  2904. Promise.prototype._addCallbacks = function (
  2905. fulfill,
  2906. reject,
  2907. promise,
  2908. receiver,
  2909. context
  2910. ) {
  2911. var index = this._length();
  2912. if (index >= 65535 - 4) {
  2913. index = 0;
  2914. this._setLength(0);
  2915. }
  2916. if (index === 0) {
  2917. this._promise0 = promise;
  2918. this._receiver0 = receiver;
  2919. if (typeof fulfill === "function") {
  2920. this._fulfillmentHandler0 = util.contextBind(context, fulfill);
  2921. }
  2922. if (typeof reject === "function") {
  2923. this._rejectionHandler0 = util.contextBind(context, reject);
  2924. }
  2925. } else {
  2926. var base = index * 4 - 4;
  2927. this[base + 2] = promise;
  2928. this[base + 3] = receiver;
  2929. if (typeof fulfill === "function") {
  2930. this[base + 0] =
  2931. util.contextBind(context, fulfill);
  2932. }
  2933. if (typeof reject === "function") {
  2934. this[base + 1] =
  2935. util.contextBind(context, reject);
  2936. }
  2937. }
  2938. this._setLength(index + 1);
  2939. return index;
  2940. };
  2941. Promise.prototype._proxy = function (proxyable, arg) {
  2942. this._addCallbacks(undefined, undefined, arg, proxyable, null);
  2943. };
  2944. Promise.prototype._resolveCallback = function(value, shouldBind) {
  2945. if (((this._bitField & 117506048) !== 0)) return;
  2946. if (value === this)
  2947. return this._rejectCallback(makeSelfResolutionError(), false);
  2948. var maybePromise = tryConvertToPromise(value, this);
  2949. if (!(maybePromise instanceof Promise)) return this._fulfill(value);
  2950. if (shouldBind) this._propagateFrom(maybePromise, 2);
  2951. var promise = maybePromise._target();
  2952. if (promise === this) {
  2953. this._reject(makeSelfResolutionError());
  2954. return;
  2955. }
  2956. var bitField = promise._bitField;
  2957. if (((bitField & 50397184) === 0)) {
  2958. var len = this._length();
  2959. if (len > 0) promise._migrateCallback0(this);
  2960. for (var i = 1; i < len; ++i) {
  2961. promise._migrateCallbackAt(this, i);
  2962. }
  2963. this._setFollowing();
  2964. this._setLength(0);
  2965. this._setFollowee(maybePromise);
  2966. } else if (((bitField & 33554432) !== 0)) {
  2967. this._fulfill(promise._value());
  2968. } else if (((bitField & 16777216) !== 0)) {
  2969. this._reject(promise._reason());
  2970. } else {
  2971. var reason = new CancellationError("late cancellation observer");
  2972. promise._attachExtraTrace(reason);
  2973. this._reject(reason);
  2974. }
  2975. };
  2976. Promise.prototype._rejectCallback =
  2977. function(reason, synchronous, ignoreNonErrorWarnings) {
  2978. var trace = util.ensureErrorObject(reason);
  2979. var hasStack = trace === reason;
  2980. if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
  2981. var message = "a promise was rejected with a non-error: " +
  2982. util.classString(reason);
  2983. this._warn(message, true);
  2984. }
  2985. this._attachExtraTrace(trace, synchronous ? hasStack : false);
  2986. this._reject(reason);
  2987. };
  2988. Promise.prototype._resolveFromExecutor = function (executor) {
  2989. if (executor === INTERNAL) return;
  2990. var promise = this;
  2991. this._captureStackTrace();
  2992. this._pushContext();
  2993. var synchronous = true;
  2994. var r = this._execute(executor, function(value) {
  2995. promise._resolveCallback(value);
  2996. }, function (reason) {
  2997. promise._rejectCallback(reason, synchronous);
  2998. });
  2999. synchronous = false;
  3000. this._popContext();
  3001. if (r !== undefined) {
  3002. promise._rejectCallback(r, true);
  3003. }
  3004. };
  3005. Promise.prototype._settlePromiseFromHandler = function (
  3006. handler, receiver, value, promise
  3007. ) {
  3008. var bitField = promise._bitField;
  3009. if (((bitField & 65536) !== 0)) return;
  3010. promise._pushContext();
  3011. var x;
  3012. if (receiver === APPLY) {
  3013. if (!value || typeof value.length !== "number") {
  3014. x = errorObj;
  3015. x.e = new TypeError("cannot .spread() a non-array: " +
  3016. util.classString(value));
  3017. } else {
  3018. x = tryCatch(handler).apply(this._boundValue(), value);
  3019. }
  3020. } else {
  3021. x = tryCatch(handler).call(receiver, value);
  3022. }
  3023. var promiseCreated = promise._popContext();
  3024. bitField = promise._bitField;
  3025. if (((bitField & 65536) !== 0)) return;
  3026. if (x === NEXT_FILTER) {
  3027. promise._reject(value);
  3028. } else if (x === errorObj) {
  3029. promise._rejectCallback(x.e, false);
  3030. } else {
  3031. debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
  3032. promise._resolveCallback(x);
  3033. }
  3034. };
  3035. Promise.prototype._target = function() {
  3036. var ret = this;
  3037. while (ret._isFollowing()) ret = ret._followee();
  3038. return ret;
  3039. };
  3040. Promise.prototype._followee = function() {
  3041. return this._rejectionHandler0;
  3042. };
  3043. Promise.prototype._setFollowee = function(promise) {
  3044. this._rejectionHandler0 = promise;
  3045. };
  3046. Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
  3047. var isPromise = promise instanceof Promise;
  3048. var bitField = this._bitField;
  3049. var asyncGuaranteed = ((bitField & 134217728) !== 0);
  3050. if (((bitField & 65536) !== 0)) {
  3051. if (isPromise) promise._invokeInternalOnCancel();
  3052. if (receiver instanceof PassThroughHandlerContext &&
  3053. receiver.isFinallyHandler()) {
  3054. receiver.cancelPromise = promise;
  3055. if (tryCatch(handler).call(receiver, value) === errorObj) {
  3056. promise._reject(errorObj.e);
  3057. }
  3058. } else if (handler === reflectHandler) {
  3059. promise._fulfill(reflectHandler.call(receiver));
  3060. } else if (receiver instanceof Proxyable) {
  3061. receiver._promiseCancelled(promise);
  3062. } else if (isPromise || promise instanceof PromiseArray) {
  3063. promise._cancel();
  3064. } else {
  3065. receiver.cancel();
  3066. }
  3067. } else if (typeof handler === "function") {
  3068. if (!isPromise) {
  3069. handler.call(receiver, value, promise);
  3070. } else {
  3071. if (asyncGuaranteed) promise._setAsyncGuaranteed();
  3072. this._settlePromiseFromHandler(handler, receiver, value, promise);
  3073. }
  3074. } else if (receiver instanceof Proxyable) {
  3075. if (!receiver._isResolved()) {
  3076. if (((bitField & 33554432) !== 0)) {
  3077. receiver._promiseFulfilled(value, promise);
  3078. } else {
  3079. receiver._promiseRejected(value, promise);
  3080. }
  3081. }
  3082. } else if (isPromise) {
  3083. if (asyncGuaranteed) promise._setAsyncGuaranteed();
  3084. if (((bitField & 33554432) !== 0)) {
  3085. promise._fulfill(value);
  3086. } else {
  3087. promise._reject(value);
  3088. }
  3089. }
  3090. };
  3091. Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
  3092. var handler = ctx.handler;
  3093. var promise = ctx.promise;
  3094. var receiver = ctx.receiver;
  3095. var value = ctx.value;
  3096. if (typeof handler === "function") {
  3097. if (!(promise instanceof Promise)) {
  3098. handler.call(receiver, value, promise);
  3099. } else {
  3100. this._settlePromiseFromHandler(handler, receiver, value, promise);
  3101. }
  3102. } else if (promise instanceof Promise) {
  3103. promise._reject(value);
  3104. }
  3105. };
  3106. Promise.prototype._settlePromiseCtx = function(ctx) {
  3107. this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
  3108. };
  3109. Promise.prototype._settlePromise0 = function(handler, value, bitField) {
  3110. var promise = this._promise0;
  3111. var receiver = this._receiverAt(0);
  3112. this._promise0 = undefined;
  3113. this._receiver0 = undefined;
  3114. this._settlePromise(promise, handler, receiver, value);
  3115. };
  3116. Promise.prototype._clearCallbackDataAtIndex = function(index) {
  3117. var base = index * 4 - 4;
  3118. this[base + 2] =
  3119. this[base + 3] =
  3120. this[base + 0] =
  3121. this[base + 1] = undefined;
  3122. };
  3123. Promise.prototype._fulfill = function (value) {
  3124. var bitField = this._bitField;
  3125. if (((bitField & 117506048) >>> 16)) return;
  3126. if (value === this) {
  3127. var err = makeSelfResolutionError();
  3128. this._attachExtraTrace(err);
  3129. return this._reject(err);
  3130. }
  3131. this._setFulfilled();
  3132. this._rejectionHandler0 = value;
  3133. if ((bitField & 65535) > 0) {
  3134. if (((bitField & 134217728) !== 0)) {
  3135. this._settlePromises();
  3136. } else {
  3137. async.settlePromises(this);
  3138. }
  3139. this._dereferenceTrace();
  3140. }
  3141. };
  3142. Promise.prototype._reject = function (reason) {
  3143. var bitField = this._bitField;
  3144. if (((bitField & 117506048) >>> 16)) return;
  3145. this._setRejected();
  3146. this._fulfillmentHandler0 = reason;
  3147. if (this._isFinal()) {
  3148. return async.fatalError(reason, util.isNode);
  3149. }
  3150. if ((bitField & 65535) > 0) {
  3151. async.settlePromises(this);
  3152. } else {
  3153. this._ensurePossibleRejectionHandled();
  3154. }
  3155. };
  3156. Promise.prototype._fulfillPromises = function (len, value) {
  3157. for (var i = 1; i < len; i++) {
  3158. var handler = this._fulfillmentHandlerAt(i);
  3159. var promise = this._promiseAt(i);
  3160. var receiver = this._receiverAt(i);
  3161. this._clearCallbackDataAtIndex(i);
  3162. this._settlePromise(promise, handler, receiver, value);
  3163. }
  3164. };
  3165. Promise.prototype._rejectPromises = function (len, reason) {
  3166. for (var i = 1; i < len; i++) {
  3167. var handler = this._rejectionHandlerAt(i);
  3168. var promise = this._promiseAt(i);
  3169. var receiver = this._receiverAt(i);
  3170. this._clearCallbackDataAtIndex(i);
  3171. this._settlePromise(promise, handler, receiver, reason);
  3172. }
  3173. };
  3174. Promise.prototype._settlePromises = function () {
  3175. var bitField = this._bitField;
  3176. var len = (bitField & 65535);
  3177. if (len > 0) {
  3178. if (((bitField & 16842752) !== 0)) {
  3179. var reason = this._fulfillmentHandler0;
  3180. this._settlePromise0(this._rejectionHandler0, reason, bitField);
  3181. this._rejectPromises(len, reason);
  3182. } else {
  3183. var value = this._rejectionHandler0;
  3184. this._settlePromise0(this._fulfillmentHandler0, value, bitField);
  3185. this._fulfillPromises(len, value);
  3186. }
  3187. this._setLength(0);
  3188. }
  3189. this._clearCancellationData();
  3190. };
  3191. Promise.prototype._settledValue = function() {
  3192. var bitField = this._bitField;
  3193. if (((bitField & 33554432) !== 0)) {
  3194. return this._rejectionHandler0;
  3195. } else if (((bitField & 16777216) !== 0)) {
  3196. return this._fulfillmentHandler0;
  3197. }
  3198. };
  3199. if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
  3200. es5.defineProperty(Promise.prototype, Symbol.toStringTag, {
  3201. get: function () {
  3202. return "Object";
  3203. }
  3204. });
  3205. }
  3206. function deferResolve(v) {this.promise._resolveCallback(v);}
  3207. function deferReject(v) {this.promise._rejectCallback(v, false);}
  3208. Promise.defer = Promise.pending = function() {
  3209. debug.deprecated("Promise.defer", "new Promise");
  3210. var promise = new Promise(INTERNAL);
  3211. return {
  3212. promise: promise,
  3213. resolve: deferResolve,
  3214. reject: deferReject
  3215. };
  3216. };
  3217. util.notEnumerableProp(Promise,
  3218. "_makeSelfResolutionError",
  3219. makeSelfResolutionError);
  3220. _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
  3221. debug);
  3222. _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
  3223. _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
  3224. _dereq_("./direct_resolve")(Promise);
  3225. _dereq_("./synchronous_inspection")(Promise);
  3226. _dereq_("./join")(
  3227. Promise, PromiseArray, tryConvertToPromise, INTERNAL, async);
  3228. Promise.Promise = Promise;
  3229. Promise.version = "3.7.2";
  3230. _dereq_('./call_get.js')(Promise);
  3231. _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
  3232. _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
  3233. _dereq_('./nodeify.js')(Promise);
  3234. _dereq_('./promisify.js')(Promise, INTERNAL);
  3235. _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
  3236. _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
  3237. _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
  3238. _dereq_('./settle.js')(Promise, PromiseArray, debug);
  3239. _dereq_('./some.js')(Promise, PromiseArray, apiRejection);
  3240. _dereq_('./timers.js')(Promise, INTERNAL, debug);
  3241. _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
  3242. _dereq_('./any.js')(Promise);
  3243. _dereq_('./each.js')(Promise, INTERNAL);
  3244. _dereq_('./filter.js')(Promise, INTERNAL);
  3245. util.toFastProperties(Promise);
  3246. util.toFastProperties(Promise.prototype);
  3247. function fillTypes(value) {
  3248. var p = new Promise(INTERNAL);
  3249. p._fulfillmentHandler0 = value;
  3250. p._rejectionHandler0 = value;
  3251. p._promise0 = value;
  3252. p._receiver0 = value;
  3253. }
  3254. // Complete slack tracking, opt out of field-type tracking and
  3255. // stabilize map
  3256. fillTypes({a: 1});
  3257. fillTypes({b: 2});
  3258. fillTypes({c: 3});
  3259. fillTypes(1);
  3260. fillTypes(function(){});
  3261. fillTypes(undefined);
  3262. fillTypes(false);
  3263. fillTypes(new Promise(INTERNAL));
  3264. debug.setBounds(Async.firstLineError, util.lastLineError);
  3265. return Promise;
  3266. };
  3267. },{"./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,"async_hooks":undefined}],23:[function(_dereq_,module,exports){
  3268. "use strict";
  3269. module.exports = function(Promise, INTERNAL, tryConvertToPromise,
  3270. apiRejection, Proxyable) {
  3271. var util = _dereq_("./util");
  3272. var isArray = util.isArray;
  3273. function toResolutionValue(val) {
  3274. switch(val) {
  3275. case -2: return [];
  3276. case -3: return {};
  3277. case -6: return new Map();
  3278. }
  3279. }
  3280. function PromiseArray(values) {
  3281. var promise = this._promise = new Promise(INTERNAL);
  3282. if (values instanceof Promise) {
  3283. promise._propagateFrom(values, 3);
  3284. values.suppressUnhandledRejections();
  3285. }
  3286. promise._setOnCancel(this);
  3287. this._values = values;
  3288. this._length = 0;
  3289. this._totalResolved = 0;
  3290. this._init(undefined, -2);
  3291. }
  3292. util.inherits(PromiseArray, Proxyable);
  3293. PromiseArray.prototype.length = function () {
  3294. return this._length;
  3295. };
  3296. PromiseArray.prototype.promise = function () {
  3297. return this._promise;
  3298. };
  3299. PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
  3300. var values = tryConvertToPromise(this._values, this._promise);
  3301. if (values instanceof Promise) {
  3302. values = values._target();
  3303. var bitField = values._bitField;
  3304. ;
  3305. this._values = values;
  3306. if (((bitField & 50397184) === 0)) {
  3307. this._promise._setAsyncGuaranteed();
  3308. return values._then(
  3309. init,
  3310. this._reject,
  3311. undefined,
  3312. this,
  3313. resolveValueIfEmpty
  3314. );
  3315. } else if (((bitField & 33554432) !== 0)) {
  3316. values = values._value();
  3317. } else if (((bitField & 16777216) !== 0)) {
  3318. return this._reject(values._reason());
  3319. } else {
  3320. return this._cancel();
  3321. }
  3322. }
  3323. values = util.asArray(values);
  3324. if (values === null) {
  3325. var err = apiRejection(
  3326. "expecting an array or an iterable object but got " + util.classString(values)).reason();
  3327. this._promise._rejectCallback(err, false);
  3328. return;
  3329. }
  3330. if (values.length === 0) {
  3331. if (resolveValueIfEmpty === -5) {
  3332. this._resolveEmptyArray();
  3333. }
  3334. else {
  3335. this._resolve(toResolutionValue(resolveValueIfEmpty));
  3336. }
  3337. return;
  3338. }
  3339. this._iterate(values);
  3340. };
  3341. PromiseArray.prototype._iterate = function(values) {
  3342. var len = this.getActualLength(values.length);
  3343. this._length = len;
  3344. this._values = this.shouldCopyValues() ? new Array(len) : this._values;
  3345. var result = this._promise;
  3346. var isResolved = false;
  3347. var bitField = null;
  3348. for (var i = 0; i < len; ++i) {
  3349. var maybePromise = tryConvertToPromise(values[i], result);
  3350. if (maybePromise instanceof Promise) {
  3351. maybePromise = maybePromise._target();
  3352. bitField = maybePromise._bitField;
  3353. } else {
  3354. bitField = null;
  3355. }
  3356. if (isResolved) {
  3357. if (bitField !== null) {
  3358. maybePromise.suppressUnhandledRejections();
  3359. }
  3360. } else if (bitField !== null) {
  3361. if (((bitField & 50397184) === 0)) {
  3362. maybePromise._proxy(this, i);
  3363. this._values[i] = maybePromise;
  3364. } else if (((bitField & 33554432) !== 0)) {
  3365. isResolved = this._promiseFulfilled(maybePromise._value(), i);
  3366. } else if (((bitField & 16777216) !== 0)) {
  3367. isResolved = this._promiseRejected(maybePromise._reason(), i);
  3368. } else {
  3369. isResolved = this._promiseCancelled(i);
  3370. }
  3371. } else {
  3372. isResolved = this._promiseFulfilled(maybePromise, i);
  3373. }
  3374. }
  3375. if (!isResolved) result._setAsyncGuaranteed();
  3376. };
  3377. PromiseArray.prototype._isResolved = function () {
  3378. return this._values === null;
  3379. };
  3380. PromiseArray.prototype._resolve = function (value) {
  3381. this._values = null;
  3382. this._promise._fulfill(value);
  3383. };
  3384. PromiseArray.prototype._cancel = function() {
  3385. if (this._isResolved() || !this._promise._isCancellable()) return;
  3386. this._values = null;
  3387. this._promise._cancel();
  3388. };
  3389. PromiseArray.prototype._reject = function (reason) {
  3390. this._values = null;
  3391. this._promise._rejectCallback(reason, false);
  3392. };
  3393. PromiseArray.prototype._promiseFulfilled = function (value, index) {
  3394. this._values[index] = value;
  3395. var totalResolved = ++this._totalResolved;
  3396. if (totalResolved >= this._length) {
  3397. this._resolve(this._values);
  3398. return true;
  3399. }
  3400. return false;
  3401. };
  3402. PromiseArray.prototype._promiseCancelled = function() {
  3403. this._cancel();
  3404. return true;
  3405. };
  3406. PromiseArray.prototype._promiseRejected = function (reason) {
  3407. this._totalResolved++;
  3408. this._reject(reason);
  3409. return true;
  3410. };
  3411. PromiseArray.prototype._resultCancelled = function() {
  3412. if (this._isResolved()) return;
  3413. var values = this._values;
  3414. this._cancel();
  3415. if (values instanceof Promise) {
  3416. values.cancel();
  3417. } else {
  3418. for (var i = 0; i < values.length; ++i) {
  3419. if (values[i] instanceof Promise) {
  3420. values[i].cancel();
  3421. }
  3422. }
  3423. }
  3424. };
  3425. PromiseArray.prototype.shouldCopyValues = function () {
  3426. return true;
  3427. };
  3428. PromiseArray.prototype.getActualLength = function (len) {
  3429. return len;
  3430. };
  3431. return PromiseArray;
  3432. };
  3433. },{"./util":36}],24:[function(_dereq_,module,exports){
  3434. "use strict";
  3435. module.exports = function(Promise, INTERNAL) {
  3436. var THIS = {};
  3437. var util = _dereq_("./util");
  3438. var nodebackForPromise = _dereq_("./nodeback");
  3439. var withAppended = util.withAppended;
  3440. var maybeWrapAsError = util.maybeWrapAsError;
  3441. var canEvaluate = util.canEvaluate;
  3442. var TypeError = _dereq_("./errors").TypeError;
  3443. var defaultSuffix = "Async";
  3444. var defaultPromisified = {__isPromisified__: true};
  3445. var noCopyProps = [
  3446. "arity", "length",
  3447. "name",
  3448. "arguments",
  3449. "caller",
  3450. "callee",
  3451. "prototype",
  3452. "__isPromisified__"
  3453. ];
  3454. var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
  3455. var defaultFilter = function(name) {
  3456. return util.isIdentifier(name) &&
  3457. name.charAt(0) !== "_" &&
  3458. name !== "constructor";
  3459. };
  3460. function propsFilter(key) {
  3461. return !noCopyPropsPattern.test(key);
  3462. }
  3463. function isPromisified(fn) {
  3464. try {
  3465. return fn.__isPromisified__ === true;
  3466. }
  3467. catch (e) {
  3468. return false;
  3469. }
  3470. }
  3471. function hasPromisified(obj, key, suffix) {
  3472. var val = util.getDataPropertyOrDefault(obj, key + suffix,
  3473. defaultPromisified);
  3474. return val ? isPromisified(val) : false;
  3475. }
  3476. function checkValid(ret, suffix, suffixRegexp) {
  3477. for (var i = 0; i < ret.length; i += 2) {
  3478. var key = ret[i];
  3479. if (suffixRegexp.test(key)) {
  3480. var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
  3481. for (var j = 0; j < ret.length; j += 2) {
  3482. if (ret[j] === keyWithoutAsyncSuffix) {
  3483. throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
  3484. .replace("%s", suffix));
  3485. }
  3486. }
  3487. }
  3488. }
  3489. }
  3490. function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
  3491. var keys = util.inheritedDataKeys(obj);
  3492. var ret = [];
  3493. for (var i = 0; i < keys.length; ++i) {
  3494. var key = keys[i];
  3495. var value = obj[key];
  3496. var passesDefaultFilter = filter === defaultFilter
  3497. ? true : defaultFilter(key, value, obj);
  3498. if (typeof value === "function" &&
  3499. !isPromisified(value) &&
  3500. !hasPromisified(obj, key, suffix) &&
  3501. filter(key, value, obj, passesDefaultFilter)) {
  3502. ret.push(key, value);
  3503. }
  3504. }
  3505. checkValid(ret, suffix, suffixRegexp);
  3506. return ret;
  3507. }
  3508. var escapeIdentRegex = function(str) {
  3509. return str.replace(/([$])/, "\\$");
  3510. };
  3511. var makeNodePromisifiedEval;
  3512. if (!true) {
  3513. var switchCaseArgumentOrder = function(likelyArgumentCount) {
  3514. var ret = [likelyArgumentCount];
  3515. var min = Math.max(0, likelyArgumentCount - 1 - 3);
  3516. for(var i = likelyArgumentCount - 1; i >= min; --i) {
  3517. ret.push(i);
  3518. }
  3519. for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
  3520. ret.push(i);
  3521. }
  3522. return ret;
  3523. };
  3524. var argumentSequence = function(argumentCount) {
  3525. return util.filledRange(argumentCount, "_arg", "");
  3526. };
  3527. var parameterDeclaration = function(parameterCount) {
  3528. return util.filledRange(
  3529. Math.max(parameterCount, 3), "_arg", "");
  3530. };
  3531. var parameterCount = function(fn) {
  3532. if (typeof fn.length === "number") {
  3533. return Math.max(Math.min(fn.length, 1023 + 1), 0);
  3534. }
  3535. return 0;
  3536. };
  3537. makeNodePromisifiedEval =
  3538. function(callback, receiver, originalName, fn, _, multiArgs) {
  3539. var newParameterCount = Math.max(0, parameterCount(fn) - 1);
  3540. var argumentOrder = switchCaseArgumentOrder(newParameterCount);
  3541. var shouldProxyThis = typeof callback === "string" || receiver === THIS;
  3542. function generateCallForArgumentCount(count) {
  3543. var args = argumentSequence(count).join(", ");
  3544. var comma = count > 0 ? ", " : "";
  3545. var ret;
  3546. if (shouldProxyThis) {
  3547. ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
  3548. } else {
  3549. ret = receiver === undefined
  3550. ? "ret = callback({{args}}, nodeback); break;\n"
  3551. : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
  3552. }
  3553. return ret.replace("{{args}}", args).replace(", ", comma);
  3554. }
  3555. function generateArgumentSwitchCase() {
  3556. var ret = "";
  3557. for (var i = 0; i < argumentOrder.length; ++i) {
  3558. ret += "case " + argumentOrder[i] +":" +
  3559. generateCallForArgumentCount(argumentOrder[i]);
  3560. }
  3561. ret += " \n\
  3562. default: \n\
  3563. var args = new Array(len + 1); \n\
  3564. var i = 0; \n\
  3565. for (var i = 0; i < len; ++i) { \n\
  3566. args[i] = arguments[i]; \n\
  3567. } \n\
  3568. args[i] = nodeback; \n\
  3569. [CodeForCall] \n\
  3570. break; \n\
  3571. ".replace("[CodeForCall]", (shouldProxyThis
  3572. ? "ret = callback.apply(this, args);\n"
  3573. : "ret = callback.apply(receiver, args);\n"));
  3574. return ret;
  3575. }
  3576. var getFunctionCode = typeof callback === "string"
  3577. ? ("this != null ? this['"+callback+"'] : fn")
  3578. : "fn";
  3579. var body = "'use strict'; \n\
  3580. var ret = function (Parameters) { \n\
  3581. 'use strict'; \n\
  3582. var len = arguments.length; \n\
  3583. var promise = new Promise(INTERNAL); \n\
  3584. promise._captureStackTrace(); \n\
  3585. var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
  3586. var ret; \n\
  3587. var callback = tryCatch([GetFunctionCode]); \n\
  3588. switch(len) { \n\
  3589. [CodeForSwitchCase] \n\
  3590. } \n\
  3591. if (ret === errorObj) { \n\
  3592. promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
  3593. } \n\
  3594. if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
  3595. return promise; \n\
  3596. }; \n\
  3597. notEnumerableProp(ret, '__isPromisified__', true); \n\
  3598. return ret; \n\
  3599. ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
  3600. .replace("[GetFunctionCode]", getFunctionCode);
  3601. body = body.replace("Parameters", parameterDeclaration(newParameterCount));
  3602. return new Function("Promise",
  3603. "fn",
  3604. "receiver",
  3605. "withAppended",
  3606. "maybeWrapAsError",
  3607. "nodebackForPromise",
  3608. "tryCatch",
  3609. "errorObj",
  3610. "notEnumerableProp",
  3611. "INTERNAL",
  3612. body)(
  3613. Promise,
  3614. fn,
  3615. receiver,
  3616. withAppended,
  3617. maybeWrapAsError,
  3618. nodebackForPromise,
  3619. util.tryCatch,
  3620. util.errorObj,
  3621. util.notEnumerableProp,
  3622. INTERNAL);
  3623. };
  3624. }
  3625. function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
  3626. var defaultThis = (function() {return this;})();
  3627. var method = callback;
  3628. if (typeof method === "string") {
  3629. callback = fn;
  3630. }
  3631. function promisified() {
  3632. var _receiver = receiver;
  3633. if (receiver === THIS) _receiver = this;
  3634. var promise = new Promise(INTERNAL);
  3635. promise._captureStackTrace();
  3636. var cb = typeof method === "string" && this !== defaultThis
  3637. ? this[method] : callback;
  3638. var fn = nodebackForPromise(promise, multiArgs);
  3639. try {
  3640. cb.apply(_receiver, withAppended(arguments, fn));
  3641. } catch(e) {
  3642. promise._rejectCallback(maybeWrapAsError(e), true, true);
  3643. }
  3644. if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
  3645. return promise;
  3646. }
  3647. util.notEnumerableProp(promisified, "__isPromisified__", true);
  3648. return promisified;
  3649. }
  3650. var makeNodePromisified = canEvaluate
  3651. ? makeNodePromisifiedEval
  3652. : makeNodePromisifiedClosure;
  3653. function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
  3654. var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
  3655. var methods =
  3656. promisifiableMethods(obj, suffix, suffixRegexp, filter);
  3657. for (var i = 0, len = methods.length; i < len; i+= 2) {
  3658. var key = methods[i];
  3659. var fn = methods[i+1];
  3660. var promisifiedKey = key + suffix;
  3661. if (promisifier === makeNodePromisified) {
  3662. obj[promisifiedKey] =
  3663. makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
  3664. } else {
  3665. var promisified = promisifier(fn, function() {
  3666. return makeNodePromisified(key, THIS, key,
  3667. fn, suffix, multiArgs);
  3668. });
  3669. util.notEnumerableProp(promisified, "__isPromisified__", true);
  3670. obj[promisifiedKey] = promisified;
  3671. }
  3672. }
  3673. util.toFastProperties(obj);
  3674. return obj;
  3675. }
  3676. function promisify(callback, receiver, multiArgs) {
  3677. return makeNodePromisified(callback, receiver, undefined,
  3678. callback, null, multiArgs);
  3679. }
  3680. Promise.promisify = function (fn, options) {
  3681. if (typeof fn !== "function") {
  3682. throw new TypeError("expecting a function but got " + util.classString(fn));
  3683. }
  3684. if (isPromisified(fn)) {
  3685. return fn;
  3686. }
  3687. options = Object(options);
  3688. var receiver = options.context === undefined ? THIS : options.context;
  3689. var multiArgs = !!options.multiArgs;
  3690. var ret = promisify(fn, receiver, multiArgs);
  3691. util.copyDescriptors(fn, ret, propsFilter);
  3692. return ret;
  3693. };
  3694. Promise.promisifyAll = function (target, options) {
  3695. if (typeof target !== "function" && typeof target !== "object") {
  3696. throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  3697. }
  3698. options = Object(options);
  3699. var multiArgs = !!options.multiArgs;
  3700. var suffix = options.suffix;
  3701. if (typeof suffix !== "string") suffix = defaultSuffix;
  3702. var filter = options.filter;
  3703. if (typeof filter !== "function") filter = defaultFilter;
  3704. var promisifier = options.promisifier;
  3705. if (typeof promisifier !== "function") promisifier = makeNodePromisified;
  3706. if (!util.isIdentifier(suffix)) {
  3707. throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  3708. }
  3709. var keys = util.inheritedDataKeys(target);
  3710. for (var i = 0; i < keys.length; ++i) {
  3711. var value = target[keys[i]];
  3712. if (keys[i] !== "constructor" &&
  3713. util.isClass(value)) {
  3714. promisifyAll(value.prototype, suffix, filter, promisifier,
  3715. multiArgs);
  3716. promisifyAll(value, suffix, filter, promisifier, multiArgs);
  3717. }
  3718. }
  3719. return promisifyAll(target, suffix, filter, promisifier, multiArgs);
  3720. };
  3721. };
  3722. },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
  3723. "use strict";
  3724. module.exports = function(
  3725. Promise, PromiseArray, tryConvertToPromise, apiRejection) {
  3726. var util = _dereq_("./util");
  3727. var isObject = util.isObject;
  3728. var es5 = _dereq_("./es5");
  3729. var Es6Map;
  3730. if (typeof Map === "function") Es6Map = Map;
  3731. var mapToEntries = (function() {
  3732. var index = 0;
  3733. var size = 0;
  3734. function extractEntry(value, key) {
  3735. this[index] = value;
  3736. this[index + size] = key;
  3737. index++;
  3738. }
  3739. return function mapToEntries(map) {
  3740. size = map.size;
  3741. index = 0;
  3742. var ret = new Array(map.size * 2);
  3743. map.forEach(extractEntry, ret);
  3744. return ret;
  3745. };
  3746. })();
  3747. var entriesToMap = function(entries) {
  3748. var ret = new Es6Map();
  3749. var length = entries.length / 2 | 0;
  3750. for (var i = 0; i < length; ++i) {
  3751. var key = entries[length + i];
  3752. var value = entries[i];
  3753. ret.set(key, value);
  3754. }
  3755. return ret;
  3756. };
  3757. function PropertiesPromiseArray(obj) {
  3758. var isMap = false;
  3759. var entries;
  3760. if (Es6Map !== undefined && obj instanceof Es6Map) {
  3761. entries = mapToEntries(obj);
  3762. isMap = true;
  3763. } else {
  3764. var keys = es5.keys(obj);
  3765. var len = keys.length;
  3766. entries = new Array(len * 2);
  3767. for (var i = 0; i < len; ++i) {
  3768. var key = keys[i];
  3769. entries[i] = obj[key];
  3770. entries[i + len] = key;
  3771. }
  3772. }
  3773. this.constructor$(entries);
  3774. this._isMap = isMap;
  3775. this._init$(undefined, isMap ? -6 : -3);
  3776. }
  3777. util.inherits(PropertiesPromiseArray, PromiseArray);
  3778. PropertiesPromiseArray.prototype._init = function () {};
  3779. PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
  3780. this._values[index] = value;
  3781. var totalResolved = ++this._totalResolved;
  3782. if (totalResolved >= this._length) {
  3783. var val;
  3784. if (this._isMap) {
  3785. val = entriesToMap(this._values);
  3786. } else {
  3787. val = {};
  3788. var keyOffset = this.length();
  3789. for (var i = 0, len = this.length(); i < len; ++i) {
  3790. val[this._values[i + keyOffset]] = this._values[i];
  3791. }
  3792. }
  3793. this._resolve(val);
  3794. return true;
  3795. }
  3796. return false;
  3797. };
  3798. PropertiesPromiseArray.prototype.shouldCopyValues = function () {
  3799. return false;
  3800. };
  3801. PropertiesPromiseArray.prototype.getActualLength = function (len) {
  3802. return len >> 1;
  3803. };
  3804. function props(promises) {
  3805. var ret;
  3806. var castValue = tryConvertToPromise(promises);
  3807. if (!isObject(castValue)) {
  3808. return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  3809. } else if (castValue instanceof Promise) {
  3810. ret = castValue._then(
  3811. Promise.props, undefined, undefined, undefined, undefined);
  3812. } else {
  3813. ret = new PropertiesPromiseArray(castValue).promise();
  3814. }
  3815. if (castValue instanceof Promise) {
  3816. ret._propagateFrom(castValue, 2);
  3817. }
  3818. return ret;
  3819. }
  3820. Promise.prototype.props = function () {
  3821. return props(this);
  3822. };
  3823. Promise.props = function (promises) {
  3824. return props(promises);
  3825. };
  3826. };
  3827. },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
  3828. "use strict";
  3829. function arrayMove(src, srcIndex, dst, dstIndex, len) {
  3830. for (var j = 0; j < len; ++j) {
  3831. dst[j + dstIndex] = src[j + srcIndex];
  3832. src[j + srcIndex] = void 0;
  3833. }
  3834. }
  3835. function Queue(capacity) {
  3836. this._capacity = capacity;
  3837. this._length = 0;
  3838. this._front = 0;
  3839. }
  3840. Queue.prototype._willBeOverCapacity = function (size) {
  3841. return this._capacity < size;
  3842. };
  3843. Queue.prototype._pushOne = function (arg) {
  3844. var length = this.length();
  3845. this._checkCapacity(length + 1);
  3846. var i = (this._front + length) & (this._capacity - 1);
  3847. this[i] = arg;
  3848. this._length = length + 1;
  3849. };
  3850. Queue.prototype.push = function (fn, receiver, arg) {
  3851. var length = this.length() + 3;
  3852. if (this._willBeOverCapacity(length)) {
  3853. this._pushOne(fn);
  3854. this._pushOne(receiver);
  3855. this._pushOne(arg);
  3856. return;
  3857. }
  3858. var j = this._front + length - 3;
  3859. this._checkCapacity(length);
  3860. var wrapMask = this._capacity - 1;
  3861. this[(j + 0) & wrapMask] = fn;
  3862. this[(j + 1) & wrapMask] = receiver;
  3863. this[(j + 2) & wrapMask] = arg;
  3864. this._length = length;
  3865. };
  3866. Queue.prototype.shift = function () {
  3867. var front = this._front,
  3868. ret = this[front];
  3869. this[front] = undefined;
  3870. this._front = (front + 1) & (this._capacity - 1);
  3871. this._length--;
  3872. return ret;
  3873. };
  3874. Queue.prototype.length = function () {
  3875. return this._length;
  3876. };
  3877. Queue.prototype._checkCapacity = function (size) {
  3878. if (this._capacity < size) {
  3879. this._resizeTo(this._capacity << 1);
  3880. }
  3881. };
  3882. Queue.prototype._resizeTo = function (capacity) {
  3883. var oldCapacity = this._capacity;
  3884. this._capacity = capacity;
  3885. var front = this._front;
  3886. var length = this._length;
  3887. var moveItemsCount = (front + length) & (oldCapacity - 1);
  3888. arrayMove(this, 0, this, oldCapacity, moveItemsCount);
  3889. };
  3890. module.exports = Queue;
  3891. },{}],27:[function(_dereq_,module,exports){
  3892. "use strict";
  3893. module.exports = function(
  3894. Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  3895. var util = _dereq_("./util");
  3896. var raceLater = function (promise) {
  3897. return promise.then(function(array) {
  3898. return race(array, promise);
  3899. });
  3900. };
  3901. function race(promises, parent) {
  3902. var maybePromise = tryConvertToPromise(promises);
  3903. if (maybePromise instanceof Promise) {
  3904. return raceLater(maybePromise);
  3905. } else {
  3906. promises = util.asArray(promises);
  3907. if (promises === null)
  3908. return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
  3909. }
  3910. var ret = new Promise(INTERNAL);
  3911. if (parent !== undefined) {
  3912. ret._propagateFrom(parent, 3);
  3913. }
  3914. var fulfill = ret._fulfill;
  3915. var reject = ret._reject;
  3916. for (var i = 0, len = promises.length; i < len; ++i) {
  3917. var val = promises[i];
  3918. if (val === undefined && !(i in promises)) {
  3919. continue;
  3920. }
  3921. Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
  3922. }
  3923. return ret;
  3924. }
  3925. Promise.race = function (promises) {
  3926. return race(promises, undefined);
  3927. };
  3928. Promise.prototype.race = function () {
  3929. return race(this, undefined);
  3930. };
  3931. };
  3932. },{"./util":36}],28:[function(_dereq_,module,exports){
  3933. "use strict";
  3934. module.exports = function(Promise,
  3935. PromiseArray,
  3936. apiRejection,
  3937. tryConvertToPromise,
  3938. INTERNAL,
  3939. debug) {
  3940. var util = _dereq_("./util");
  3941. var tryCatch = util.tryCatch;
  3942. function ReductionPromiseArray(promises, fn, initialValue, _each) {
  3943. this.constructor$(promises);
  3944. var context = Promise._getContext();
  3945. this._fn = util.contextBind(context, fn);
  3946. if (initialValue !== undefined) {
  3947. initialValue = Promise.resolve(initialValue);
  3948. initialValue._attachCancellationCallback(this);
  3949. }
  3950. this._initialValue = initialValue;
  3951. this._currentCancellable = null;
  3952. if(_each === INTERNAL) {
  3953. this._eachValues = Array(this._length);
  3954. } else if (_each === 0) {
  3955. this._eachValues = null;
  3956. } else {
  3957. this._eachValues = undefined;
  3958. }
  3959. this._promise._captureStackTrace();
  3960. this._init$(undefined, -5);
  3961. }
  3962. util.inherits(ReductionPromiseArray, PromiseArray);
  3963. ReductionPromiseArray.prototype._gotAccum = function(accum) {
  3964. if (this._eachValues !== undefined &&
  3965. this._eachValues !== null &&
  3966. accum !== INTERNAL) {
  3967. this._eachValues.push(accum);
  3968. }
  3969. };
  3970. ReductionPromiseArray.prototype._eachComplete = function(value) {
  3971. if (this._eachValues !== null) {
  3972. this._eachValues.push(value);
  3973. }
  3974. return this._eachValues;
  3975. };
  3976. ReductionPromiseArray.prototype._init = function() {};
  3977. ReductionPromiseArray.prototype._resolveEmptyArray = function() {
  3978. this._resolve(this._eachValues !== undefined ? this._eachValues
  3979. : this._initialValue);
  3980. };
  3981. ReductionPromiseArray.prototype.shouldCopyValues = function () {
  3982. return false;
  3983. };
  3984. ReductionPromiseArray.prototype._resolve = function(value) {
  3985. this._promise._resolveCallback(value);
  3986. this._values = null;
  3987. };
  3988. ReductionPromiseArray.prototype._resultCancelled = function(sender) {
  3989. if (sender === this._initialValue) return this._cancel();
  3990. if (this._isResolved()) return;
  3991. this._resultCancelled$();
  3992. if (this._currentCancellable instanceof Promise) {
  3993. this._currentCancellable.cancel();
  3994. }
  3995. if (this._initialValue instanceof Promise) {
  3996. this._initialValue.cancel();
  3997. }
  3998. };
  3999. ReductionPromiseArray.prototype._iterate = function (values) {
  4000. this._values = values;
  4001. var value;
  4002. var i;
  4003. var length = values.length;
  4004. if (this._initialValue !== undefined) {
  4005. value = this._initialValue;
  4006. i = 0;
  4007. } else {
  4008. value = Promise.resolve(values[0]);
  4009. i = 1;
  4010. }
  4011. this._currentCancellable = value;
  4012. for (var j = i; j < length; ++j) {
  4013. var maybePromise = values[j];
  4014. if (maybePromise instanceof Promise) {
  4015. maybePromise.suppressUnhandledRejections();
  4016. }
  4017. }
  4018. if (!value.isRejected()) {
  4019. for (; i < length; ++i) {
  4020. var ctx = {
  4021. accum: null,
  4022. value: values[i],
  4023. index: i,
  4024. length: length,
  4025. array: this
  4026. };
  4027. value = value._then(gotAccum, undefined, undefined, ctx, undefined);
  4028. if ((i & 127) === 0) {
  4029. value._setNoAsyncGuarantee();
  4030. }
  4031. }
  4032. }
  4033. if (this._eachValues !== undefined) {
  4034. value = value
  4035. ._then(this._eachComplete, undefined, undefined, this, undefined);
  4036. }
  4037. value._then(completed, completed, undefined, value, this);
  4038. };
  4039. Promise.prototype.reduce = function (fn, initialValue) {
  4040. return reduce(this, fn, initialValue, null);
  4041. };
  4042. Promise.reduce = function (promises, fn, initialValue, _each) {
  4043. return reduce(promises, fn, initialValue, _each);
  4044. };
  4045. function completed(valueOrReason, array) {
  4046. if (this.isFulfilled()) {
  4047. array._resolve(valueOrReason);
  4048. } else {
  4049. array._reject(valueOrReason);
  4050. }
  4051. }
  4052. function reduce(promises, fn, initialValue, _each) {
  4053. if (typeof fn !== "function") {
  4054. return apiRejection("expecting a function but got " + util.classString(fn));
  4055. }
  4056. var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
  4057. return array.promise();
  4058. }
  4059. function gotAccum(accum) {
  4060. this.accum = accum;
  4061. this.array._gotAccum(accum);
  4062. var value = tryConvertToPromise(this.value, this.array._promise);
  4063. if (value instanceof Promise) {
  4064. this.array._currentCancellable = value;
  4065. return value._then(gotValue, undefined, undefined, this, undefined);
  4066. } else {
  4067. return gotValue.call(this, value);
  4068. }
  4069. }
  4070. function gotValue(value) {
  4071. var array = this.array;
  4072. var promise = array._promise;
  4073. var fn = tryCatch(array._fn);
  4074. promise._pushContext();
  4075. var ret;
  4076. if (array._eachValues !== undefined) {
  4077. ret = fn.call(promise._boundValue(), value, this.index, this.length);
  4078. } else {
  4079. ret = fn.call(promise._boundValue(),
  4080. this.accum, value, this.index, this.length);
  4081. }
  4082. if (ret instanceof Promise) {
  4083. array._currentCancellable = ret;
  4084. }
  4085. var promiseCreated = promise._popContext();
  4086. debug.checkForgottenReturns(
  4087. ret,
  4088. promiseCreated,
  4089. array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
  4090. promise
  4091. );
  4092. return ret;
  4093. }
  4094. };
  4095. },{"./util":36}],29:[function(_dereq_,module,exports){
  4096. "use strict";
  4097. var util = _dereq_("./util");
  4098. var schedule;
  4099. var noAsyncScheduler = function() {
  4100. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  4101. };
  4102. var NativePromise = util.getNativePromise();
  4103. if (util.isNode && typeof MutationObserver === "undefined") {
  4104. var GlobalSetImmediate = global.setImmediate;
  4105. var ProcessNextTick = process.nextTick;
  4106. schedule = util.isRecentNode
  4107. ? function(fn) { GlobalSetImmediate.call(global, fn); }
  4108. : function(fn) { ProcessNextTick.call(process, fn); };
  4109. } else if (typeof NativePromise === "function" &&
  4110. typeof NativePromise.resolve === "function") {
  4111. var nativePromise = NativePromise.resolve();
  4112. schedule = function(fn) {
  4113. nativePromise.then(fn);
  4114. };
  4115. } else if ((typeof MutationObserver !== "undefined") &&
  4116. !(typeof window !== "undefined" &&
  4117. window.navigator &&
  4118. (window.navigator.standalone || window.cordova)) &&
  4119. ("classList" in document.documentElement)) {
  4120. schedule = (function() {
  4121. var div = document.createElement("div");
  4122. var opts = {attributes: true};
  4123. var toggleScheduled = false;
  4124. var div2 = document.createElement("div");
  4125. var o2 = new MutationObserver(function() {
  4126. div.classList.toggle("foo");
  4127. toggleScheduled = false;
  4128. });
  4129. o2.observe(div2, opts);
  4130. var scheduleToggle = function() {
  4131. if (toggleScheduled) return;
  4132. toggleScheduled = true;
  4133. div2.classList.toggle("foo");
  4134. };
  4135. return function schedule(fn) {
  4136. var o = new MutationObserver(function() {
  4137. o.disconnect();
  4138. fn();
  4139. });
  4140. o.observe(div, opts);
  4141. scheduleToggle();
  4142. };
  4143. })();
  4144. } else if (typeof setImmediate !== "undefined") {
  4145. schedule = function (fn) {
  4146. setImmediate(fn);
  4147. };
  4148. } else if (typeof setTimeout !== "undefined") {
  4149. schedule = function (fn) {
  4150. setTimeout(fn, 0);
  4151. };
  4152. } else {
  4153. schedule = noAsyncScheduler;
  4154. }
  4155. module.exports = schedule;
  4156. },{"./util":36}],30:[function(_dereq_,module,exports){
  4157. "use strict";
  4158. module.exports =
  4159. function(Promise, PromiseArray, debug) {
  4160. var PromiseInspection = Promise.PromiseInspection;
  4161. var util = _dereq_("./util");
  4162. function SettledPromiseArray(values) {
  4163. this.constructor$(values);
  4164. }
  4165. util.inherits(SettledPromiseArray, PromiseArray);
  4166. SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
  4167. this._values[index] = inspection;
  4168. var totalResolved = ++this._totalResolved;
  4169. if (totalResolved >= this._length) {
  4170. this._resolve(this._values);
  4171. return true;
  4172. }
  4173. return false;
  4174. };
  4175. SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
  4176. var ret = new PromiseInspection();
  4177. ret._bitField = 33554432;
  4178. ret._settledValueField = value;
  4179. return this._promiseResolved(index, ret);
  4180. };
  4181. SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
  4182. var ret = new PromiseInspection();
  4183. ret._bitField = 16777216;
  4184. ret._settledValueField = reason;
  4185. return this._promiseResolved(index, ret);
  4186. };
  4187. Promise.settle = function (promises) {
  4188. debug.deprecated(".settle()", ".reflect()");
  4189. return new SettledPromiseArray(promises).promise();
  4190. };
  4191. Promise.allSettled = function (promises) {
  4192. return new SettledPromiseArray(promises).promise();
  4193. };
  4194. Promise.prototype.settle = function () {
  4195. return Promise.settle(this);
  4196. };
  4197. };
  4198. },{"./util":36}],31:[function(_dereq_,module,exports){
  4199. "use strict";
  4200. module.exports =
  4201. function(Promise, PromiseArray, apiRejection) {
  4202. var util = _dereq_("./util");
  4203. var RangeError = _dereq_("./errors").RangeError;
  4204. var AggregateError = _dereq_("./errors").AggregateError;
  4205. var isArray = util.isArray;
  4206. var CANCELLATION = {};
  4207. function SomePromiseArray(values) {
  4208. this.constructor$(values);
  4209. this._howMany = 0;
  4210. this._unwrap = false;
  4211. this._initialized = false;
  4212. }
  4213. util.inherits(SomePromiseArray, PromiseArray);
  4214. SomePromiseArray.prototype._init = function () {
  4215. if (!this._initialized) {
  4216. return;
  4217. }
  4218. if (this._howMany === 0) {
  4219. this._resolve([]);
  4220. return;
  4221. }
  4222. this._init$(undefined, -5);
  4223. var isArrayResolved = isArray(this._values);
  4224. if (!this._isResolved() &&
  4225. isArrayResolved &&
  4226. this._howMany > this._canPossiblyFulfill()) {
  4227. this._reject(this._getRangeError(this.length()));
  4228. }
  4229. };
  4230. SomePromiseArray.prototype.init = function () {
  4231. this._initialized = true;
  4232. this._init();
  4233. };
  4234. SomePromiseArray.prototype.setUnwrap = function () {
  4235. this._unwrap = true;
  4236. };
  4237. SomePromiseArray.prototype.howMany = function () {
  4238. return this._howMany;
  4239. };
  4240. SomePromiseArray.prototype.setHowMany = function (count) {
  4241. this._howMany = count;
  4242. };
  4243. SomePromiseArray.prototype._promiseFulfilled = function (value) {
  4244. this._addFulfilled(value);
  4245. if (this._fulfilled() === this.howMany()) {
  4246. this._values.length = this.howMany();
  4247. if (this.howMany() === 1 && this._unwrap) {
  4248. this._resolve(this._values[0]);
  4249. } else {
  4250. this._resolve(this._values);
  4251. }
  4252. return true;
  4253. }
  4254. return false;
  4255. };
  4256. SomePromiseArray.prototype._promiseRejected = function (reason) {
  4257. this._addRejected(reason);
  4258. return this._checkOutcome();
  4259. };
  4260. SomePromiseArray.prototype._promiseCancelled = function () {
  4261. if (this._values instanceof Promise || this._values == null) {
  4262. return this._cancel();
  4263. }
  4264. this._addRejected(CANCELLATION);
  4265. return this._checkOutcome();
  4266. };
  4267. SomePromiseArray.prototype._checkOutcome = function() {
  4268. if (this.howMany() > this._canPossiblyFulfill()) {
  4269. var e = new AggregateError();
  4270. for (var i = this.length(); i < this._values.length; ++i) {
  4271. if (this._values[i] !== CANCELLATION) {
  4272. e.push(this._values[i]);
  4273. }
  4274. }
  4275. if (e.length > 0) {
  4276. this._reject(e);
  4277. } else {
  4278. this._cancel();
  4279. }
  4280. return true;
  4281. }
  4282. return false;
  4283. };
  4284. SomePromiseArray.prototype._fulfilled = function () {
  4285. return this._totalResolved;
  4286. };
  4287. SomePromiseArray.prototype._rejected = function () {
  4288. return this._values.length - this.length();
  4289. };
  4290. SomePromiseArray.prototype._addRejected = function (reason) {
  4291. this._values.push(reason);
  4292. };
  4293. SomePromiseArray.prototype._addFulfilled = function (value) {
  4294. this._values[this._totalResolved++] = value;
  4295. };
  4296. SomePromiseArray.prototype._canPossiblyFulfill = function () {
  4297. return this.length() - this._rejected();
  4298. };
  4299. SomePromiseArray.prototype._getRangeError = function (count) {
  4300. var message = "Input array must contain at least " +
  4301. this._howMany + " items but contains only " + count + " items";
  4302. return new RangeError(message);
  4303. };
  4304. SomePromiseArray.prototype._resolveEmptyArray = function () {
  4305. this._reject(this._getRangeError(0));
  4306. };
  4307. function some(promises, howMany) {
  4308. if ((howMany | 0) !== howMany || howMany < 0) {
  4309. return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  4310. }
  4311. var ret = new SomePromiseArray(promises);
  4312. var promise = ret.promise();
  4313. ret.setHowMany(howMany);
  4314. ret.init();
  4315. return promise;
  4316. }
  4317. Promise.some = function (promises, howMany) {
  4318. return some(promises, howMany);
  4319. };
  4320. Promise.prototype.some = function (howMany) {
  4321. return some(this, howMany);
  4322. };
  4323. Promise._SomePromiseArray = SomePromiseArray;
  4324. };
  4325. },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
  4326. "use strict";
  4327. module.exports = function(Promise) {
  4328. function PromiseInspection(promise) {
  4329. if (promise !== undefined) {
  4330. promise = promise._target();
  4331. this._bitField = promise._bitField;
  4332. this._settledValueField = promise._isFateSealed()
  4333. ? promise._settledValue() : undefined;
  4334. }
  4335. else {
  4336. this._bitField = 0;
  4337. this._settledValueField = undefined;
  4338. }
  4339. }
  4340. PromiseInspection.prototype._settledValue = function() {
  4341. return this._settledValueField;
  4342. };
  4343. var value = PromiseInspection.prototype.value = function () {
  4344. if (!this.isFulfilled()) {
  4345. throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  4346. }
  4347. return this._settledValue();
  4348. };
  4349. var reason = PromiseInspection.prototype.error =
  4350. PromiseInspection.prototype.reason = function () {
  4351. if (!this.isRejected()) {
  4352. throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  4353. }
  4354. return this._settledValue();
  4355. };
  4356. var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
  4357. return (this._bitField & 33554432) !== 0;
  4358. };
  4359. var isRejected = PromiseInspection.prototype.isRejected = function () {
  4360. return (this._bitField & 16777216) !== 0;
  4361. };
  4362. var isPending = PromiseInspection.prototype.isPending = function () {
  4363. return (this._bitField & 50397184) === 0;
  4364. };
  4365. var isResolved = PromiseInspection.prototype.isResolved = function () {
  4366. return (this._bitField & 50331648) !== 0;
  4367. };
  4368. PromiseInspection.prototype.isCancelled = function() {
  4369. return (this._bitField & 8454144) !== 0;
  4370. };
  4371. Promise.prototype.__isCancelled = function() {
  4372. return (this._bitField & 65536) === 65536;
  4373. };
  4374. Promise.prototype._isCancelled = function() {
  4375. return this._target().__isCancelled();
  4376. };
  4377. Promise.prototype.isCancelled = function() {
  4378. return (this._target()._bitField & 8454144) !== 0;
  4379. };
  4380. Promise.prototype.isPending = function() {
  4381. return isPending.call(this._target());
  4382. };
  4383. Promise.prototype.isRejected = function() {
  4384. return isRejected.call(this._target());
  4385. };
  4386. Promise.prototype.isFulfilled = function() {
  4387. return isFulfilled.call(this._target());
  4388. };
  4389. Promise.prototype.isResolved = function() {
  4390. return isResolved.call(this._target());
  4391. };
  4392. Promise.prototype.value = function() {
  4393. return value.call(this._target());
  4394. };
  4395. Promise.prototype.reason = function() {
  4396. var target = this._target();
  4397. target._unsetRejectionIsUnhandled();
  4398. return reason.call(target);
  4399. };
  4400. Promise.prototype._value = function() {
  4401. return this._settledValue();
  4402. };
  4403. Promise.prototype._reason = function() {
  4404. this._unsetRejectionIsUnhandled();
  4405. return this._settledValue();
  4406. };
  4407. Promise.PromiseInspection = PromiseInspection;
  4408. };
  4409. },{}],33:[function(_dereq_,module,exports){
  4410. "use strict";
  4411. module.exports = function(Promise, INTERNAL) {
  4412. var util = _dereq_("./util");
  4413. var errorObj = util.errorObj;
  4414. var isObject = util.isObject;
  4415. function tryConvertToPromise(obj, context) {
  4416. if (isObject(obj)) {
  4417. if (obj instanceof Promise) return obj;
  4418. var then = getThen(obj);
  4419. if (then === errorObj) {
  4420. if (context) context._pushContext();
  4421. var ret = Promise.reject(then.e);
  4422. if (context) context._popContext();
  4423. return ret;
  4424. } else if (typeof then === "function") {
  4425. if (isAnyBluebirdPromise(obj)) {
  4426. var ret = new Promise(INTERNAL);
  4427. obj._then(
  4428. ret._fulfill,
  4429. ret._reject,
  4430. undefined,
  4431. ret,
  4432. null
  4433. );
  4434. return ret;
  4435. }
  4436. return doThenable(obj, then, context);
  4437. }
  4438. }
  4439. return obj;
  4440. }
  4441. function doGetThen(obj) {
  4442. return obj.then;
  4443. }
  4444. function getThen(obj) {
  4445. try {
  4446. return doGetThen(obj);
  4447. } catch (e) {
  4448. errorObj.e = e;
  4449. return errorObj;
  4450. }
  4451. }
  4452. var hasProp = {}.hasOwnProperty;
  4453. function isAnyBluebirdPromise(obj) {
  4454. try {
  4455. return hasProp.call(obj, "_promise0");
  4456. } catch (e) {
  4457. return false;
  4458. }
  4459. }
  4460. function doThenable(x, then, context) {
  4461. var promise = new Promise(INTERNAL);
  4462. var ret = promise;
  4463. if (context) context._pushContext();
  4464. promise._captureStackTrace();
  4465. if (context) context._popContext();
  4466. var synchronous = true;
  4467. var result = util.tryCatch(then).call(x, resolve, reject);
  4468. synchronous = false;
  4469. if (promise && result === errorObj) {
  4470. promise._rejectCallback(result.e, true, true);
  4471. promise = null;
  4472. }
  4473. function resolve(value) {
  4474. if (!promise) return;
  4475. promise._resolveCallback(value);
  4476. promise = null;
  4477. }
  4478. function reject(reason) {
  4479. if (!promise) return;
  4480. promise._rejectCallback(reason, synchronous, true);
  4481. promise = null;
  4482. }
  4483. return ret;
  4484. }
  4485. return tryConvertToPromise;
  4486. };
  4487. },{"./util":36}],34:[function(_dereq_,module,exports){
  4488. "use strict";
  4489. module.exports = function(Promise, INTERNAL, debug) {
  4490. var util = _dereq_("./util");
  4491. var TimeoutError = Promise.TimeoutError;
  4492. function HandleWrapper(handle) {
  4493. this.handle = handle;
  4494. }
  4495. HandleWrapper.prototype._resultCancelled = function() {
  4496. clearTimeout(this.handle);
  4497. };
  4498. var afterValue = function(value) { return delay(+this).thenReturn(value); };
  4499. var delay = Promise.delay = function (ms, value) {
  4500. var ret;
  4501. var handle;
  4502. if (value !== undefined) {
  4503. ret = Promise.resolve(value)
  4504. ._then(afterValue, null, null, ms, undefined);
  4505. if (debug.cancellation() && value instanceof Promise) {
  4506. ret._setOnCancel(value);
  4507. }
  4508. } else {
  4509. ret = new Promise(INTERNAL);
  4510. handle = setTimeout(function() { ret._fulfill(); }, +ms);
  4511. if (debug.cancellation()) {
  4512. ret._setOnCancel(new HandleWrapper(handle));
  4513. }
  4514. ret._captureStackTrace();
  4515. }
  4516. ret._setAsyncGuaranteed();
  4517. return ret;
  4518. };
  4519. Promise.prototype.delay = function (ms) {
  4520. return delay(ms, this);
  4521. };
  4522. var afterTimeout = function (promise, message, parent) {
  4523. var err;
  4524. if (typeof message !== "string") {
  4525. if (message instanceof Error) {
  4526. err = message;
  4527. } else {
  4528. err = new TimeoutError("operation timed out");
  4529. }
  4530. } else {
  4531. err = new TimeoutError(message);
  4532. }
  4533. util.markAsOriginatingFromRejection(err);
  4534. promise._attachExtraTrace(err);
  4535. promise._reject(err);
  4536. if (parent != null) {
  4537. parent.cancel();
  4538. }
  4539. };
  4540. function successClear(value) {
  4541. clearTimeout(this.handle);
  4542. return value;
  4543. }
  4544. function failureClear(reason) {
  4545. clearTimeout(this.handle);
  4546. throw reason;
  4547. }
  4548. Promise.prototype.timeout = function (ms, message) {
  4549. ms = +ms;
  4550. var ret, parent;
  4551. var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
  4552. if (ret.isPending()) {
  4553. afterTimeout(ret, message, parent);
  4554. }
  4555. }, ms));
  4556. if (debug.cancellation()) {
  4557. parent = this.then();
  4558. ret = parent._then(successClear, failureClear,
  4559. undefined, handleWrapper, undefined);
  4560. ret._setOnCancel(handleWrapper);
  4561. } else {
  4562. ret = this._then(successClear, failureClear,
  4563. undefined, handleWrapper, undefined);
  4564. }
  4565. return ret;
  4566. };
  4567. };
  4568. },{"./util":36}],35:[function(_dereq_,module,exports){
  4569. "use strict";
  4570. module.exports = function (Promise, apiRejection, tryConvertToPromise,
  4571. createContext, INTERNAL, debug) {
  4572. var util = _dereq_("./util");
  4573. var TypeError = _dereq_("./errors").TypeError;
  4574. var inherits = _dereq_("./util").inherits;
  4575. var errorObj = util.errorObj;
  4576. var tryCatch = util.tryCatch;
  4577. var NULL = {};
  4578. function thrower(e) {
  4579. setTimeout(function(){throw e;}, 0);
  4580. }
  4581. function castPreservingDisposable(thenable) {
  4582. var maybePromise = tryConvertToPromise(thenable);
  4583. if (maybePromise !== thenable &&
  4584. typeof thenable._isDisposable === "function" &&
  4585. typeof thenable._getDisposer === "function" &&
  4586. thenable._isDisposable()) {
  4587. maybePromise._setDisposable(thenable._getDisposer());
  4588. }
  4589. return maybePromise;
  4590. }
  4591. function dispose(resources, inspection) {
  4592. var i = 0;
  4593. var len = resources.length;
  4594. var ret = new Promise(INTERNAL);
  4595. function iterator() {
  4596. if (i >= len) return ret._fulfill();
  4597. var maybePromise = castPreservingDisposable(resources[i++]);
  4598. if (maybePromise instanceof Promise &&
  4599. maybePromise._isDisposable()) {
  4600. try {
  4601. maybePromise = tryConvertToPromise(
  4602. maybePromise._getDisposer().tryDispose(inspection),
  4603. resources.promise);
  4604. } catch (e) {
  4605. return thrower(e);
  4606. }
  4607. if (maybePromise instanceof Promise) {
  4608. return maybePromise._then(iterator, thrower,
  4609. null, null, null);
  4610. }
  4611. }
  4612. iterator();
  4613. }
  4614. iterator();
  4615. return ret;
  4616. }
  4617. function Disposer(data, promise, context) {
  4618. this._data = data;
  4619. this._promise = promise;
  4620. this._context = context;
  4621. }
  4622. Disposer.prototype.data = function () {
  4623. return this._data;
  4624. };
  4625. Disposer.prototype.promise = function () {
  4626. return this._promise;
  4627. };
  4628. Disposer.prototype.resource = function () {
  4629. if (this.promise().isFulfilled()) {
  4630. return this.promise().value();
  4631. }
  4632. return NULL;
  4633. };
  4634. Disposer.prototype.tryDispose = function(inspection) {
  4635. var resource = this.resource();
  4636. var context = this._context;
  4637. if (context !== undefined) context._pushContext();
  4638. var ret = resource !== NULL
  4639. ? this.doDispose(resource, inspection) : null;
  4640. if (context !== undefined) context._popContext();
  4641. this._promise._unsetDisposable();
  4642. this._data = null;
  4643. return ret;
  4644. };
  4645. Disposer.isDisposer = function (d) {
  4646. return (d != null &&
  4647. typeof d.resource === "function" &&
  4648. typeof d.tryDispose === "function");
  4649. };
  4650. function FunctionDisposer(fn, promise, context) {
  4651. this.constructor$(fn, promise, context);
  4652. }
  4653. inherits(FunctionDisposer, Disposer);
  4654. FunctionDisposer.prototype.doDispose = function (resource, inspection) {
  4655. var fn = this.data();
  4656. return fn.call(resource, resource, inspection);
  4657. };
  4658. function maybeUnwrapDisposer(value) {
  4659. if (Disposer.isDisposer(value)) {
  4660. this.resources[this.index]._setDisposable(value);
  4661. return value.promise();
  4662. }
  4663. return value;
  4664. }
  4665. function ResourceList(length) {
  4666. this.length = length;
  4667. this.promise = null;
  4668. this[length-1] = null;
  4669. }
  4670. ResourceList.prototype._resultCancelled = function() {
  4671. var len = this.length;
  4672. for (var i = 0; i < len; ++i) {
  4673. var item = this[i];
  4674. if (item instanceof Promise) {
  4675. item.cancel();
  4676. }
  4677. }
  4678. };
  4679. Promise.using = function () {
  4680. var len = arguments.length;
  4681. if (len < 2) return apiRejection(
  4682. "you must pass at least 2 arguments to Promise.using");
  4683. var fn = arguments[len - 1];
  4684. if (typeof fn !== "function") {
  4685. return apiRejection("expecting a function but got " + util.classString(fn));
  4686. }
  4687. var input;
  4688. var spreadArgs = true;
  4689. if (len === 2 && Array.isArray(arguments[0])) {
  4690. input = arguments[0];
  4691. len = input.length;
  4692. spreadArgs = false;
  4693. } else {
  4694. input = arguments;
  4695. len--;
  4696. }
  4697. var resources = new ResourceList(len);
  4698. for (var i = 0; i < len; ++i) {
  4699. var resource = input[i];
  4700. if (Disposer.isDisposer(resource)) {
  4701. var disposer = resource;
  4702. resource = resource.promise();
  4703. resource._setDisposable(disposer);
  4704. } else {
  4705. var maybePromise = tryConvertToPromise(resource);
  4706. if (maybePromise instanceof Promise) {
  4707. resource =
  4708. maybePromise._then(maybeUnwrapDisposer, null, null, {
  4709. resources: resources,
  4710. index: i
  4711. }, undefined);
  4712. }
  4713. }
  4714. resources[i] = resource;
  4715. }
  4716. var reflectedResources = new Array(resources.length);
  4717. for (var i = 0; i < reflectedResources.length; ++i) {
  4718. reflectedResources[i] = Promise.resolve(resources[i]).reflect();
  4719. }
  4720. var resultPromise = Promise.all(reflectedResources)
  4721. .then(function(inspections) {
  4722. for (var i = 0; i < inspections.length; ++i) {
  4723. var inspection = inspections[i];
  4724. if (inspection.isRejected()) {
  4725. errorObj.e = inspection.error();
  4726. return errorObj;
  4727. } else if (!inspection.isFulfilled()) {
  4728. resultPromise.cancel();
  4729. return;
  4730. }
  4731. inspections[i] = inspection.value();
  4732. }
  4733. promise._pushContext();
  4734. fn = tryCatch(fn);
  4735. var ret = spreadArgs
  4736. ? fn.apply(undefined, inspections) : fn(inspections);
  4737. var promiseCreated = promise._popContext();
  4738. debug.checkForgottenReturns(
  4739. ret, promiseCreated, "Promise.using", promise);
  4740. return ret;
  4741. });
  4742. var promise = resultPromise.lastly(function() {
  4743. var inspection = new Promise.PromiseInspection(resultPromise);
  4744. return dispose(resources, inspection);
  4745. });
  4746. resources.promise = promise;
  4747. promise._setOnCancel(resources);
  4748. return promise;
  4749. };
  4750. Promise.prototype._setDisposable = function (disposer) {
  4751. this._bitField = this._bitField | 131072;
  4752. this._disposer = disposer;
  4753. };
  4754. Promise.prototype._isDisposable = function () {
  4755. return (this._bitField & 131072) > 0;
  4756. };
  4757. Promise.prototype._getDisposer = function () {
  4758. return this._disposer;
  4759. };
  4760. Promise.prototype._unsetDisposable = function () {
  4761. this._bitField = this._bitField & (~131072);
  4762. this._disposer = undefined;
  4763. };
  4764. Promise.prototype.disposer = function (fn) {
  4765. if (typeof fn === "function") {
  4766. return new FunctionDisposer(fn, this, createContext());
  4767. }
  4768. throw new TypeError();
  4769. };
  4770. };
  4771. },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
  4772. "use strict";
  4773. var es5 = _dereq_("./es5");
  4774. var canEvaluate = typeof navigator == "undefined";
  4775. var errorObj = {e: {}};
  4776. var tryCatchTarget;
  4777. var globalObject = typeof self !== "undefined" ? self :
  4778. typeof window !== "undefined" ? window :
  4779. typeof global !== "undefined" ? global :
  4780. this !== undefined ? this : null;
  4781. function tryCatcher() {
  4782. try {
  4783. var target = tryCatchTarget;
  4784. tryCatchTarget = null;
  4785. return target.apply(this, arguments);
  4786. } catch (e) {
  4787. errorObj.e = e;
  4788. return errorObj;
  4789. }
  4790. }
  4791. function tryCatch(fn) {
  4792. tryCatchTarget = fn;
  4793. return tryCatcher;
  4794. }
  4795. var inherits = function(Child, Parent) {
  4796. var hasProp = {}.hasOwnProperty;
  4797. function T() {
  4798. this.constructor = Child;
  4799. this.constructor$ = Parent;
  4800. for (var propertyName in Parent.prototype) {
  4801. if (hasProp.call(Parent.prototype, propertyName) &&
  4802. propertyName.charAt(propertyName.length-1) !== "$"
  4803. ) {
  4804. this[propertyName + "$"] = Parent.prototype[propertyName];
  4805. }
  4806. }
  4807. }
  4808. T.prototype = Parent.prototype;
  4809. Child.prototype = new T();
  4810. return Child.prototype;
  4811. };
  4812. function isPrimitive(val) {
  4813. return val == null || val === true || val === false ||
  4814. typeof val === "string" || typeof val === "number";
  4815. }
  4816. function isObject(value) {
  4817. return typeof value === "function" ||
  4818. typeof value === "object" && value !== null;
  4819. }
  4820. function maybeWrapAsError(maybeError) {
  4821. if (!isPrimitive(maybeError)) return maybeError;
  4822. return new Error(safeToString(maybeError));
  4823. }
  4824. function withAppended(target, appendee) {
  4825. var len = target.length;
  4826. var ret = new Array(len + 1);
  4827. var i;
  4828. for (i = 0; i < len; ++i) {
  4829. ret[i] = target[i];
  4830. }
  4831. ret[i] = appendee;
  4832. return ret;
  4833. }
  4834. function getDataPropertyOrDefault(obj, key, defaultValue) {
  4835. if (es5.isES5) {
  4836. var desc = Object.getOwnPropertyDescriptor(obj, key);
  4837. if (desc != null) {
  4838. return desc.get == null && desc.set == null
  4839. ? desc.value
  4840. : defaultValue;
  4841. }
  4842. } else {
  4843. return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
  4844. }
  4845. }
  4846. function notEnumerableProp(obj, name, value) {
  4847. if (isPrimitive(obj)) return obj;
  4848. var descriptor = {
  4849. value: value,
  4850. configurable: true,
  4851. enumerable: false,
  4852. writable: true
  4853. };
  4854. es5.defineProperty(obj, name, descriptor);
  4855. return obj;
  4856. }
  4857. function thrower(r) {
  4858. throw r;
  4859. }
  4860. var inheritedDataKeys = (function() {
  4861. var excludedPrototypes = [
  4862. Array.prototype,
  4863. Object.prototype,
  4864. Function.prototype
  4865. ];
  4866. var isExcludedProto = function(val) {
  4867. for (var i = 0; i < excludedPrototypes.length; ++i) {
  4868. if (excludedPrototypes[i] === val) {
  4869. return true;
  4870. }
  4871. }
  4872. return false;
  4873. };
  4874. if (es5.isES5) {
  4875. var getKeys = Object.getOwnPropertyNames;
  4876. return function(obj) {
  4877. var ret = [];
  4878. var visitedKeys = Object.create(null);
  4879. while (obj != null && !isExcludedProto(obj)) {
  4880. var keys;
  4881. try {
  4882. keys = getKeys(obj);
  4883. } catch (e) {
  4884. return ret;
  4885. }
  4886. for (var i = 0; i < keys.length; ++i) {
  4887. var key = keys[i];
  4888. if (visitedKeys[key]) continue;
  4889. visitedKeys[key] = true;
  4890. var desc = Object.getOwnPropertyDescriptor(obj, key);
  4891. if (desc != null && desc.get == null && desc.set == null) {
  4892. ret.push(key);
  4893. }
  4894. }
  4895. obj = es5.getPrototypeOf(obj);
  4896. }
  4897. return ret;
  4898. };
  4899. } else {
  4900. var hasProp = {}.hasOwnProperty;
  4901. return function(obj) {
  4902. if (isExcludedProto(obj)) return [];
  4903. var ret = [];
  4904. /*jshint forin:false */
  4905. enumeration: for (var key in obj) {
  4906. if (hasProp.call(obj, key)) {
  4907. ret.push(key);
  4908. } else {
  4909. for (var i = 0; i < excludedPrototypes.length; ++i) {
  4910. if (hasProp.call(excludedPrototypes[i], key)) {
  4911. continue enumeration;
  4912. }
  4913. }
  4914. ret.push(key);
  4915. }
  4916. }
  4917. return ret;
  4918. };
  4919. }
  4920. })();
  4921. var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
  4922. function isClass(fn) {
  4923. try {
  4924. if (typeof fn === "function") {
  4925. var keys = es5.names(fn.prototype);
  4926. var hasMethods = es5.isES5 && keys.length > 1;
  4927. var hasMethodsOtherThanConstructor = keys.length > 0 &&
  4928. !(keys.length === 1 && keys[0] === "constructor");
  4929. var hasThisAssignmentAndStaticMethods =
  4930. thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
  4931. if (hasMethods || hasMethodsOtherThanConstructor ||
  4932. hasThisAssignmentAndStaticMethods) {
  4933. return true;
  4934. }
  4935. }
  4936. return false;
  4937. } catch (e) {
  4938. return false;
  4939. }
  4940. }
  4941. function toFastProperties(obj) {
  4942. /*jshint -W027,-W055,-W031*/
  4943. function FakeConstructor() {}
  4944. FakeConstructor.prototype = obj;
  4945. var receiver = new FakeConstructor();
  4946. function ic() {
  4947. return typeof receiver.foo;
  4948. }
  4949. ic();
  4950. ic();
  4951. return obj;
  4952. eval(obj);
  4953. }
  4954. var rident = /^[a-z$_][a-z$_0-9]*$/i;
  4955. function isIdentifier(str) {
  4956. return rident.test(str);
  4957. }
  4958. function filledRange(count, prefix, suffix) {
  4959. var ret = new Array(count);
  4960. for(var i = 0; i < count; ++i) {
  4961. ret[i] = prefix + i + suffix;
  4962. }
  4963. return ret;
  4964. }
  4965. function safeToString(obj) {
  4966. try {
  4967. return obj + "";
  4968. } catch (e) {
  4969. return "[no string representation]";
  4970. }
  4971. }
  4972. function isError(obj) {
  4973. return obj instanceof Error ||
  4974. (obj !== null &&
  4975. typeof obj === "object" &&
  4976. typeof obj.message === "string" &&
  4977. typeof obj.name === "string");
  4978. }
  4979. function markAsOriginatingFromRejection(e) {
  4980. try {
  4981. notEnumerableProp(e, "isOperational", true);
  4982. }
  4983. catch(ignore) {}
  4984. }
  4985. function originatesFromRejection(e) {
  4986. if (e == null) return false;
  4987. return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
  4988. e["isOperational"] === true);
  4989. }
  4990. function canAttachTrace(obj) {
  4991. return isError(obj) && es5.propertyIsWritable(obj, "stack");
  4992. }
  4993. var ensureErrorObject = (function() {
  4994. if (!("stack" in new Error())) {
  4995. return function(value) {
  4996. if (canAttachTrace(value)) return value;
  4997. try {throw new Error(safeToString(value));}
  4998. catch(err) {return err;}
  4999. };
  5000. } else {
  5001. return function(value) {
  5002. if (canAttachTrace(value)) return value;
  5003. return new Error(safeToString(value));
  5004. };
  5005. }
  5006. })();
  5007. function classString(obj) {
  5008. return {}.toString.call(obj);
  5009. }
  5010. function copyDescriptors(from, to, filter) {
  5011. var keys = es5.names(from);
  5012. for (var i = 0; i < keys.length; ++i) {
  5013. var key = keys[i];
  5014. if (filter(key)) {
  5015. try {
  5016. es5.defineProperty(to, key, es5.getDescriptor(from, key));
  5017. } catch (ignore) {}
  5018. }
  5019. }
  5020. }
  5021. var asArray = function(v) {
  5022. if (es5.isArray(v)) {
  5023. return v;
  5024. }
  5025. return null;
  5026. };
  5027. if (typeof Symbol !== "undefined" && Symbol.iterator) {
  5028. var ArrayFrom = typeof Array.from === "function" ? function(v) {
  5029. return Array.from(v);
  5030. } : function(v) {
  5031. var ret = [];
  5032. var it = v[Symbol.iterator]();
  5033. var itResult;
  5034. while (!((itResult = it.next()).done)) {
  5035. ret.push(itResult.value);
  5036. }
  5037. return ret;
  5038. };
  5039. asArray = function(v) {
  5040. if (es5.isArray(v)) {
  5041. return v;
  5042. } else if (v != null && typeof v[Symbol.iterator] === "function") {
  5043. return ArrayFrom(v);
  5044. }
  5045. return null;
  5046. };
  5047. }
  5048. var isNode = typeof process !== "undefined" &&
  5049. classString(process).toLowerCase() === "[object process]";
  5050. var hasEnvVariables = typeof process !== "undefined" &&
  5051. typeof process.env !== "undefined";
  5052. function env(key) {
  5053. return hasEnvVariables ? process.env[key] : undefined;
  5054. }
  5055. function getNativePromise() {
  5056. if (typeof Promise === "function") {
  5057. try {
  5058. var promise = new Promise(function(){});
  5059. if (classString(promise) === "[object Promise]") {
  5060. return Promise;
  5061. }
  5062. } catch (e) {}
  5063. }
  5064. }
  5065. var reflectHandler;
  5066. function contextBind(ctx, cb) {
  5067. if (ctx === null ||
  5068. typeof cb !== "function" ||
  5069. cb === reflectHandler) {
  5070. return cb;
  5071. }
  5072. if (ctx.domain !== null) {
  5073. cb = ctx.domain.bind(cb);
  5074. }
  5075. var async = ctx.async;
  5076. if (async !== null) {
  5077. var old = cb;
  5078. cb = function() {
  5079. var args = (new Array(2)).concat([].slice.call(arguments));;
  5080. args[0] = old;
  5081. args[1] = this;
  5082. return async.runInAsyncScope.apply(async, args);
  5083. };
  5084. }
  5085. return cb;
  5086. }
  5087. var ret = {
  5088. setReflectHandler: function(fn) {
  5089. reflectHandler = fn;
  5090. },
  5091. isClass: isClass,
  5092. isIdentifier: isIdentifier,
  5093. inheritedDataKeys: inheritedDataKeys,
  5094. getDataPropertyOrDefault: getDataPropertyOrDefault,
  5095. thrower: thrower,
  5096. isArray: es5.isArray,
  5097. asArray: asArray,
  5098. notEnumerableProp: notEnumerableProp,
  5099. isPrimitive: isPrimitive,
  5100. isObject: isObject,
  5101. isError: isError,
  5102. canEvaluate: canEvaluate,
  5103. errorObj: errorObj,
  5104. tryCatch: tryCatch,
  5105. inherits: inherits,
  5106. withAppended: withAppended,
  5107. maybeWrapAsError: maybeWrapAsError,
  5108. toFastProperties: toFastProperties,
  5109. filledRange: filledRange,
  5110. toString: safeToString,
  5111. canAttachTrace: canAttachTrace,
  5112. ensureErrorObject: ensureErrorObject,
  5113. originatesFromRejection: originatesFromRejection,
  5114. markAsOriginatingFromRejection: markAsOriginatingFromRejection,
  5115. classString: classString,
  5116. copyDescriptors: copyDescriptors,
  5117. isNode: isNode,
  5118. hasEnvVariables: hasEnvVariables,
  5119. env: env,
  5120. global: globalObject,
  5121. getNativePromise: getNativePromise,
  5122. contextBind: contextBind
  5123. };
  5124. ret.isRecentNode = ret.isNode && (function() {
  5125. var version;
  5126. if (process.versions && process.versions.node) {
  5127. version = process.versions.node.split(".").map(Number);
  5128. } else if (process.version) {
  5129. version = process.version.split(".").map(Number);
  5130. }
  5131. return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
  5132. })();
  5133. ret.nodeSupportsAsyncResource = ret.isNode && (function() {
  5134. var supportsAsync = false;
  5135. try {
  5136. var res = _dereq_("async_hooks").AsyncResource;
  5137. supportsAsync = typeof res.prototype.runInAsyncScope === "function";
  5138. } catch (e) {
  5139. supportsAsync = false;
  5140. }
  5141. return supportsAsync;
  5142. })();
  5143. if (ret.isNode) ret.toFastProperties(process);
  5144. try {throw new Error(); } catch (e) {ret.lastLineError = e;}
  5145. module.exports = ret;
  5146. },{"./es5":13,"async_hooks":undefined}]},{},[4])(4)
  5147. }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }