socket.io.js 170 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988
  1. !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.io=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 require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  2. module.exports = _dereq_('./lib/');
  3. },{"./lib/":2}],2:[function(_dereq_,module,exports){
  4. /**
  5. * Module dependencies.
  6. */
  7. var url = _dereq_('./url');
  8. var parser = _dereq_('socket.io-parser');
  9. var Manager = _dereq_('./manager');
  10. var debug = _dereq_('debug')('socket.io-client');
  11. /**
  12. * Module exports.
  13. */
  14. module.exports = exports = lookup;
  15. /**
  16. * Managers cache.
  17. */
  18. var cache = exports.managers = {};
  19. /**
  20. * Looks up an existing `Manager` for multiplexing.
  21. * If the user summons:
  22. *
  23. * `io('http://localhost/a');`
  24. * `io('http://localhost/b');`
  25. *
  26. * We reuse the existing instance based on same scheme/port/host,
  27. * and we initialize sockets for each namespace.
  28. *
  29. * @api public
  30. */
  31. function lookup(uri, opts) {
  32. if (typeof uri == 'object') {
  33. opts = uri;
  34. uri = undefined;
  35. }
  36. opts = opts || {};
  37. var parsed = url(uri);
  38. var source = parsed.source;
  39. var id = parsed.id;
  40. var io;
  41. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  42. debug('ignoring socket cache for %s', source);
  43. io = Manager(source, opts);
  44. } else {
  45. if (!cache[id]) {
  46. debug('new io instance for %s', source);
  47. cache[id] = Manager(source, opts);
  48. }
  49. io = cache[id];
  50. }
  51. return io.socket(parsed.path);
  52. }
  53. /**
  54. * Protocol version.
  55. *
  56. * @api public
  57. */
  58. exports.protocol = parser.protocol;
  59. /**
  60. * `connect`.
  61. *
  62. * @param {String} uri
  63. * @api public
  64. */
  65. exports.connect = lookup;
  66. /**
  67. * Expose constructors for standalone build.
  68. *
  69. * @api public
  70. */
  71. exports.Manager = _dereq_('./manager');
  72. exports.Socket = _dereq_('./socket');
  73. },{"./manager":3,"./socket":5,"./url":6,"debug":10,"socket.io-parser":44}],3:[function(_dereq_,module,exports){
  74. /**
  75. * Module dependencies.
  76. */
  77. var url = _dereq_('./url');
  78. var eio = _dereq_('engine.io-client');
  79. var Socket = _dereq_('./socket');
  80. var Emitter = _dereq_('component-emitter');
  81. var parser = _dereq_('socket.io-parser');
  82. var on = _dereq_('./on');
  83. var bind = _dereq_('component-bind');
  84. var object = _dereq_('object-component');
  85. var debug = _dereq_('debug')('socket.io-client:manager');
  86. var indexOf = _dereq_('indexof');
  87. var Backoff = _dereq_('backo2');
  88. /**
  89. * Module exports
  90. */
  91. module.exports = Manager;
  92. /**
  93. * `Manager` constructor.
  94. *
  95. * @param {String} engine instance or engine uri/opts
  96. * @param {Object} options
  97. * @api public
  98. */
  99. function Manager(uri, opts){
  100. if (!(this instanceof Manager)) return new Manager(uri, opts);
  101. if (uri && ('object' == typeof uri)) {
  102. opts = uri;
  103. uri = undefined;
  104. }
  105. opts = opts || {};
  106. opts.path = opts.path || '/socket.io';
  107. this.nsps = {};
  108. this.subs = [];
  109. this.opts = opts;
  110. this.reconnection(opts.reconnection !== false);
  111. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  112. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  113. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  114. this.randomizationFactor(opts.randomizationFactor || 0.5);
  115. this.backoff = new Backoff({
  116. min: this.reconnectionDelay(),
  117. max: this.reconnectionDelayMax(),
  118. jitter: this.randomizationFactor()
  119. });
  120. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  121. this.readyState = 'closed';
  122. this.uri = uri;
  123. this.connected = [];
  124. this.encoding = false;
  125. this.packetBuffer = [];
  126. this.encoder = new parser.Encoder();
  127. this.decoder = new parser.Decoder();
  128. this.autoConnect = opts.autoConnect !== false;
  129. if (this.autoConnect) this.open();
  130. }
  131. /**
  132. * Propagate given event to sockets and emit on `this`
  133. *
  134. * @api private
  135. */
  136. Manager.prototype.emitAll = function() {
  137. this.emit.apply(this, arguments);
  138. for (var nsp in this.nsps) {
  139. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  140. }
  141. };
  142. /**
  143. * Update `socket.id` of all sockets
  144. *
  145. * @api private
  146. */
  147. Manager.prototype.updateSocketIds = function(){
  148. for (var nsp in this.nsps) {
  149. this.nsps[nsp].id = this.engine.id;
  150. }
  151. };
  152. /**
  153. * Mix in `Emitter`.
  154. */
  155. Emitter(Manager.prototype);
  156. /**
  157. * Sets the `reconnection` config.
  158. *
  159. * @param {Boolean} true/false if it should automatically reconnect
  160. * @return {Manager} self or value
  161. * @api public
  162. */
  163. Manager.prototype.reconnection = function(v){
  164. if (!arguments.length) return this._reconnection;
  165. this._reconnection = !!v;
  166. return this;
  167. };
  168. /**
  169. * Sets the reconnection attempts config.
  170. *
  171. * @param {Number} max reconnection attempts before giving up
  172. * @return {Manager} self or value
  173. * @api public
  174. */
  175. Manager.prototype.reconnectionAttempts = function(v){
  176. if (!arguments.length) return this._reconnectionAttempts;
  177. this._reconnectionAttempts = v;
  178. return this;
  179. };
  180. /**
  181. * Sets the delay between reconnections.
  182. *
  183. * @param {Number} delay
  184. * @return {Manager} self or value
  185. * @api public
  186. */
  187. Manager.prototype.reconnectionDelay = function(v){
  188. if (!arguments.length) return this._reconnectionDelay;
  189. this._reconnectionDelay = v;
  190. this.backoff && this.backoff.setMin(v);
  191. return this;
  192. };
  193. Manager.prototype.randomizationFactor = function(v){
  194. if (!arguments.length) return this._randomizationFactor;
  195. this._randomizationFactor = v;
  196. this.backoff && this.backoff.setJitter(v);
  197. return this;
  198. };
  199. /**
  200. * Sets the maximum delay between reconnections.
  201. *
  202. * @param {Number} delay
  203. * @return {Manager} self or value
  204. * @api public
  205. */
  206. Manager.prototype.reconnectionDelayMax = function(v){
  207. if (!arguments.length) return this._reconnectionDelayMax;
  208. this._reconnectionDelayMax = v;
  209. this.backoff && this.backoff.setMax(v);
  210. return this;
  211. };
  212. /**
  213. * Sets the connection timeout. `false` to disable
  214. *
  215. * @return {Manager} self or value
  216. * @api public
  217. */
  218. Manager.prototype.timeout = function(v){
  219. if (!arguments.length) return this._timeout;
  220. this._timeout = v;
  221. return this;
  222. };
  223. /**
  224. * Starts trying to reconnect if reconnection is enabled and we have not
  225. * started reconnecting yet
  226. *
  227. * @api private
  228. */
  229. Manager.prototype.maybeReconnectOnOpen = function() {
  230. // Only try to reconnect if it's the first time we're connecting
  231. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  232. // keeps reconnection from firing twice for the same reconnection loop
  233. this.reconnect();
  234. }
  235. };
  236. /**
  237. * Sets the current transport `socket`.
  238. *
  239. * @param {Function} optional, callback
  240. * @return {Manager} self
  241. * @api public
  242. */
  243. Manager.prototype.open =
  244. Manager.prototype.connect = function(fn){
  245. debug('readyState %s', this.readyState);
  246. if (~this.readyState.indexOf('open')) return this;
  247. debug('opening %s', this.uri);
  248. this.engine = eio(this.uri, this.opts);
  249. var socket = this.engine;
  250. var self = this;
  251. this.readyState = 'opening';
  252. this.skipReconnect = false;
  253. // emit `open`
  254. var openSub = on(socket, 'open', function() {
  255. self.onopen();
  256. fn && fn();
  257. });
  258. // emit `connect_error`
  259. var errorSub = on(socket, 'error', function(data){
  260. debug('connect_error');
  261. self.cleanup();
  262. self.readyState = 'closed';
  263. self.emitAll('connect_error', data);
  264. if (fn) {
  265. var err = new Error('Connection error');
  266. err.data = data;
  267. fn(err);
  268. } else {
  269. // Only do this if there is no fn to handle the error
  270. self.maybeReconnectOnOpen();
  271. }
  272. });
  273. // emit `connect_timeout`
  274. if (false !== this._timeout) {
  275. var timeout = this._timeout;
  276. debug('connect attempt will timeout after %d', timeout);
  277. // set timer
  278. var timer = setTimeout(function(){
  279. debug('connect attempt timed out after %d', timeout);
  280. openSub.destroy();
  281. socket.close();
  282. socket.emit('error', 'timeout');
  283. self.emitAll('connect_timeout', timeout);
  284. }, timeout);
  285. this.subs.push({
  286. destroy: function(){
  287. clearTimeout(timer);
  288. }
  289. });
  290. }
  291. this.subs.push(openSub);
  292. this.subs.push(errorSub);
  293. return this;
  294. };
  295. /**
  296. * Called upon transport open.
  297. *
  298. * @api private
  299. */
  300. Manager.prototype.onopen = function(){
  301. debug('open');
  302. // clear old subs
  303. this.cleanup();
  304. // mark as open
  305. this.readyState = 'open';
  306. this.emit('open');
  307. // add new subs
  308. var socket = this.engine;
  309. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  310. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  311. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  312. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  313. };
  314. /**
  315. * Called with data.
  316. *
  317. * @api private
  318. */
  319. Manager.prototype.ondata = function(data){
  320. this.decoder.add(data);
  321. };
  322. /**
  323. * Called when parser fully decodes a packet.
  324. *
  325. * @api private
  326. */
  327. Manager.prototype.ondecoded = function(packet) {
  328. this.emit('packet', packet);
  329. };
  330. /**
  331. * Called upon socket error.
  332. *
  333. * @api private
  334. */
  335. Manager.prototype.onerror = function(err){
  336. debug('error', err);
  337. this.emitAll('error', err);
  338. };
  339. /**
  340. * Creates a new socket for the given `nsp`.
  341. *
  342. * @return {Socket}
  343. * @api public
  344. */
  345. Manager.prototype.socket = function(nsp){
  346. var socket = this.nsps[nsp];
  347. if (!socket) {
  348. socket = new Socket(this, nsp);
  349. this.nsps[nsp] = socket;
  350. var self = this;
  351. socket.on('connect', function(){
  352. socket.id = self.engine.id;
  353. if (!~indexOf(self.connected, socket)) {
  354. self.connected.push(socket);
  355. }
  356. });
  357. }
  358. return socket;
  359. };
  360. /**
  361. * Called upon a socket close.
  362. *
  363. * @param {Socket} socket
  364. */
  365. Manager.prototype.destroy = function(socket){
  366. var index = indexOf(this.connected, socket);
  367. if (~index) this.connected.splice(index, 1);
  368. if (this.connected.length) return;
  369. this.close();
  370. };
  371. /**
  372. * Writes a packet.
  373. *
  374. * @param {Object} packet
  375. * @api private
  376. */
  377. Manager.prototype.packet = function(packet){
  378. debug('writing packet %j', packet);
  379. var self = this;
  380. if (!self.encoding) {
  381. // encode, then write to engine with result
  382. self.encoding = true;
  383. this.encoder.encode(packet, function(encodedPackets) {
  384. for (var i = 0; i < encodedPackets.length; i++) {
  385. self.engine.write(encodedPackets[i]);
  386. }
  387. self.encoding = false;
  388. self.processPacketQueue();
  389. });
  390. } else { // add packet to the queue
  391. self.packetBuffer.push(packet);
  392. }
  393. };
  394. /**
  395. * If packet buffer is non-empty, begins encoding the
  396. * next packet in line.
  397. *
  398. * @api private
  399. */
  400. Manager.prototype.processPacketQueue = function() {
  401. if (this.packetBuffer.length > 0 && !this.encoding) {
  402. var pack = this.packetBuffer.shift();
  403. this.packet(pack);
  404. }
  405. };
  406. /**
  407. * Clean up transport subscriptions and packet buffer.
  408. *
  409. * @api private
  410. */
  411. Manager.prototype.cleanup = function(){
  412. var sub;
  413. while (sub = this.subs.shift()) sub.destroy();
  414. this.packetBuffer = [];
  415. this.encoding = false;
  416. this.decoder.destroy();
  417. };
  418. /**
  419. * Close the current socket.
  420. *
  421. * @api private
  422. */
  423. Manager.prototype.close =
  424. Manager.prototype.disconnect = function(){
  425. this.skipReconnect = true;
  426. this.backoff.reset();
  427. this.readyState = 'closed';
  428. this.engine && this.engine.close();
  429. };
  430. /**
  431. * Called upon engine close.
  432. *
  433. * @api private
  434. */
  435. Manager.prototype.onclose = function(reason){
  436. debug('close');
  437. this.cleanup();
  438. this.backoff.reset();
  439. this.readyState = 'closed';
  440. this.emit('close', reason);
  441. if (this._reconnection && !this.skipReconnect) {
  442. this.reconnect();
  443. }
  444. };
  445. /**
  446. * Attempt a reconnection.
  447. *
  448. * @api private
  449. */
  450. Manager.prototype.reconnect = function(){
  451. if (this.reconnecting || this.skipReconnect) return this;
  452. var self = this;
  453. if (this.backoff.attempts >= this._reconnectionAttempts) {
  454. debug('reconnect failed');
  455. this.backoff.reset();
  456. this.emitAll('reconnect_failed');
  457. this.reconnecting = false;
  458. } else {
  459. var delay = this.backoff.duration();
  460. debug('will wait %dms before reconnect attempt', delay);
  461. this.reconnecting = true;
  462. var timer = setTimeout(function(){
  463. if (self.skipReconnect) return;
  464. debug('attempting reconnect');
  465. self.emitAll('reconnect_attempt', self.backoff.attempts);
  466. self.emitAll('reconnecting', self.backoff.attempts);
  467. // check again for the case socket closed in above events
  468. if (self.skipReconnect) return;
  469. self.open(function(err){
  470. if (err) {
  471. debug('reconnect attempt error');
  472. self.reconnecting = false;
  473. self.reconnect();
  474. self.emitAll('reconnect_error', err.data);
  475. } else {
  476. debug('reconnect success');
  477. self.onreconnect();
  478. }
  479. });
  480. }, delay);
  481. this.subs.push({
  482. destroy: function(){
  483. clearTimeout(timer);
  484. }
  485. });
  486. }
  487. };
  488. /**
  489. * Called upon successful reconnect.
  490. *
  491. * @api private
  492. */
  493. Manager.prototype.onreconnect = function(){
  494. var attempt = this.backoff.attempts;
  495. this.reconnecting = false;
  496. this.backoff.reset();
  497. this.updateSocketIds();
  498. this.emitAll('reconnect', attempt);
  499. };
  500. },{"./on":4,"./socket":5,"./url":6,"backo2":7,"component-bind":8,"component-emitter":9,"debug":10,"engine.io-client":11,"indexof":40,"object-component":41,"socket.io-parser":44}],4:[function(_dereq_,module,exports){
  501. /**
  502. * Module exports.
  503. */
  504. module.exports = on;
  505. /**
  506. * Helper for subscriptions.
  507. *
  508. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  509. * @param {String} event name
  510. * @param {Function} callback
  511. * @api public
  512. */
  513. function on(obj, ev, fn) {
  514. obj.on(ev, fn);
  515. return {
  516. destroy: function(){
  517. obj.removeListener(ev, fn);
  518. }
  519. };
  520. }
  521. },{}],5:[function(_dereq_,module,exports){
  522. /**
  523. * Module dependencies.
  524. */
  525. var parser = _dereq_('socket.io-parser');
  526. var Emitter = _dereq_('component-emitter');
  527. var toArray = _dereq_('to-array');
  528. var on = _dereq_('./on');
  529. var bind = _dereq_('component-bind');
  530. var debug = _dereq_('debug')('socket.io-client:socket');
  531. var hasBin = _dereq_('has-binary');
  532. /**
  533. * Module exports.
  534. */
  535. module.exports = exports = Socket;
  536. /**
  537. * Internal events (blacklisted).
  538. * These events can't be emitted by the user.
  539. *
  540. * @api private
  541. */
  542. var events = {
  543. connect: 1,
  544. connect_error: 1,
  545. connect_timeout: 1,
  546. disconnect: 1,
  547. error: 1,
  548. reconnect: 1,
  549. reconnect_attempt: 1,
  550. reconnect_failed: 1,
  551. reconnect_error: 1,
  552. reconnecting: 1
  553. };
  554. /**
  555. * Shortcut to `Emitter#emit`.
  556. */
  557. var emit = Emitter.prototype.emit;
  558. /**
  559. * `Socket` constructor.
  560. *
  561. * @api public
  562. */
  563. function Socket(io, nsp){
  564. this.io = io;
  565. this.nsp = nsp;
  566. this.json = this; // compat
  567. this.ids = 0;
  568. this.acks = {};
  569. if (this.io.autoConnect) this.open();
  570. this.receiveBuffer = [];
  571. this.sendBuffer = [];
  572. this.connected = false;
  573. this.disconnected = true;
  574. }
  575. /**
  576. * Mix in `Emitter`.
  577. */
  578. Emitter(Socket.prototype);
  579. /**
  580. * Subscribe to open, close and packet events
  581. *
  582. * @api private
  583. */
  584. Socket.prototype.subEvents = function() {
  585. if (this.subs) return;
  586. var io = this.io;
  587. this.subs = [
  588. on(io, 'open', bind(this, 'onopen')),
  589. on(io, 'packet', bind(this, 'onpacket')),
  590. on(io, 'close', bind(this, 'onclose'))
  591. ];
  592. };
  593. /**
  594. * "Opens" the socket.
  595. *
  596. * @api public
  597. */
  598. Socket.prototype.open =
  599. Socket.prototype.connect = function(){
  600. if (this.connected) return this;
  601. this.subEvents();
  602. this.io.open(); // ensure open
  603. if ('open' == this.io.readyState) this.onopen();
  604. return this;
  605. };
  606. /**
  607. * Sends a `message` event.
  608. *
  609. * @return {Socket} self
  610. * @api public
  611. */
  612. Socket.prototype.send = function(){
  613. var args = toArray(arguments);
  614. args.unshift('message');
  615. this.emit.apply(this, args);
  616. return this;
  617. };
  618. /**
  619. * Override `emit`.
  620. * If the event is in `events`, it's emitted normally.
  621. *
  622. * @param {String} event name
  623. * @return {Socket} self
  624. * @api public
  625. */
  626. Socket.prototype.emit = function(ev){
  627. if (events.hasOwnProperty(ev)) {
  628. emit.apply(this, arguments);
  629. return this;
  630. }
  631. var args = toArray(arguments);
  632. var parserType = parser.EVENT; // default
  633. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  634. var packet = { type: parserType, data: args };
  635. // event ack callback
  636. if ('function' == typeof args[args.length - 1]) {
  637. debug('emitting packet with ack id %d', this.ids);
  638. this.acks[this.ids] = args.pop();
  639. packet.id = this.ids++;
  640. }
  641. if (this.connected) {
  642. this.packet(packet);
  643. } else {
  644. this.sendBuffer.push(packet);
  645. }
  646. return this;
  647. };
  648. /**
  649. * Sends a packet.
  650. *
  651. * @param {Object} packet
  652. * @api private
  653. */
  654. Socket.prototype.packet = function(packet){
  655. packet.nsp = this.nsp;
  656. this.io.packet(packet);
  657. };
  658. /**
  659. * Called upon engine `open`.
  660. *
  661. * @api private
  662. */
  663. Socket.prototype.onopen = function(){
  664. debug('transport is open - connecting');
  665. // write connect packet if necessary
  666. if ('/' != this.nsp) {
  667. this.packet({ type: parser.CONNECT });
  668. }
  669. };
  670. /**
  671. * Called upon engine `close`.
  672. *
  673. * @param {String} reason
  674. * @api private
  675. */
  676. Socket.prototype.onclose = function(reason){
  677. debug('close (%s)', reason);
  678. this.connected = false;
  679. this.disconnected = true;
  680. delete this.id;
  681. this.emit('disconnect', reason);
  682. };
  683. /**
  684. * Called with socket packet.
  685. *
  686. * @param {Object} packet
  687. * @api private
  688. */
  689. Socket.prototype.onpacket = function(packet){
  690. if (packet.nsp != this.nsp) return;
  691. switch (packet.type) {
  692. case parser.CONNECT:
  693. this.onconnect();
  694. break;
  695. case parser.EVENT:
  696. this.onevent(packet);
  697. break;
  698. case parser.BINARY_EVENT:
  699. this.onevent(packet);
  700. break;
  701. case parser.ACK:
  702. this.onack(packet);
  703. break;
  704. case parser.BINARY_ACK:
  705. this.onack(packet);
  706. break;
  707. case parser.DISCONNECT:
  708. this.ondisconnect();
  709. break;
  710. case parser.ERROR:
  711. this.emit('error', packet.data);
  712. break;
  713. }
  714. };
  715. /**
  716. * Called upon a server event.
  717. *
  718. * @param {Object} packet
  719. * @api private
  720. */
  721. Socket.prototype.onevent = function(packet){
  722. var args = packet.data || [];
  723. debug('emitting event %j', args);
  724. if (null != packet.id) {
  725. debug('attaching ack callback to event');
  726. args.push(this.ack(packet.id));
  727. }
  728. if (this.connected) {
  729. emit.apply(this, args);
  730. } else {
  731. this.receiveBuffer.push(args);
  732. }
  733. };
  734. /**
  735. * Produces an ack callback to emit with an event.
  736. *
  737. * @api private
  738. */
  739. Socket.prototype.ack = function(id){
  740. var self = this;
  741. var sent = false;
  742. return function(){
  743. // prevent double callbacks
  744. if (sent) return;
  745. sent = true;
  746. var args = toArray(arguments);
  747. debug('sending ack %j', args);
  748. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  749. self.packet({
  750. type: type,
  751. id: id,
  752. data: args
  753. });
  754. };
  755. };
  756. /**
  757. * Called upon a server acknowlegement.
  758. *
  759. * @param {Object} packet
  760. * @api private
  761. */
  762. Socket.prototype.onack = function(packet){
  763. debug('calling ack %s with %j', packet.id, packet.data);
  764. var fn = this.acks[packet.id];
  765. fn.apply(this, packet.data);
  766. delete this.acks[packet.id];
  767. };
  768. /**
  769. * Called upon server connect.
  770. *
  771. * @api private
  772. */
  773. Socket.prototype.onconnect = function(){
  774. this.connected = true;
  775. this.disconnected = false;
  776. this.emit('connect');
  777. this.emitBuffered();
  778. };
  779. /**
  780. * Emit buffered events (received and emitted).
  781. *
  782. * @api private
  783. */
  784. Socket.prototype.emitBuffered = function(){
  785. var i;
  786. for (i = 0; i < this.receiveBuffer.length; i++) {
  787. emit.apply(this, this.receiveBuffer[i]);
  788. }
  789. this.receiveBuffer = [];
  790. for (i = 0; i < this.sendBuffer.length; i++) {
  791. this.packet(this.sendBuffer[i]);
  792. }
  793. this.sendBuffer = [];
  794. };
  795. /**
  796. * Called upon server disconnect.
  797. *
  798. * @api private
  799. */
  800. Socket.prototype.ondisconnect = function(){
  801. debug('server disconnect (%s)', this.nsp);
  802. this.destroy();
  803. this.onclose('io server disconnect');
  804. };
  805. /**
  806. * Called upon forced client/server side disconnections,
  807. * this method ensures the manager stops tracking us and
  808. * that reconnections don't get triggered for this.
  809. *
  810. * @api private.
  811. */
  812. Socket.prototype.destroy = function(){
  813. if (this.subs) {
  814. // clean subscriptions to avoid reconnections
  815. for (var i = 0; i < this.subs.length; i++) {
  816. this.subs[i].destroy();
  817. }
  818. this.subs = null;
  819. }
  820. this.io.destroy(this);
  821. };
  822. /**
  823. * Disconnects the socket manually.
  824. *
  825. * @return {Socket} self
  826. * @api public
  827. */
  828. Socket.prototype.close =
  829. Socket.prototype.disconnect = function(){
  830. if (this.connected) {
  831. debug('performing disconnect (%s)', this.nsp);
  832. this.packet({ type: parser.DISCONNECT });
  833. }
  834. // remove socket from pool
  835. this.destroy();
  836. if (this.connected) {
  837. // fire events
  838. this.onclose('io client disconnect');
  839. }
  840. return this;
  841. };
  842. },{"./on":4,"component-bind":8,"component-emitter":9,"debug":10,"has-binary":36,"socket.io-parser":44,"to-array":48}],6:[function(_dereq_,module,exports){
  843. (function (global){
  844. /**
  845. * Module dependencies.
  846. */
  847. var parseuri = _dereq_('parseuri');
  848. var debug = _dereq_('debug')('socket.io-client:url');
  849. /**
  850. * Module exports.
  851. */
  852. module.exports = url;
  853. /**
  854. * URL parser.
  855. *
  856. * @param {String} url
  857. * @param {Object} An object meant to mimic window.location.
  858. * Defaults to window.location.
  859. * @api public
  860. */
  861. function url(uri, loc){
  862. var obj = uri;
  863. // default to window.location
  864. var loc = loc || global.location;
  865. if (null == uri) uri = loc.protocol + '//' + loc.host;
  866. // relative path support
  867. if ('string' == typeof uri) {
  868. if ('/' == uri.charAt(0)) {
  869. if ('/' == uri.charAt(1)) {
  870. uri = loc.protocol + uri;
  871. } else {
  872. uri = loc.hostname + uri;
  873. }
  874. }
  875. if (!/^(https?|wss?):\/\//.test(uri)) {
  876. debug('protocol-less url %s', uri);
  877. if ('undefined' != typeof loc) {
  878. uri = loc.protocol + '//' + uri;
  879. } else {
  880. uri = 'https://' + uri;
  881. }
  882. }
  883. // parse
  884. debug('parse %s', uri);
  885. obj = parseuri(uri);
  886. }
  887. // make sure we treat `localhost:80` and `localhost` equally
  888. if (!obj.port) {
  889. if (/^(http|ws)$/.test(obj.protocol)) {
  890. obj.port = '80';
  891. }
  892. else if (/^(http|ws)s$/.test(obj.protocol)) {
  893. obj.port = '443';
  894. }
  895. }
  896. obj.path = obj.path || '/';
  897. // define unique id
  898. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  899. // define href
  900. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  901. return obj;
  902. }
  903. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  904. },{"debug":10,"parseuri":42}],7:[function(_dereq_,module,exports){
  905. /**
  906. * Expose `Backoff`.
  907. */
  908. module.exports = Backoff;
  909. /**
  910. * Initialize backoff timer with `opts`.
  911. *
  912. * - `min` initial timeout in milliseconds [100]
  913. * - `max` max timeout [10000]
  914. * - `jitter` [0]
  915. * - `factor` [2]
  916. *
  917. * @param {Object} opts
  918. * @api public
  919. */
  920. function Backoff(opts) {
  921. opts = opts || {};
  922. this.ms = opts.min || 100;
  923. this.max = opts.max || 10000;
  924. this.factor = opts.factor || 2;
  925. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  926. this.attempts = 0;
  927. }
  928. /**
  929. * Return the backoff duration.
  930. *
  931. * @return {Number}
  932. * @api public
  933. */
  934. Backoff.prototype.duration = function(){
  935. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  936. if (this.jitter) {
  937. var rand = Math.random();
  938. var deviation = Math.floor(rand * this.jitter * ms);
  939. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  940. }
  941. return Math.min(ms, this.max) | 0;
  942. };
  943. /**
  944. * Reset the number of attempts.
  945. *
  946. * @api public
  947. */
  948. Backoff.prototype.reset = function(){
  949. this.attempts = 0;
  950. };
  951. /**
  952. * Set the minimum duration
  953. *
  954. * @api public
  955. */
  956. Backoff.prototype.setMin = function(min){
  957. this.ms = min;
  958. };
  959. /**
  960. * Set the maximum duration
  961. *
  962. * @api public
  963. */
  964. Backoff.prototype.setMax = function(max){
  965. this.max = max;
  966. };
  967. /**
  968. * Set the jitter
  969. *
  970. * @api public
  971. */
  972. Backoff.prototype.setJitter = function(jitter){
  973. this.jitter = jitter;
  974. };
  975. },{}],8:[function(_dereq_,module,exports){
  976. /**
  977. * Slice reference.
  978. */
  979. var slice = [].slice;
  980. /**
  981. * Bind `obj` to `fn`.
  982. *
  983. * @param {Object} obj
  984. * @param {Function|String} fn or string
  985. * @return {Function}
  986. * @api public
  987. */
  988. module.exports = function(obj, fn){
  989. if ('string' == typeof fn) fn = obj[fn];
  990. if ('function' != typeof fn) throw new Error('bind() requires a function');
  991. var args = slice.call(arguments, 2);
  992. return function(){
  993. return fn.apply(obj, args.concat(slice.call(arguments)));
  994. }
  995. };
  996. },{}],9:[function(_dereq_,module,exports){
  997. /**
  998. * Expose `Emitter`.
  999. */
  1000. module.exports = Emitter;
  1001. /**
  1002. * Initialize a new `Emitter`.
  1003. *
  1004. * @api public
  1005. */
  1006. function Emitter(obj) {
  1007. if (obj) return mixin(obj);
  1008. };
  1009. /**
  1010. * Mixin the emitter properties.
  1011. *
  1012. * @param {Object} obj
  1013. * @return {Object}
  1014. * @api private
  1015. */
  1016. function mixin(obj) {
  1017. for (var key in Emitter.prototype) {
  1018. obj[key] = Emitter.prototype[key];
  1019. }
  1020. return obj;
  1021. }
  1022. /**
  1023. * Listen on the given `event` with `fn`.
  1024. *
  1025. * @param {String} event
  1026. * @param {Function} fn
  1027. * @return {Emitter}
  1028. * @api public
  1029. */
  1030. Emitter.prototype.on =
  1031. Emitter.prototype.addEventListener = function(event, fn){
  1032. this._callbacks = this._callbacks || {};
  1033. (this._callbacks[event] = this._callbacks[event] || [])
  1034. .push(fn);
  1035. return this;
  1036. };
  1037. /**
  1038. * Adds an `event` listener that will be invoked a single
  1039. * time then automatically removed.
  1040. *
  1041. * @param {String} event
  1042. * @param {Function} fn
  1043. * @return {Emitter}
  1044. * @api public
  1045. */
  1046. Emitter.prototype.once = function(event, fn){
  1047. var self = this;
  1048. this._callbacks = this._callbacks || {};
  1049. function on() {
  1050. self.off(event, on);
  1051. fn.apply(this, arguments);
  1052. }
  1053. on.fn = fn;
  1054. this.on(event, on);
  1055. return this;
  1056. };
  1057. /**
  1058. * Remove the given callback for `event` or all
  1059. * registered callbacks.
  1060. *
  1061. * @param {String} event
  1062. * @param {Function} fn
  1063. * @return {Emitter}
  1064. * @api public
  1065. */
  1066. Emitter.prototype.off =
  1067. Emitter.prototype.removeListener =
  1068. Emitter.prototype.removeAllListeners =
  1069. Emitter.prototype.removeEventListener = function(event, fn){
  1070. this._callbacks = this._callbacks || {};
  1071. // all
  1072. if (0 == arguments.length) {
  1073. this._callbacks = {};
  1074. return this;
  1075. }
  1076. // specific event
  1077. var callbacks = this._callbacks[event];
  1078. if (!callbacks) return this;
  1079. // remove all handlers
  1080. if (1 == arguments.length) {
  1081. delete this._callbacks[event];
  1082. return this;
  1083. }
  1084. // remove specific handler
  1085. var cb;
  1086. for (var i = 0; i < callbacks.length; i++) {
  1087. cb = callbacks[i];
  1088. if (cb === fn || cb.fn === fn) {
  1089. callbacks.splice(i, 1);
  1090. break;
  1091. }
  1092. }
  1093. return this;
  1094. };
  1095. /**
  1096. * Emit `event` with the given args.
  1097. *
  1098. * @param {String} event
  1099. * @param {Mixed} ...
  1100. * @return {Emitter}
  1101. */
  1102. Emitter.prototype.emit = function(event){
  1103. this._callbacks = this._callbacks || {};
  1104. var args = [].slice.call(arguments, 1)
  1105. , callbacks = this._callbacks[event];
  1106. if (callbacks) {
  1107. callbacks = callbacks.slice(0);
  1108. for (var i = 0, len = callbacks.length; i < len; ++i) {
  1109. callbacks[i].apply(this, args);
  1110. }
  1111. }
  1112. return this;
  1113. };
  1114. /**
  1115. * Return array of callbacks for `event`.
  1116. *
  1117. * @param {String} event
  1118. * @return {Array}
  1119. * @api public
  1120. */
  1121. Emitter.prototype.listeners = function(event){
  1122. this._callbacks = this._callbacks || {};
  1123. return this._callbacks[event] || [];
  1124. };
  1125. /**
  1126. * Check if this emitter has `event` handlers.
  1127. *
  1128. * @param {String} event
  1129. * @return {Boolean}
  1130. * @api public
  1131. */
  1132. Emitter.prototype.hasListeners = function(event){
  1133. return !! this.listeners(event).length;
  1134. };
  1135. },{}],10:[function(_dereq_,module,exports){
  1136. /**
  1137. * Expose `debug()` as the module.
  1138. */
  1139. module.exports = debug;
  1140. /**
  1141. * Create a debugger with the given `name`.
  1142. *
  1143. * @param {String} name
  1144. * @return {Type}
  1145. * @api public
  1146. */
  1147. function debug(name) {
  1148. if (!debug.enabled(name)) return function(){};
  1149. return function(fmt){
  1150. fmt = coerce(fmt);
  1151. var curr = new Date;
  1152. var ms = curr - (debug[name] || curr);
  1153. debug[name] = curr;
  1154. fmt = name
  1155. + ' '
  1156. + fmt
  1157. + ' +' + debug.humanize(ms);
  1158. // This hackery is required for IE8
  1159. // where `console.log` doesn't have 'apply'
  1160. window.console
  1161. && console.log
  1162. && Function.prototype.apply.call(console.log, console, arguments);
  1163. }
  1164. }
  1165. /**
  1166. * The currently active debug mode names.
  1167. */
  1168. debug.names = [];
  1169. debug.skips = [];
  1170. /**
  1171. * Enables a debug mode by name. This can include modes
  1172. * separated by a colon and wildcards.
  1173. *
  1174. * @param {String} name
  1175. * @api public
  1176. */
  1177. debug.enable = function(name) {
  1178. try {
  1179. localStorage.debug = name;
  1180. } catch(e){}
  1181. var split = (name || '').split(/[\s,]+/)
  1182. , len = split.length;
  1183. for (var i = 0; i < len; i++) {
  1184. name = split[i].replace('*', '.*?');
  1185. if (name[0] === '-') {
  1186. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  1187. }
  1188. else {
  1189. debug.names.push(new RegExp('^' + name + '$'));
  1190. }
  1191. }
  1192. };
  1193. /**
  1194. * Disable debug output.
  1195. *
  1196. * @api public
  1197. */
  1198. debug.disable = function(){
  1199. debug.enable('');
  1200. };
  1201. /**
  1202. * Humanize the given `ms`.
  1203. *
  1204. * @param {Number} m
  1205. * @return {String}
  1206. * @api private
  1207. */
  1208. debug.humanize = function(ms) {
  1209. var sec = 1000
  1210. , min = 60 * 1000
  1211. , hour = 60 * min;
  1212. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  1213. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  1214. if (ms >= sec) return (ms / sec | 0) + 's';
  1215. return ms + 'ms';
  1216. };
  1217. /**
  1218. * Returns true if the given mode name is enabled, false otherwise.
  1219. *
  1220. * @param {String} name
  1221. * @return {Boolean}
  1222. * @api public
  1223. */
  1224. debug.enabled = function(name) {
  1225. for (var i = 0, len = debug.skips.length; i < len; i++) {
  1226. if (debug.skips[i].test(name)) {
  1227. return false;
  1228. }
  1229. }
  1230. for (var i = 0, len = debug.names.length; i < len; i++) {
  1231. if (debug.names[i].test(name)) {
  1232. return true;
  1233. }
  1234. }
  1235. return false;
  1236. };
  1237. /**
  1238. * Coerce `val`.
  1239. */
  1240. function coerce(val) {
  1241. if (val instanceof Error) return val.stack || val.message;
  1242. return val;
  1243. }
  1244. // persist
  1245. try {
  1246. if (window.localStorage) debug.enable(localStorage.debug);
  1247. } catch(e){}
  1248. },{}],11:[function(_dereq_,module,exports){
  1249. module.exports = _dereq_('./lib/');
  1250. },{"./lib/":12}],12:[function(_dereq_,module,exports){
  1251. module.exports = _dereq_('./socket');
  1252. /**
  1253. * Exports parser
  1254. *
  1255. * @api public
  1256. *
  1257. */
  1258. module.exports.parser = _dereq_('engine.io-parser');
  1259. },{"./socket":13,"engine.io-parser":25}],13:[function(_dereq_,module,exports){
  1260. (function (global){
  1261. /**
  1262. * Module dependencies.
  1263. */
  1264. var transports = _dereq_('./transports');
  1265. var Emitter = _dereq_('component-emitter');
  1266. var debug = _dereq_('debug')('engine.io-client:socket');
  1267. var index = _dereq_('indexof');
  1268. var parser = _dereq_('engine.io-parser');
  1269. var parseuri = _dereq_('parseuri');
  1270. var parsejson = _dereq_('parsejson');
  1271. var parseqs = _dereq_('parseqs');
  1272. /**
  1273. * Module exports.
  1274. */
  1275. module.exports = Socket;
  1276. /**
  1277. * Noop function.
  1278. *
  1279. * @api private
  1280. */
  1281. function noop(){}
  1282. /**
  1283. * Socket constructor.
  1284. *
  1285. * @param {String|Object} uri or options
  1286. * @param {Object} options
  1287. * @api public
  1288. */
  1289. function Socket(uri, opts){
  1290. if (!(this instanceof Socket)) return new Socket(uri, opts);
  1291. opts = opts || {};
  1292. if (uri && 'object' == typeof uri) {
  1293. opts = uri;
  1294. uri = null;
  1295. }
  1296. if (uri) {
  1297. uri = parseuri(uri);
  1298. opts.host = uri.host;
  1299. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  1300. opts.port = uri.port;
  1301. if (uri.query) opts.query = uri.query;
  1302. }
  1303. this.secure = null != opts.secure ? opts.secure :
  1304. (global.location && 'https:' == location.protocol);
  1305. if (opts.host) {
  1306. var pieces = opts.host.split(':');
  1307. opts.hostname = pieces.shift();
  1308. if (pieces.length) {
  1309. opts.port = pieces.pop();
  1310. } else if (!opts.port) {
  1311. // if no port is specified manually, use the protocol default
  1312. opts.port = this.secure ? '443' : '80';
  1313. }
  1314. }
  1315. this.agent = opts.agent || false;
  1316. this.hostname = opts.hostname ||
  1317. (global.location ? location.hostname : 'localhost');
  1318. this.port = opts.port || (global.location && location.port ?
  1319. location.port :
  1320. (this.secure ? 443 : 80));
  1321. this.query = opts.query || {};
  1322. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  1323. this.upgrade = false !== opts.upgrade;
  1324. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  1325. this.forceJSONP = !!opts.forceJSONP;
  1326. this.jsonp = false !== opts.jsonp;
  1327. this.forceBase64 = !!opts.forceBase64;
  1328. this.enablesXDR = !!opts.enablesXDR;
  1329. this.timestampParam = opts.timestampParam || 't';
  1330. this.timestampRequests = opts.timestampRequests;
  1331. this.transports = opts.transports || ['polling', 'websocket'];
  1332. this.readyState = '';
  1333. this.writeBuffer = [];
  1334. this.callbackBuffer = [];
  1335. this.policyPort = opts.policyPort || 843;
  1336. this.rememberUpgrade = opts.rememberUpgrade || false;
  1337. this.binaryType = null;
  1338. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  1339. // SSL options for Node.js client
  1340. this.pfx = opts.pfx || null;
  1341. this.key = opts.key || null;
  1342. this.passphrase = opts.passphrase || null;
  1343. this.cert = opts.cert || null;
  1344. this.ca = opts.ca || null;
  1345. this.ciphers = opts.ciphers || null;
  1346. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  1347. this.open();
  1348. }
  1349. Socket.priorWebsocketSuccess = false;
  1350. /**
  1351. * Mix in `Emitter`.
  1352. */
  1353. Emitter(Socket.prototype);
  1354. /**
  1355. * Protocol version.
  1356. *
  1357. * @api public
  1358. */
  1359. Socket.protocol = parser.protocol; // this is an int
  1360. /**
  1361. * Expose deps for legacy compatibility
  1362. * and standalone browser access.
  1363. */
  1364. Socket.Socket = Socket;
  1365. Socket.Transport = _dereq_('./transport');
  1366. Socket.transports = _dereq_('./transports');
  1367. Socket.parser = _dereq_('engine.io-parser');
  1368. /**
  1369. * Creates transport of the given type.
  1370. *
  1371. * @param {String} transport name
  1372. * @return {Transport}
  1373. * @api private
  1374. */
  1375. Socket.prototype.createTransport = function (name) {
  1376. debug('creating transport "%s"', name);
  1377. var query = clone(this.query);
  1378. // append engine.io protocol identifier
  1379. query.EIO = parser.protocol;
  1380. // transport name
  1381. query.transport = name;
  1382. // session id if we already have one
  1383. if (this.id) query.sid = this.id;
  1384. var transport = new transports[name]({
  1385. agent: this.agent,
  1386. hostname: this.hostname,
  1387. port: this.port,
  1388. secure: this.secure,
  1389. path: this.path,
  1390. query: query,
  1391. forceJSONP: this.forceJSONP,
  1392. jsonp: this.jsonp,
  1393. forceBase64: this.forceBase64,
  1394. enablesXDR: this.enablesXDR,
  1395. timestampRequests: this.timestampRequests,
  1396. timestampParam: this.timestampParam,
  1397. policyPort: this.policyPort,
  1398. socket: this,
  1399. pfx: this.pfx,
  1400. key: this.key,
  1401. passphrase: this.passphrase,
  1402. cert: this.cert,
  1403. ca: this.ca,
  1404. ciphers: this.ciphers,
  1405. rejectUnauthorized: this.rejectUnauthorized
  1406. });
  1407. return transport;
  1408. };
  1409. function clone (obj) {
  1410. var o = {};
  1411. for (var i in obj) {
  1412. if (obj.hasOwnProperty(i)) {
  1413. o[i] = obj[i];
  1414. }
  1415. }
  1416. return o;
  1417. }
  1418. /**
  1419. * Initializes transport to use and starts probe.
  1420. *
  1421. * @api private
  1422. */
  1423. Socket.prototype.open = function () {
  1424. var transport;
  1425. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  1426. transport = 'websocket';
  1427. } else if (0 == this.transports.length) {
  1428. // Emit error on next tick so it can be listened to
  1429. var self = this;
  1430. setTimeout(function() {
  1431. self.emit('error', 'No transports available');
  1432. }, 0);
  1433. return;
  1434. } else {
  1435. transport = this.transports[0];
  1436. }
  1437. this.readyState = 'opening';
  1438. // Retry with the next transport if the transport is disabled (jsonp: false)
  1439. var transport;
  1440. try {
  1441. transport = this.createTransport(transport);
  1442. } catch (e) {
  1443. this.transports.shift();
  1444. this.open();
  1445. return;
  1446. }
  1447. transport.open();
  1448. this.setTransport(transport);
  1449. };
  1450. /**
  1451. * Sets the current transport. Disables the existing one (if any).
  1452. *
  1453. * @api private
  1454. */
  1455. Socket.prototype.setTransport = function(transport){
  1456. debug('setting transport %s', transport.name);
  1457. var self = this;
  1458. if (this.transport) {
  1459. debug('clearing existing transport %s', this.transport.name);
  1460. this.transport.removeAllListeners();
  1461. }
  1462. // set up transport
  1463. this.transport = transport;
  1464. // set up transport listeners
  1465. transport
  1466. .on('drain', function(){
  1467. self.onDrain();
  1468. })
  1469. .on('packet', function(packet){
  1470. self.onPacket(packet);
  1471. })
  1472. .on('error', function(e){
  1473. self.onError(e);
  1474. })
  1475. .on('close', function(){
  1476. self.onClose('transport close');
  1477. });
  1478. };
  1479. /**
  1480. * Probes a transport.
  1481. *
  1482. * @param {String} transport name
  1483. * @api private
  1484. */
  1485. Socket.prototype.probe = function (name) {
  1486. debug('probing transport "%s"', name);
  1487. var transport = this.createTransport(name, { probe: 1 })
  1488. , failed = false
  1489. , self = this;
  1490. Socket.priorWebsocketSuccess = false;
  1491. function onTransportOpen(){
  1492. if (self.onlyBinaryUpgrades) {
  1493. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  1494. failed = failed || upgradeLosesBinary;
  1495. }
  1496. if (failed) return;
  1497. debug('probe transport "%s" opened', name);
  1498. transport.send([{ type: 'ping', data: 'probe' }]);
  1499. transport.once('packet', function (msg) {
  1500. if (failed) return;
  1501. if ('pong' == msg.type && 'probe' == msg.data) {
  1502. debug('probe transport "%s" pong', name);
  1503. self.upgrading = true;
  1504. self.emit('upgrading', transport);
  1505. if (!transport) return;
  1506. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  1507. debug('pausing current transport "%s"', self.transport.name);
  1508. self.transport.pause(function () {
  1509. if (failed) return;
  1510. if ('closed' == self.readyState) return;
  1511. debug('changing transport and sending upgrade packet');
  1512. cleanup();
  1513. self.setTransport(transport);
  1514. transport.send([{ type: 'upgrade' }]);
  1515. self.emit('upgrade', transport);
  1516. transport = null;
  1517. self.upgrading = false;
  1518. self.flush();
  1519. });
  1520. } else {
  1521. debug('probe transport "%s" failed', name);
  1522. var err = new Error('probe error');
  1523. err.transport = transport.name;
  1524. self.emit('upgradeError', err);
  1525. }
  1526. });
  1527. }
  1528. function freezeTransport() {
  1529. if (failed) return;
  1530. // Any callback called by transport should be ignored since now
  1531. failed = true;
  1532. cleanup();
  1533. transport.close();
  1534. transport = null;
  1535. }
  1536. //Handle any error that happens while probing
  1537. function onerror(err) {
  1538. var error = new Error('probe error: ' + err);
  1539. error.transport = transport.name;
  1540. freezeTransport();
  1541. debug('probe transport "%s" failed because of error: %s', name, err);
  1542. self.emit('upgradeError', error);
  1543. }
  1544. function onTransportClose(){
  1545. onerror("transport closed");
  1546. }
  1547. //When the socket is closed while we're probing
  1548. function onclose(){
  1549. onerror("socket closed");
  1550. }
  1551. //When the socket is upgraded while we're probing
  1552. function onupgrade(to){
  1553. if (transport && to.name != transport.name) {
  1554. debug('"%s" works - aborting "%s"', to.name, transport.name);
  1555. freezeTransport();
  1556. }
  1557. }
  1558. //Remove all listeners on the transport and on self
  1559. function cleanup(){
  1560. transport.removeListener('open', onTransportOpen);
  1561. transport.removeListener('error', onerror);
  1562. transport.removeListener('close', onTransportClose);
  1563. self.removeListener('close', onclose);
  1564. self.removeListener('upgrading', onupgrade);
  1565. }
  1566. transport.once('open', onTransportOpen);
  1567. transport.once('error', onerror);
  1568. transport.once('close', onTransportClose);
  1569. this.once('close', onclose);
  1570. this.once('upgrading', onupgrade);
  1571. transport.open();
  1572. };
  1573. /**
  1574. * Called when connection is deemed open.
  1575. *
  1576. * @api public
  1577. */
  1578. Socket.prototype.onOpen = function () {
  1579. debug('socket open');
  1580. this.readyState = 'open';
  1581. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  1582. this.emit('open');
  1583. this.flush();
  1584. // we check for `readyState` in case an `open`
  1585. // listener already closed the socket
  1586. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  1587. debug('starting upgrade probes');
  1588. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  1589. this.probe(this.upgrades[i]);
  1590. }
  1591. }
  1592. };
  1593. /**
  1594. * Handles a packet.
  1595. *
  1596. * @api private
  1597. */
  1598. Socket.prototype.onPacket = function (packet) {
  1599. if ('opening' == this.readyState || 'open' == this.readyState) {
  1600. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  1601. this.emit('packet', packet);
  1602. // Socket is live - any packet counts
  1603. this.emit('heartbeat');
  1604. switch (packet.type) {
  1605. case 'open':
  1606. this.onHandshake(parsejson(packet.data));
  1607. break;
  1608. case 'pong':
  1609. this.setPing();
  1610. break;
  1611. case 'error':
  1612. var err = new Error('server error');
  1613. err.code = packet.data;
  1614. this.emit('error', err);
  1615. break;
  1616. case 'message':
  1617. this.emit('data', packet.data);
  1618. this.emit('message', packet.data);
  1619. break;
  1620. }
  1621. } else {
  1622. debug('packet received with socket readyState "%s"', this.readyState);
  1623. }
  1624. };
  1625. /**
  1626. * Called upon handshake completion.
  1627. *
  1628. * @param {Object} handshake obj
  1629. * @api private
  1630. */
  1631. Socket.prototype.onHandshake = function (data) {
  1632. this.emit('handshake', data);
  1633. this.id = data.sid;
  1634. this.transport.query.sid = data.sid;
  1635. this.upgrades = this.filterUpgrades(data.upgrades);
  1636. this.pingInterval = data.pingInterval;
  1637. this.pingTimeout = data.pingTimeout;
  1638. this.onOpen();
  1639. // In case open handler closes socket
  1640. if ('closed' == this.readyState) return;
  1641. this.setPing();
  1642. // Prolong liveness of socket on heartbeat
  1643. this.removeListener('heartbeat', this.onHeartbeat);
  1644. this.on('heartbeat', this.onHeartbeat);
  1645. };
  1646. /**
  1647. * Resets ping timeout.
  1648. *
  1649. * @api private
  1650. */
  1651. Socket.prototype.onHeartbeat = function (timeout) {
  1652. clearTimeout(this.pingTimeoutTimer);
  1653. var self = this;
  1654. self.pingTimeoutTimer = setTimeout(function () {
  1655. if ('closed' == self.readyState) return;
  1656. self.onClose('ping timeout');
  1657. }, timeout || (self.pingInterval + self.pingTimeout));
  1658. };
  1659. /**
  1660. * Pings server every `this.pingInterval` and expects response
  1661. * within `this.pingTimeout` or closes connection.
  1662. *
  1663. * @api private
  1664. */
  1665. Socket.prototype.setPing = function () {
  1666. var self = this;
  1667. clearTimeout(self.pingIntervalTimer);
  1668. self.pingIntervalTimer = setTimeout(function () {
  1669. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  1670. self.ping();
  1671. self.onHeartbeat(self.pingTimeout);
  1672. }, self.pingInterval);
  1673. };
  1674. /**
  1675. * Sends a ping packet.
  1676. *
  1677. * @api public
  1678. */
  1679. Socket.prototype.ping = function () {
  1680. this.sendPacket('ping');
  1681. };
  1682. /**
  1683. * Called on `drain` event
  1684. *
  1685. * @api private
  1686. */
  1687. Socket.prototype.onDrain = function() {
  1688. for (var i = 0; i < this.prevBufferLen; i++) {
  1689. if (this.callbackBuffer[i]) {
  1690. this.callbackBuffer[i]();
  1691. }
  1692. }
  1693. this.writeBuffer.splice(0, this.prevBufferLen);
  1694. this.callbackBuffer.splice(0, this.prevBufferLen);
  1695. // setting prevBufferLen = 0 is very important
  1696. // for example, when upgrading, upgrade packet is sent over,
  1697. // and a nonzero prevBufferLen could cause problems on `drain`
  1698. this.prevBufferLen = 0;
  1699. if (this.writeBuffer.length == 0) {
  1700. this.emit('drain');
  1701. } else {
  1702. this.flush();
  1703. }
  1704. };
  1705. /**
  1706. * Flush write buffers.
  1707. *
  1708. * @api private
  1709. */
  1710. Socket.prototype.flush = function () {
  1711. if ('closed' != this.readyState && this.transport.writable &&
  1712. !this.upgrading && this.writeBuffer.length) {
  1713. debug('flushing %d packets in socket', this.writeBuffer.length);
  1714. this.transport.send(this.writeBuffer);
  1715. // keep track of current length of writeBuffer
  1716. // splice writeBuffer and callbackBuffer on `drain`
  1717. this.prevBufferLen = this.writeBuffer.length;
  1718. this.emit('flush');
  1719. }
  1720. };
  1721. /**
  1722. * Sends a message.
  1723. *
  1724. * @param {String} message.
  1725. * @param {Function} callback function.
  1726. * @return {Socket} for chaining.
  1727. * @api public
  1728. */
  1729. Socket.prototype.write =
  1730. Socket.prototype.send = function (msg, fn) {
  1731. this.sendPacket('message', msg, fn);
  1732. return this;
  1733. };
  1734. /**
  1735. * Sends a packet.
  1736. *
  1737. * @param {String} packet type.
  1738. * @param {String} data.
  1739. * @param {Function} callback function.
  1740. * @api private
  1741. */
  1742. Socket.prototype.sendPacket = function (type, data, fn) {
  1743. if ('closing' == this.readyState || 'closed' == this.readyState) {
  1744. return;
  1745. }
  1746. var packet = { type: type, data: data };
  1747. this.emit('packetCreate', packet);
  1748. this.writeBuffer.push(packet);
  1749. this.callbackBuffer.push(fn);
  1750. this.flush();
  1751. };
  1752. /**
  1753. * Closes the connection.
  1754. *
  1755. * @api private
  1756. */
  1757. Socket.prototype.close = function () {
  1758. if ('opening' == this.readyState || 'open' == this.readyState) {
  1759. this.readyState = 'closing';
  1760. var self = this;
  1761. function close() {
  1762. self.onClose('forced close');
  1763. debug('socket closing - telling transport to close');
  1764. self.transport.close();
  1765. }
  1766. function cleanupAndClose() {
  1767. self.removeListener('upgrade', cleanupAndClose);
  1768. self.removeListener('upgradeError', cleanupAndClose);
  1769. close();
  1770. }
  1771. function waitForUpgrade() {
  1772. // wait for upgrade to finish since we can't send packets while pausing a transport
  1773. self.once('upgrade', cleanupAndClose);
  1774. self.once('upgradeError', cleanupAndClose);
  1775. }
  1776. if (this.writeBuffer.length) {
  1777. this.once('drain', function() {
  1778. if (this.upgrading) {
  1779. waitForUpgrade();
  1780. } else {
  1781. close();
  1782. }
  1783. });
  1784. } else if (this.upgrading) {
  1785. waitForUpgrade();
  1786. } else {
  1787. close();
  1788. }
  1789. }
  1790. return this;
  1791. };
  1792. /**
  1793. * Called upon transport error
  1794. *
  1795. * @api private
  1796. */
  1797. Socket.prototype.onError = function (err) {
  1798. debug('socket error %j', err);
  1799. Socket.priorWebsocketSuccess = false;
  1800. this.emit('error', err);
  1801. this.onClose('transport error', err);
  1802. };
  1803. /**
  1804. * Called upon transport close.
  1805. *
  1806. * @api private
  1807. */
  1808. Socket.prototype.onClose = function (reason, desc) {
  1809. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  1810. debug('socket close with reason: "%s"', reason);
  1811. var self = this;
  1812. // clear timers
  1813. clearTimeout(this.pingIntervalTimer);
  1814. clearTimeout(this.pingTimeoutTimer);
  1815. // clean buffers in next tick, so developers can still
  1816. // grab the buffers on `close` event
  1817. setTimeout(function() {
  1818. self.writeBuffer = [];
  1819. self.callbackBuffer = [];
  1820. self.prevBufferLen = 0;
  1821. }, 0);
  1822. // stop event from firing again for transport
  1823. this.transport.removeAllListeners('close');
  1824. // ensure transport won't stay open
  1825. this.transport.close();
  1826. // ignore further transport communication
  1827. this.transport.removeAllListeners();
  1828. // set ready state
  1829. this.readyState = 'closed';
  1830. // clear session id
  1831. this.id = null;
  1832. // emit close event
  1833. this.emit('close', reason, desc);
  1834. }
  1835. };
  1836. /**
  1837. * Filters upgrades, returning only those matching client transports.
  1838. *
  1839. * @param {Array} server upgrades
  1840. * @api private
  1841. *
  1842. */
  1843. Socket.prototype.filterUpgrades = function (upgrades) {
  1844. var filteredUpgrades = [];
  1845. for (var i = 0, j = upgrades.length; i<j; i++) {
  1846. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  1847. }
  1848. return filteredUpgrades;
  1849. };
  1850. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1851. },{"./transport":14,"./transports":15,"component-emitter":9,"debug":22,"engine.io-parser":25,"indexof":40,"parsejson":32,"parseqs":33,"parseuri":34}],14:[function(_dereq_,module,exports){
  1852. /**
  1853. * Module dependencies.
  1854. */
  1855. var parser = _dereq_('engine.io-parser');
  1856. var Emitter = _dereq_('component-emitter');
  1857. /**
  1858. * Module exports.
  1859. */
  1860. module.exports = Transport;
  1861. /**
  1862. * Transport abstract constructor.
  1863. *
  1864. * @param {Object} options.
  1865. * @api private
  1866. */
  1867. function Transport (opts) {
  1868. this.path = opts.path;
  1869. this.hostname = opts.hostname;
  1870. this.port = opts.port;
  1871. this.secure = opts.secure;
  1872. this.query = opts.query;
  1873. this.timestampParam = opts.timestampParam;
  1874. this.timestampRequests = opts.timestampRequests;
  1875. this.readyState = '';
  1876. this.agent = opts.agent || false;
  1877. this.socket = opts.socket;
  1878. this.enablesXDR = opts.enablesXDR;
  1879. // SSL options for Node.js client
  1880. this.pfx = opts.pfx;
  1881. this.key = opts.key;
  1882. this.passphrase = opts.passphrase;
  1883. this.cert = opts.cert;
  1884. this.ca = opts.ca;
  1885. this.ciphers = opts.ciphers;
  1886. this.rejectUnauthorized = opts.rejectUnauthorized;
  1887. }
  1888. /**
  1889. * Mix in `Emitter`.
  1890. */
  1891. Emitter(Transport.prototype);
  1892. /**
  1893. * A counter used to prevent collisions in the timestamps used
  1894. * for cache busting.
  1895. */
  1896. Transport.timestamps = 0;
  1897. /**
  1898. * Emits an error.
  1899. *
  1900. * @param {String} str
  1901. * @return {Transport} for chaining
  1902. * @api public
  1903. */
  1904. Transport.prototype.onError = function (msg, desc) {
  1905. var err = new Error(msg);
  1906. err.type = 'TransportError';
  1907. err.description = desc;
  1908. this.emit('error', err);
  1909. return this;
  1910. };
  1911. /**
  1912. * Opens the transport.
  1913. *
  1914. * @api public
  1915. */
  1916. Transport.prototype.open = function () {
  1917. if ('closed' == this.readyState || '' == this.readyState) {
  1918. this.readyState = 'opening';
  1919. this.doOpen();
  1920. }
  1921. return this;
  1922. };
  1923. /**
  1924. * Closes the transport.
  1925. *
  1926. * @api private
  1927. */
  1928. Transport.prototype.close = function () {
  1929. if ('opening' == this.readyState || 'open' == this.readyState) {
  1930. this.doClose();
  1931. this.onClose();
  1932. }
  1933. return this;
  1934. };
  1935. /**
  1936. * Sends multiple packets.
  1937. *
  1938. * @param {Array} packets
  1939. * @api private
  1940. */
  1941. Transport.prototype.send = function(packets){
  1942. if ('open' == this.readyState) {
  1943. this.write(packets);
  1944. } else {
  1945. throw new Error('Transport not open');
  1946. }
  1947. };
  1948. /**
  1949. * Called upon open
  1950. *
  1951. * @api private
  1952. */
  1953. Transport.prototype.onOpen = function () {
  1954. this.readyState = 'open';
  1955. this.writable = true;
  1956. this.emit('open');
  1957. };
  1958. /**
  1959. * Called with data.
  1960. *
  1961. * @param {String} data
  1962. * @api private
  1963. */
  1964. Transport.prototype.onData = function(data){
  1965. var packet = parser.decodePacket(data, this.socket.binaryType);
  1966. this.onPacket(packet);
  1967. };
  1968. /**
  1969. * Called with a decoded packet.
  1970. */
  1971. Transport.prototype.onPacket = function (packet) {
  1972. this.emit('packet', packet);
  1973. };
  1974. /**
  1975. * Called upon close.
  1976. *
  1977. * @api private
  1978. */
  1979. Transport.prototype.onClose = function () {
  1980. this.readyState = 'closed';
  1981. this.emit('close');
  1982. };
  1983. },{"component-emitter":9,"engine.io-parser":25}],15:[function(_dereq_,module,exports){
  1984. (function (global){
  1985. /**
  1986. * Module dependencies
  1987. */
  1988. var XMLHttpRequest = _dereq_('xmlhttprequest');
  1989. var XHR = _dereq_('./polling-xhr');
  1990. var JSONP = _dereq_('./polling-jsonp');
  1991. var websocket = _dereq_('./websocket');
  1992. /**
  1993. * Export transports.
  1994. */
  1995. exports.polling = polling;
  1996. exports.websocket = websocket;
  1997. /**
  1998. * Polling transport polymorphic constructor.
  1999. * Decides on xhr vs jsonp based on feature detection.
  2000. *
  2001. * @api private
  2002. */
  2003. function polling(opts){
  2004. var xhr;
  2005. var xd = false;
  2006. var xs = false;
  2007. var jsonp = false !== opts.jsonp;
  2008. if (global.location) {
  2009. var isSSL = 'https:' == location.protocol;
  2010. var port = location.port;
  2011. // some user agents have empty `location.port`
  2012. if (!port) {
  2013. port = isSSL ? 443 : 80;
  2014. }
  2015. xd = opts.hostname != location.hostname || port != opts.port;
  2016. xs = opts.secure != isSSL;
  2017. }
  2018. opts.xdomain = xd;
  2019. opts.xscheme = xs;
  2020. xhr = new XMLHttpRequest(opts);
  2021. if ('open' in xhr && !opts.forceJSONP) {
  2022. return new XHR(opts);
  2023. } else {
  2024. if (!jsonp) throw new Error('JSONP disabled');
  2025. return new JSONP(opts);
  2026. }
  2027. }
  2028. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2029. },{"./polling-jsonp":16,"./polling-xhr":17,"./websocket":19,"xmlhttprequest":20}],16:[function(_dereq_,module,exports){
  2030. (function (global){
  2031. /**
  2032. * Module requirements.
  2033. */
  2034. var Polling = _dereq_('./polling');
  2035. var inherit = _dereq_('component-inherit');
  2036. /**
  2037. * Module exports.
  2038. */
  2039. module.exports = JSONPPolling;
  2040. /**
  2041. * Cached regular expressions.
  2042. */
  2043. var rNewline = /\n/g;
  2044. var rEscapedNewline = /\\n/g;
  2045. /**
  2046. * Global JSONP callbacks.
  2047. */
  2048. var callbacks;
  2049. /**
  2050. * Callbacks count.
  2051. */
  2052. var index = 0;
  2053. /**
  2054. * Noop.
  2055. */
  2056. function empty () { }
  2057. /**
  2058. * JSONP Polling constructor.
  2059. *
  2060. * @param {Object} opts.
  2061. * @api public
  2062. */
  2063. function JSONPPolling (opts) {
  2064. Polling.call(this, opts);
  2065. this.query = this.query || {};
  2066. // define global callbacks array if not present
  2067. // we do this here (lazily) to avoid unneeded global pollution
  2068. if (!callbacks) {
  2069. // we need to consider multiple engines in the same page
  2070. if (!global.___eio) global.___eio = [];
  2071. callbacks = global.___eio;
  2072. }
  2073. // callback identifier
  2074. this.index = callbacks.length;
  2075. // add callback to jsonp global
  2076. var self = this;
  2077. callbacks.push(function (msg) {
  2078. self.onData(msg);
  2079. });
  2080. // append to query string
  2081. this.query.j = this.index;
  2082. // prevent spurious errors from being emitted when the window is unloaded
  2083. if (global.document && global.addEventListener) {
  2084. global.addEventListener('beforeunload', function () {
  2085. if (self.script) self.script.onerror = empty;
  2086. }, false);
  2087. }
  2088. }
  2089. /**
  2090. * Inherits from Polling.
  2091. */
  2092. inherit(JSONPPolling, Polling);
  2093. /*
  2094. * JSONP only supports binary as base64 encoded strings
  2095. */
  2096. JSONPPolling.prototype.supportsBinary = false;
  2097. /**
  2098. * Closes the socket.
  2099. *
  2100. * @api private
  2101. */
  2102. JSONPPolling.prototype.doClose = function () {
  2103. if (this.script) {
  2104. this.script.parentNode.removeChild(this.script);
  2105. this.script = null;
  2106. }
  2107. if (this.form) {
  2108. this.form.parentNode.removeChild(this.form);
  2109. this.form = null;
  2110. this.iframe = null;
  2111. }
  2112. Polling.prototype.doClose.call(this);
  2113. };
  2114. /**
  2115. * Starts a poll cycle.
  2116. *
  2117. * @api private
  2118. */
  2119. JSONPPolling.prototype.doPoll = function () {
  2120. var self = this;
  2121. var script = document.createElement('script');
  2122. if (this.script) {
  2123. this.script.parentNode.removeChild(this.script);
  2124. this.script = null;
  2125. }
  2126. script.async = true;
  2127. script.src = this.uri();
  2128. script.onerror = function(e){
  2129. self.onError('jsonp poll error',e);
  2130. };
  2131. var insertAt = document.getElementsByTagName('script')[0];
  2132. insertAt.parentNode.insertBefore(script, insertAt);
  2133. this.script = script;
  2134. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  2135. if (isUAgecko) {
  2136. setTimeout(function () {
  2137. var iframe = document.createElement('iframe');
  2138. document.body.appendChild(iframe);
  2139. document.body.removeChild(iframe);
  2140. }, 100);
  2141. }
  2142. };
  2143. /**
  2144. * Writes with a hidden iframe.
  2145. *
  2146. * @param {String} data to send
  2147. * @param {Function} called upon flush.
  2148. * @api private
  2149. */
  2150. JSONPPolling.prototype.doWrite = function (data, fn) {
  2151. var self = this;
  2152. if (!this.form) {
  2153. var form = document.createElement('form');
  2154. var area = document.createElement('textarea');
  2155. var id = this.iframeId = 'eio_iframe_' + this.index;
  2156. var iframe;
  2157. form.className = 'socketio';
  2158. form.style.position = 'absolute';
  2159. form.style.top = '-1000px';
  2160. form.style.left = '-1000px';
  2161. form.target = id;
  2162. form.method = 'POST';
  2163. form.setAttribute('accept-charset', 'utf-8');
  2164. area.name = 'd';
  2165. form.appendChild(area);
  2166. document.body.appendChild(form);
  2167. this.form = form;
  2168. this.area = area;
  2169. }
  2170. this.form.action = this.uri();
  2171. function complete () {
  2172. initIframe();
  2173. fn();
  2174. }
  2175. function initIframe () {
  2176. if (self.iframe) {
  2177. try {
  2178. self.form.removeChild(self.iframe);
  2179. } catch (e) {
  2180. self.onError('jsonp polling iframe removal error', e);
  2181. }
  2182. }
  2183. try {
  2184. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  2185. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  2186. iframe = document.createElement(html);
  2187. } catch (e) {
  2188. iframe = document.createElement('iframe');
  2189. iframe.name = self.iframeId;
  2190. iframe.src = 'javascript:0';
  2191. }
  2192. iframe.id = self.iframeId;
  2193. self.form.appendChild(iframe);
  2194. self.iframe = iframe;
  2195. }
  2196. initIframe();
  2197. // escape \n to prevent it from being converted into \r\n by some UAs
  2198. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  2199. data = data.replace(rEscapedNewline, '\\\n');
  2200. this.area.value = data.replace(rNewline, '\\n');
  2201. try {
  2202. this.form.submit();
  2203. } catch(e) {}
  2204. if (this.iframe.attachEvent) {
  2205. this.iframe.onreadystatechange = function(){
  2206. if (self.iframe.readyState == 'complete') {
  2207. complete();
  2208. }
  2209. };
  2210. } else {
  2211. this.iframe.onload = complete;
  2212. }
  2213. };
  2214. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2215. },{"./polling":18,"component-inherit":21}],17:[function(_dereq_,module,exports){
  2216. (function (global){
  2217. /**
  2218. * Module requirements.
  2219. */
  2220. var XMLHttpRequest = _dereq_('xmlhttprequest');
  2221. var Polling = _dereq_('./polling');
  2222. var Emitter = _dereq_('component-emitter');
  2223. var inherit = _dereq_('component-inherit');
  2224. var debug = _dereq_('debug')('engine.io-client:polling-xhr');
  2225. /**
  2226. * Module exports.
  2227. */
  2228. module.exports = XHR;
  2229. module.exports.Request = Request;
  2230. /**
  2231. * Empty function
  2232. */
  2233. function empty(){}
  2234. /**
  2235. * XHR Polling constructor.
  2236. *
  2237. * @param {Object} opts
  2238. * @api public
  2239. */
  2240. function XHR(opts){
  2241. Polling.call(this, opts);
  2242. if (global.location) {
  2243. var isSSL = 'https:' == location.protocol;
  2244. var port = location.port;
  2245. // some user agents have empty `location.port`
  2246. if (!port) {
  2247. port = isSSL ? 443 : 80;
  2248. }
  2249. this.xd = opts.hostname != global.location.hostname ||
  2250. port != opts.port;
  2251. this.xs = opts.secure != isSSL;
  2252. }
  2253. }
  2254. /**
  2255. * Inherits from Polling.
  2256. */
  2257. inherit(XHR, Polling);
  2258. /**
  2259. * XHR supports binary
  2260. */
  2261. XHR.prototype.supportsBinary = true;
  2262. /**
  2263. * Creates a request.
  2264. *
  2265. * @param {String} method
  2266. * @api private
  2267. */
  2268. XHR.prototype.request = function(opts){
  2269. opts = opts || {};
  2270. opts.uri = this.uri();
  2271. opts.xd = this.xd;
  2272. opts.xs = this.xs;
  2273. opts.agent = this.agent || false;
  2274. opts.supportsBinary = this.supportsBinary;
  2275. opts.enablesXDR = this.enablesXDR;
  2276. // SSL options for Node.js client
  2277. opts.pfx = this.pfx;
  2278. opts.key = this.key;
  2279. opts.passphrase = this.passphrase;
  2280. opts.cert = this.cert;
  2281. opts.ca = this.ca;
  2282. opts.ciphers = this.ciphers;
  2283. opts.rejectUnauthorized = this.rejectUnauthorized;
  2284. return new Request(opts);
  2285. };
  2286. /**
  2287. * Sends data.
  2288. *
  2289. * @param {String} data to send.
  2290. * @param {Function} called upon flush.
  2291. * @api private
  2292. */
  2293. XHR.prototype.doWrite = function(data, fn){
  2294. var isBinary = typeof data !== 'string' && data !== undefined;
  2295. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  2296. var self = this;
  2297. req.on('success', fn);
  2298. req.on('error', function(err){
  2299. self.onError('xhr post error', err);
  2300. });
  2301. this.sendXhr = req;
  2302. };
  2303. /**
  2304. * Starts a poll cycle.
  2305. *
  2306. * @api private
  2307. */
  2308. XHR.prototype.doPoll = function(){
  2309. debug('xhr poll');
  2310. var req = this.request();
  2311. var self = this;
  2312. req.on('data', function(data){
  2313. self.onData(data);
  2314. });
  2315. req.on('error', function(err){
  2316. self.onError('xhr poll error', err);
  2317. });
  2318. this.pollXhr = req;
  2319. };
  2320. /**
  2321. * Request constructor
  2322. *
  2323. * @param {Object} options
  2324. * @api public
  2325. */
  2326. function Request(opts){
  2327. this.method = opts.method || 'GET';
  2328. this.uri = opts.uri;
  2329. this.xd = !!opts.xd;
  2330. this.xs = !!opts.xs;
  2331. this.async = false !== opts.async;
  2332. this.data = undefined != opts.data ? opts.data : null;
  2333. this.agent = opts.agent;
  2334. this.isBinary = opts.isBinary;
  2335. this.supportsBinary = opts.supportsBinary;
  2336. this.enablesXDR = opts.enablesXDR;
  2337. // SSL options for Node.js client
  2338. this.pfx = opts.pfx;
  2339. this.key = opts.key;
  2340. this.passphrase = opts.passphrase;
  2341. this.cert = opts.cert;
  2342. this.ca = opts.ca;
  2343. this.ciphers = opts.ciphers;
  2344. this.rejectUnauthorized = opts.rejectUnauthorized;
  2345. this.create();
  2346. }
  2347. /**
  2348. * Mix in `Emitter`.
  2349. */
  2350. Emitter(Request.prototype);
  2351. /**
  2352. * Creates the XHR object and sends the request.
  2353. *
  2354. * @api private
  2355. */
  2356. Request.prototype.create = function(){
  2357. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  2358. // SSL options for Node.js client
  2359. opts.pfx = this.pfx;
  2360. opts.key = this.key;
  2361. opts.passphrase = this.passphrase;
  2362. opts.cert = this.cert;
  2363. opts.ca = this.ca;
  2364. opts.ciphers = this.ciphers;
  2365. opts.rejectUnauthorized = this.rejectUnauthorized;
  2366. var xhr = this.xhr = new XMLHttpRequest(opts);
  2367. var self = this;
  2368. try {
  2369. debug('xhr open %s: %s', this.method, this.uri);
  2370. xhr.open(this.method, this.uri, this.async);
  2371. if (this.supportsBinary) {
  2372. // This has to be done after open because Firefox is stupid
  2373. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  2374. xhr.responseType = 'arraybuffer';
  2375. }
  2376. if ('POST' == this.method) {
  2377. try {
  2378. if (this.isBinary) {
  2379. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  2380. } else {
  2381. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  2382. }
  2383. } catch (e) {}
  2384. }
  2385. // ie6 check
  2386. if ('withCredentials' in xhr) {
  2387. xhr.withCredentials = true;
  2388. }
  2389. if (this.hasXDR()) {
  2390. xhr.onload = function(){
  2391. self.onLoad();
  2392. };
  2393. xhr.onerror = function(){
  2394. self.onError(xhr.responseText);
  2395. };
  2396. } else {
  2397. xhr.onreadystatechange = function(){
  2398. if (4 != xhr.readyState) return;
  2399. if (200 == xhr.status || 1223 == xhr.status) {
  2400. self.onLoad();
  2401. } else {
  2402. // make sure the `error` event handler that's user-set
  2403. // does not throw in the same tick and gets caught here
  2404. setTimeout(function(){
  2405. self.onError(xhr.status);
  2406. }, 0);
  2407. }
  2408. };
  2409. }
  2410. debug('xhr data %s', this.data);
  2411. xhr.send(this.data);
  2412. } catch (e) {
  2413. // Need to defer since .create() is called directly fhrom the constructor
  2414. // and thus the 'error' event can only be only bound *after* this exception
  2415. // occurs. Therefore, also, we cannot throw here at all.
  2416. setTimeout(function() {
  2417. self.onError(e);
  2418. }, 0);
  2419. return;
  2420. }
  2421. if (global.document) {
  2422. this.index = Request.requestsCount++;
  2423. Request.requests[this.index] = this;
  2424. }
  2425. };
  2426. /**
  2427. * Called upon successful response.
  2428. *
  2429. * @api private
  2430. */
  2431. Request.prototype.onSuccess = function(){
  2432. this.emit('success');
  2433. this.cleanup();
  2434. };
  2435. /**
  2436. * Called if we have data.
  2437. *
  2438. * @api private
  2439. */
  2440. Request.prototype.onData = function(data){
  2441. this.emit('data', data);
  2442. this.onSuccess();
  2443. };
  2444. /**
  2445. * Called upon error.
  2446. *
  2447. * @api private
  2448. */
  2449. Request.prototype.onError = function(err){
  2450. this.emit('error', err);
  2451. this.cleanup(true);
  2452. };
  2453. /**
  2454. * Cleans up house.
  2455. *
  2456. * @api private
  2457. */
  2458. Request.prototype.cleanup = function(fromError){
  2459. if ('undefined' == typeof this.xhr || null === this.xhr) {
  2460. return;
  2461. }
  2462. // xmlhttprequest
  2463. if (this.hasXDR()) {
  2464. this.xhr.onload = this.xhr.onerror = empty;
  2465. } else {
  2466. this.xhr.onreadystatechange = empty;
  2467. }
  2468. if (fromError) {
  2469. try {
  2470. this.xhr.abort();
  2471. } catch(e) {}
  2472. }
  2473. if (global.document) {
  2474. delete Request.requests[this.index];
  2475. }
  2476. this.xhr = null;
  2477. };
  2478. /**
  2479. * Called upon load.
  2480. *
  2481. * @api private
  2482. */
  2483. Request.prototype.onLoad = function(){
  2484. var data;
  2485. try {
  2486. var contentType;
  2487. try {
  2488. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  2489. } catch (e) {}
  2490. if (contentType === 'application/octet-stream') {
  2491. data = this.xhr.response;
  2492. } else {
  2493. if (!this.supportsBinary) {
  2494. data = this.xhr.responseText;
  2495. } else {
  2496. data = 'ok';
  2497. }
  2498. }
  2499. } catch (e) {
  2500. this.onError(e);
  2501. }
  2502. if (null != data) {
  2503. this.onData(data);
  2504. }
  2505. };
  2506. /**
  2507. * Check if it has XDomainRequest.
  2508. *
  2509. * @api private
  2510. */
  2511. Request.prototype.hasXDR = function(){
  2512. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  2513. };
  2514. /**
  2515. * Aborts the request.
  2516. *
  2517. * @api public
  2518. */
  2519. Request.prototype.abort = function(){
  2520. this.cleanup();
  2521. };
  2522. /**
  2523. * Aborts pending requests when unloading the window. This is needed to prevent
  2524. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  2525. * emitted.
  2526. */
  2527. if (global.document) {
  2528. Request.requestsCount = 0;
  2529. Request.requests = {};
  2530. if (global.attachEvent) {
  2531. global.attachEvent('onunload', unloadHandler);
  2532. } else if (global.addEventListener) {
  2533. global.addEventListener('beforeunload', unloadHandler, false);
  2534. }
  2535. }
  2536. function unloadHandler() {
  2537. for (var i in Request.requests) {
  2538. if (Request.requests.hasOwnProperty(i)) {
  2539. Request.requests[i].abort();
  2540. }
  2541. }
  2542. }
  2543. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2544. },{"./polling":18,"component-emitter":9,"component-inherit":21,"debug":22,"xmlhttprequest":20}],18:[function(_dereq_,module,exports){
  2545. /**
  2546. * Module dependencies.
  2547. */
  2548. var Transport = _dereq_('../transport');
  2549. var parseqs = _dereq_('parseqs');
  2550. var parser = _dereq_('engine.io-parser');
  2551. var inherit = _dereq_('component-inherit');
  2552. var debug = _dereq_('debug')('engine.io-client:polling');
  2553. /**
  2554. * Module exports.
  2555. */
  2556. module.exports = Polling;
  2557. /**
  2558. * Is XHR2 supported?
  2559. */
  2560. var hasXHR2 = (function() {
  2561. var XMLHttpRequest = _dereq_('xmlhttprequest');
  2562. var xhr = new XMLHttpRequest({ xdomain: false });
  2563. return null != xhr.responseType;
  2564. })();
  2565. /**
  2566. * Polling interface.
  2567. *
  2568. * @param {Object} opts
  2569. * @api private
  2570. */
  2571. function Polling(opts){
  2572. var forceBase64 = (opts && opts.forceBase64);
  2573. if (!hasXHR2 || forceBase64) {
  2574. this.supportsBinary = false;
  2575. }
  2576. Transport.call(this, opts);
  2577. }
  2578. /**
  2579. * Inherits from Transport.
  2580. */
  2581. inherit(Polling, Transport);
  2582. /**
  2583. * Transport name.
  2584. */
  2585. Polling.prototype.name = 'polling';
  2586. /**
  2587. * Opens the socket (triggers polling). We write a PING message to determine
  2588. * when the transport is open.
  2589. *
  2590. * @api private
  2591. */
  2592. Polling.prototype.doOpen = function(){
  2593. this.poll();
  2594. };
  2595. /**
  2596. * Pauses polling.
  2597. *
  2598. * @param {Function} callback upon buffers are flushed and transport is paused
  2599. * @api private
  2600. */
  2601. Polling.prototype.pause = function(onPause){
  2602. var pending = 0;
  2603. var self = this;
  2604. this.readyState = 'pausing';
  2605. function pause(){
  2606. debug('paused');
  2607. self.readyState = 'paused';
  2608. onPause();
  2609. }
  2610. if (this.polling || !this.writable) {
  2611. var total = 0;
  2612. if (this.polling) {
  2613. debug('we are currently polling - waiting to pause');
  2614. total++;
  2615. this.once('pollComplete', function(){
  2616. debug('pre-pause polling complete');
  2617. --total || pause();
  2618. });
  2619. }
  2620. if (!this.writable) {
  2621. debug('we are currently writing - waiting to pause');
  2622. total++;
  2623. this.once('drain', function(){
  2624. debug('pre-pause writing complete');
  2625. --total || pause();
  2626. });
  2627. }
  2628. } else {
  2629. pause();
  2630. }
  2631. };
  2632. /**
  2633. * Starts polling cycle.
  2634. *
  2635. * @api public
  2636. */
  2637. Polling.prototype.poll = function(){
  2638. debug('polling');
  2639. this.polling = true;
  2640. this.doPoll();
  2641. this.emit('poll');
  2642. };
  2643. /**
  2644. * Overloads onData to detect payloads.
  2645. *
  2646. * @api private
  2647. */
  2648. Polling.prototype.onData = function(data){
  2649. var self = this;
  2650. debug('polling got data %s', data);
  2651. var callback = function(packet, index, total) {
  2652. // if its the first message we consider the transport open
  2653. if ('opening' == self.readyState) {
  2654. self.onOpen();
  2655. }
  2656. // if its a close packet, we close the ongoing requests
  2657. if ('close' == packet.type) {
  2658. self.onClose();
  2659. return false;
  2660. }
  2661. // otherwise bypass onData and handle the message
  2662. self.onPacket(packet);
  2663. };
  2664. // decode payload
  2665. parser.decodePayload(data, this.socket.binaryType, callback);
  2666. // if an event did not trigger closing
  2667. if ('closed' != this.readyState) {
  2668. // if we got data we're not polling
  2669. this.polling = false;
  2670. this.emit('pollComplete');
  2671. if ('open' == this.readyState) {
  2672. this.poll();
  2673. } else {
  2674. debug('ignoring poll - transport state "%s"', this.readyState);
  2675. }
  2676. }
  2677. };
  2678. /**
  2679. * For polling, send a close packet.
  2680. *
  2681. * @api private
  2682. */
  2683. Polling.prototype.doClose = function(){
  2684. var self = this;
  2685. function close(){
  2686. debug('writing close packet');
  2687. self.write([{ type: 'close' }]);
  2688. }
  2689. if ('open' == this.readyState) {
  2690. debug('transport open - closing');
  2691. close();
  2692. } else {
  2693. // in case we're trying to close while
  2694. // handshaking is in progress (GH-164)
  2695. debug('transport not open - deferring close');
  2696. this.once('open', close);
  2697. }
  2698. };
  2699. /**
  2700. * Writes a packets payload.
  2701. *
  2702. * @param {Array} data packets
  2703. * @param {Function} drain callback
  2704. * @api private
  2705. */
  2706. Polling.prototype.write = function(packets){
  2707. var self = this;
  2708. this.writable = false;
  2709. var callbackfn = function() {
  2710. self.writable = true;
  2711. self.emit('drain');
  2712. };
  2713. var self = this;
  2714. parser.encodePayload(packets, this.supportsBinary, function(data) {
  2715. self.doWrite(data, callbackfn);
  2716. });
  2717. };
  2718. /**
  2719. * Generates uri for connection.
  2720. *
  2721. * @api private
  2722. */
  2723. Polling.prototype.uri = function(){
  2724. var query = this.query || {};
  2725. var schema = this.secure ? 'https' : 'http';
  2726. var port = '';
  2727. // cache busting is forced
  2728. if (false !== this.timestampRequests) {
  2729. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  2730. }
  2731. if (!this.supportsBinary && !query.sid) {
  2732. query.b64 = 1;
  2733. }
  2734. query = parseqs.encode(query);
  2735. // avoid port if default for schema
  2736. if (this.port && (('https' == schema && this.port != 443) ||
  2737. ('http' == schema && this.port != 80))) {
  2738. port = ':' + this.port;
  2739. }
  2740. // prepend ? to query
  2741. if (query.length) {
  2742. query = '?' + query;
  2743. }
  2744. return schema + '://' + this.hostname + port + this.path + query;
  2745. };
  2746. },{"../transport":14,"component-inherit":21,"debug":22,"engine.io-parser":25,"parseqs":33,"xmlhttprequest":20}],19:[function(_dereq_,module,exports){
  2747. /**
  2748. * Module dependencies.
  2749. */
  2750. var Transport = _dereq_('../transport');
  2751. var parser = _dereq_('engine.io-parser');
  2752. var parseqs = _dereq_('parseqs');
  2753. var inherit = _dereq_('component-inherit');
  2754. var debug = _dereq_('debug')('engine.io-client:websocket');
  2755. /**
  2756. * `ws` exposes a WebSocket-compatible interface in
  2757. * Node, or the `WebSocket` or `MozWebSocket` globals
  2758. * in the browser.
  2759. */
  2760. var WebSocket = _dereq_('ws');
  2761. /**
  2762. * Module exports.
  2763. */
  2764. module.exports = WS;
  2765. /**
  2766. * WebSocket transport constructor.
  2767. *
  2768. * @api {Object} connection options
  2769. * @api public
  2770. */
  2771. function WS(opts){
  2772. var forceBase64 = (opts && opts.forceBase64);
  2773. if (forceBase64) {
  2774. this.supportsBinary = false;
  2775. }
  2776. Transport.call(this, opts);
  2777. }
  2778. /**
  2779. * Inherits from Transport.
  2780. */
  2781. inherit(WS, Transport);
  2782. /**
  2783. * Transport name.
  2784. *
  2785. * @api public
  2786. */
  2787. WS.prototype.name = 'websocket';
  2788. /*
  2789. * WebSockets support binary
  2790. */
  2791. WS.prototype.supportsBinary = true;
  2792. /**
  2793. * Opens socket.
  2794. *
  2795. * @api private
  2796. */
  2797. WS.prototype.doOpen = function(){
  2798. if (!this.check()) {
  2799. // let probe timeout
  2800. return;
  2801. }
  2802. var self = this;
  2803. var uri = this.uri();
  2804. var protocols = void(0);
  2805. var opts = { agent: this.agent };
  2806. // SSL options for Node.js client
  2807. opts.pfx = this.pfx;
  2808. opts.key = this.key;
  2809. opts.passphrase = this.passphrase;
  2810. opts.cert = this.cert;
  2811. opts.ca = this.ca;
  2812. opts.ciphers = this.ciphers;
  2813. opts.rejectUnauthorized = this.rejectUnauthorized;
  2814. this.ws = new WebSocket(uri, protocols, opts);
  2815. if (this.ws.binaryType === undefined) {
  2816. this.supportsBinary = false;
  2817. }
  2818. this.ws.binaryType = 'arraybuffer';
  2819. this.addEventListeners();
  2820. };
  2821. /**
  2822. * Adds event listeners to the socket
  2823. *
  2824. * @api private
  2825. */
  2826. WS.prototype.addEventListeners = function(){
  2827. var self = this;
  2828. this.ws.onopen = function(){
  2829. self.onOpen();
  2830. };
  2831. this.ws.onclose = function(){
  2832. self.onClose();
  2833. };
  2834. this.ws.onmessage = function(ev){
  2835. self.onData(ev.data);
  2836. };
  2837. this.ws.onerror = function(e){
  2838. self.onError('websocket error', e);
  2839. };
  2840. };
  2841. /**
  2842. * Override `onData` to use a timer on iOS.
  2843. * See: https://gist.github.com/mloughran/2052006
  2844. *
  2845. * @api private
  2846. */
  2847. if ('undefined' != typeof navigator
  2848. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  2849. WS.prototype.onData = function(data){
  2850. var self = this;
  2851. setTimeout(function(){
  2852. Transport.prototype.onData.call(self, data);
  2853. }, 0);
  2854. };
  2855. }
  2856. /**
  2857. * Writes data to socket.
  2858. *
  2859. * @param {Array} array of packets.
  2860. * @api private
  2861. */
  2862. WS.prototype.write = function(packets){
  2863. var self = this;
  2864. this.writable = false;
  2865. // encodePacket efficient as it uses WS framing
  2866. // no need for encodePayload
  2867. for (var i = 0, l = packets.length; i < l; i++) {
  2868. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  2869. //Sometimes the websocket has already been closed but the browser didn't
  2870. //have a chance of informing us about it yet, in that case send will
  2871. //throw an error
  2872. try {
  2873. self.ws.send(data);
  2874. } catch (e){
  2875. debug('websocket closed before onclose event');
  2876. }
  2877. });
  2878. }
  2879. function ondrain() {
  2880. self.writable = true;
  2881. self.emit('drain');
  2882. }
  2883. // fake drain
  2884. // defer to next tick to allow Socket to clear writeBuffer
  2885. setTimeout(ondrain, 0);
  2886. };
  2887. /**
  2888. * Called upon close
  2889. *
  2890. * @api private
  2891. */
  2892. WS.prototype.onClose = function(){
  2893. Transport.prototype.onClose.call(this);
  2894. };
  2895. /**
  2896. * Closes socket.
  2897. *
  2898. * @api private
  2899. */
  2900. WS.prototype.doClose = function(){
  2901. if (typeof this.ws !== 'undefined') {
  2902. this.ws.close();
  2903. }
  2904. };
  2905. /**
  2906. * Generates uri for connection.
  2907. *
  2908. * @api private
  2909. */
  2910. WS.prototype.uri = function(){
  2911. var query = this.query || {};
  2912. var schema = this.secure ? 'wss' : 'ws';
  2913. var port = '';
  2914. // avoid port if default for schema
  2915. if (this.port && (('wss' == schema && this.port != 443)
  2916. || ('ws' == schema && this.port != 80))) {
  2917. port = ':' + this.port;
  2918. }
  2919. // append timestamp to URI
  2920. if (this.timestampRequests) {
  2921. query[this.timestampParam] = +new Date;
  2922. }
  2923. // communicate binary support capabilities
  2924. if (!this.supportsBinary) {
  2925. query.b64 = 1;
  2926. }
  2927. query = parseqs.encode(query);
  2928. // prepend ? to query
  2929. if (query.length) {
  2930. query = '?' + query;
  2931. }
  2932. return schema + '://' + this.hostname + port + this.path + query;
  2933. };
  2934. /**
  2935. * Feature detection for WebSocket.
  2936. *
  2937. * @return {Boolean} whether this transport is available.
  2938. * @api public
  2939. */
  2940. WS.prototype.check = function(){
  2941. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  2942. };
  2943. },{"../transport":14,"component-inherit":21,"debug":22,"engine.io-parser":25,"parseqs":33,"ws":35}],20:[function(_dereq_,module,exports){
  2944. // browser shim for xmlhttprequest module
  2945. var hasCORS = _dereq_('has-cors');
  2946. module.exports = function(opts) {
  2947. var xdomain = opts.xdomain;
  2948. // scheme must be same when usign XDomainRequest
  2949. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  2950. var xscheme = opts.xscheme;
  2951. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  2952. // https://github.com/Automattic/engine.io-client/pull/217
  2953. var enablesXDR = opts.enablesXDR;
  2954. // XMLHttpRequest can be disabled on IE
  2955. try {
  2956. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  2957. return new XMLHttpRequest();
  2958. }
  2959. } catch (e) { }
  2960. // Use XDomainRequest for IE8 if enablesXDR is true
  2961. // because loading bar keeps flashing when using jsonp-polling
  2962. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  2963. try {
  2964. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  2965. return new XDomainRequest();
  2966. }
  2967. } catch (e) { }
  2968. if (!xdomain) {
  2969. try {
  2970. return new ActiveXObject('Microsoft.XMLHTTP');
  2971. } catch(e) { }
  2972. }
  2973. }
  2974. },{"has-cors":38}],21:[function(_dereq_,module,exports){
  2975. module.exports = function(a, b){
  2976. var fn = function(){};
  2977. fn.prototype = b.prototype;
  2978. a.prototype = new fn;
  2979. a.prototype.constructor = a;
  2980. };
  2981. },{}],22:[function(_dereq_,module,exports){
  2982. /**
  2983. * This is the web browser implementation of `debug()`.
  2984. *
  2985. * Expose `debug()` as the module.
  2986. */
  2987. exports = module.exports = _dereq_('./debug');
  2988. exports.log = log;
  2989. exports.formatArgs = formatArgs;
  2990. exports.save = save;
  2991. exports.load = load;
  2992. exports.useColors = useColors;
  2993. /**
  2994. * Colors.
  2995. */
  2996. exports.colors = [
  2997. 'lightseagreen',
  2998. 'forestgreen',
  2999. 'goldenrod',
  3000. 'dodgerblue',
  3001. 'darkorchid',
  3002. 'crimson'
  3003. ];
  3004. /**
  3005. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  3006. * and the Firebug extension (any Firefox version) are known
  3007. * to support "%c" CSS customizations.
  3008. *
  3009. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  3010. */
  3011. function useColors() {
  3012. // is webkit? http://stackoverflow.com/a/16459606/376773
  3013. return ('WebkitAppearance' in document.documentElement.style) ||
  3014. // is firebug? http://stackoverflow.com/a/398120/376773
  3015. (window.console && (console.firebug || (console.exception && console.table))) ||
  3016. // is firefox >= v31?
  3017. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  3018. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  3019. }
  3020. /**
  3021. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  3022. */
  3023. exports.formatters.j = function(v) {
  3024. return JSON.stringify(v);
  3025. };
  3026. /**
  3027. * Colorize log arguments if enabled.
  3028. *
  3029. * @api public
  3030. */
  3031. function formatArgs() {
  3032. var args = arguments;
  3033. var useColors = this.useColors;
  3034. args[0] = (useColors ? '%c' : '')
  3035. + this.namespace
  3036. + (useColors ? ' %c' : ' ')
  3037. + args[0]
  3038. + (useColors ? '%c ' : ' ')
  3039. + '+' + exports.humanize(this.diff);
  3040. if (!useColors) return args;
  3041. var c = 'color: ' + this.color;
  3042. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  3043. // the final "%c" is somewhat tricky, because there could be other
  3044. // arguments passed either before or after the %c, so we need to
  3045. // figure out the correct index to insert the CSS into
  3046. var index = 0;
  3047. var lastC = 0;
  3048. args[0].replace(/%[a-z%]/g, function(match) {
  3049. if ('%%' === match) return;
  3050. index++;
  3051. if ('%c' === match) {
  3052. // we only are interested in the *last* %c
  3053. // (the user may have provided their own)
  3054. lastC = index;
  3055. }
  3056. });
  3057. args.splice(lastC, 0, c);
  3058. return args;
  3059. }
  3060. /**
  3061. * Invokes `console.log()` when available.
  3062. * No-op when `console.log` is not a "function".
  3063. *
  3064. * @api public
  3065. */
  3066. function log() {
  3067. // This hackery is required for IE8,
  3068. // where the `console.log` function doesn't have 'apply'
  3069. return 'object' == typeof console
  3070. && 'function' == typeof console.log
  3071. && Function.prototype.apply.call(console.log, console, arguments);
  3072. }
  3073. /**
  3074. * Save `namespaces`.
  3075. *
  3076. * @param {String} namespaces
  3077. * @api private
  3078. */
  3079. function save(namespaces) {
  3080. try {
  3081. if (null == namespaces) {
  3082. localStorage.removeItem('debug');
  3083. } else {
  3084. localStorage.debug = namespaces;
  3085. }
  3086. } catch(e) {}
  3087. }
  3088. /**
  3089. * Load `namespaces`.
  3090. *
  3091. * @return {String} returns the previously persisted debug modes
  3092. * @api private
  3093. */
  3094. function load() {
  3095. var r;
  3096. try {
  3097. r = localStorage.debug;
  3098. } catch(e) {}
  3099. return r;
  3100. }
  3101. /**
  3102. * Enable namespaces listed in `localStorage.debug` initially.
  3103. */
  3104. exports.enable(load());
  3105. },{"./debug":23}],23:[function(_dereq_,module,exports){
  3106. /**
  3107. * This is the common logic for both the Node.js and web browser
  3108. * implementations of `debug()`.
  3109. *
  3110. * Expose `debug()` as the module.
  3111. */
  3112. exports = module.exports = debug;
  3113. exports.coerce = coerce;
  3114. exports.disable = disable;
  3115. exports.enable = enable;
  3116. exports.enabled = enabled;
  3117. exports.humanize = _dereq_('ms');
  3118. /**
  3119. * The currently active debug mode names, and names to skip.
  3120. */
  3121. exports.names = [];
  3122. exports.skips = [];
  3123. /**
  3124. * Map of special "%n" handling functions, for the debug "format" argument.
  3125. *
  3126. * Valid key names are a single, lowercased letter, i.e. "n".
  3127. */
  3128. exports.formatters = {};
  3129. /**
  3130. * Previously assigned color.
  3131. */
  3132. var prevColor = 0;
  3133. /**
  3134. * Previous log timestamp.
  3135. */
  3136. var prevTime;
  3137. /**
  3138. * Select a color.
  3139. *
  3140. * @return {Number}
  3141. * @api private
  3142. */
  3143. function selectColor() {
  3144. return exports.colors[prevColor++ % exports.colors.length];
  3145. }
  3146. /**
  3147. * Create a debugger with the given `namespace`.
  3148. *
  3149. * @param {String} namespace
  3150. * @return {Function}
  3151. * @api public
  3152. */
  3153. function debug(namespace) {
  3154. // define the `disabled` version
  3155. function disabled() {
  3156. }
  3157. disabled.enabled = false;
  3158. // define the `enabled` version
  3159. function enabled() {
  3160. var self = enabled;
  3161. // set `diff` timestamp
  3162. var curr = +new Date();
  3163. var ms = curr - (prevTime || curr);
  3164. self.diff = ms;
  3165. self.prev = prevTime;
  3166. self.curr = curr;
  3167. prevTime = curr;
  3168. // add the `color` if not set
  3169. if (null == self.useColors) self.useColors = exports.useColors();
  3170. if (null == self.color && self.useColors) self.color = selectColor();
  3171. var args = Array.prototype.slice.call(arguments);
  3172. args[0] = exports.coerce(args[0]);
  3173. if ('string' !== typeof args[0]) {
  3174. // anything else let's inspect with %o
  3175. args = ['%o'].concat(args);
  3176. }
  3177. // apply any `formatters` transformations
  3178. var index = 0;
  3179. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  3180. // if we encounter an escaped % then don't increase the array index
  3181. if (match === '%%') return match;
  3182. index++;
  3183. var formatter = exports.formatters[format];
  3184. if ('function' === typeof formatter) {
  3185. var val = args[index];
  3186. match = formatter.call(self, val);
  3187. // now we need to remove `args[index]` since it's inlined in the `format`
  3188. args.splice(index, 1);
  3189. index--;
  3190. }
  3191. return match;
  3192. });
  3193. if ('function' === typeof exports.formatArgs) {
  3194. args = exports.formatArgs.apply(self, args);
  3195. }
  3196. var logFn = enabled.log || exports.log || console.log.bind(console);
  3197. logFn.apply(self, args);
  3198. }
  3199. enabled.enabled = true;
  3200. var fn = exports.enabled(namespace) ? enabled : disabled;
  3201. fn.namespace = namespace;
  3202. return fn;
  3203. }
  3204. /**
  3205. * Enables a debug mode by namespaces. This can include modes
  3206. * separated by a colon and wildcards.
  3207. *
  3208. * @param {String} namespaces
  3209. * @api public
  3210. */
  3211. function enable(namespaces) {
  3212. exports.save(namespaces);
  3213. var split = (namespaces || '').split(/[\s,]+/);
  3214. var len = split.length;
  3215. for (var i = 0; i < len; i++) {
  3216. if (!split[i]) continue; // ignore empty strings
  3217. namespaces = split[i].replace(/\*/g, '.*?');
  3218. if (namespaces[0] === '-') {
  3219. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  3220. } else {
  3221. exports.names.push(new RegExp('^' + namespaces + '$'));
  3222. }
  3223. }
  3224. }
  3225. /**
  3226. * Disable debug output.
  3227. *
  3228. * @api public
  3229. */
  3230. function disable() {
  3231. exports.enable('');
  3232. }
  3233. /**
  3234. * Returns true if the given mode name is enabled, false otherwise.
  3235. *
  3236. * @param {String} name
  3237. * @return {Boolean}
  3238. * @api public
  3239. */
  3240. function enabled(name) {
  3241. var i, len;
  3242. for (i = 0, len = exports.skips.length; i < len; i++) {
  3243. if (exports.skips[i].test(name)) {
  3244. return false;
  3245. }
  3246. }
  3247. for (i = 0, len = exports.names.length; i < len; i++) {
  3248. if (exports.names[i].test(name)) {
  3249. return true;
  3250. }
  3251. }
  3252. return false;
  3253. }
  3254. /**
  3255. * Coerce `val`.
  3256. *
  3257. * @param {Mixed} val
  3258. * @return {Mixed}
  3259. * @api private
  3260. */
  3261. function coerce(val) {
  3262. if (val instanceof Error) return val.stack || val.message;
  3263. return val;
  3264. }
  3265. },{"ms":24}],24:[function(_dereq_,module,exports){
  3266. /**
  3267. * Helpers.
  3268. */
  3269. var s = 1000;
  3270. var m = s * 60;
  3271. var h = m * 60;
  3272. var d = h * 24;
  3273. var y = d * 365.25;
  3274. /**
  3275. * Parse or format the given `val`.
  3276. *
  3277. * Options:
  3278. *
  3279. * - `long` verbose formatting [false]
  3280. *
  3281. * @param {String|Number} val
  3282. * @param {Object} options
  3283. * @return {String|Number}
  3284. * @api public
  3285. */
  3286. module.exports = function(val, options){
  3287. options = options || {};
  3288. if ('string' == typeof val) return parse(val);
  3289. return options.long
  3290. ? long(val)
  3291. : short(val);
  3292. };
  3293. /**
  3294. * Parse the given `str` and return milliseconds.
  3295. *
  3296. * @param {String} str
  3297. * @return {Number}
  3298. * @api private
  3299. */
  3300. function parse(str) {
  3301. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  3302. if (!match) return;
  3303. var n = parseFloat(match[1]);
  3304. var type = (match[2] || 'ms').toLowerCase();
  3305. switch (type) {
  3306. case 'years':
  3307. case 'year':
  3308. case 'y':
  3309. return n * y;
  3310. case 'days':
  3311. case 'day':
  3312. case 'd':
  3313. return n * d;
  3314. case 'hours':
  3315. case 'hour':
  3316. case 'h':
  3317. return n * h;
  3318. case 'minutes':
  3319. case 'minute':
  3320. case 'm':
  3321. return n * m;
  3322. case 'seconds':
  3323. case 'second':
  3324. case 's':
  3325. return n * s;
  3326. case 'ms':
  3327. return n;
  3328. }
  3329. }
  3330. /**
  3331. * Short format for `ms`.
  3332. *
  3333. * @param {Number} ms
  3334. * @return {String}
  3335. * @api private
  3336. */
  3337. function short(ms) {
  3338. if (ms >= d) return Math.round(ms / d) + 'd';
  3339. if (ms >= h) return Math.round(ms / h) + 'h';
  3340. if (ms >= m) return Math.round(ms / m) + 'm';
  3341. if (ms >= s) return Math.round(ms / s) + 's';
  3342. return ms + 'ms';
  3343. }
  3344. /**
  3345. * Long format for `ms`.
  3346. *
  3347. * @param {Number} ms
  3348. * @return {String}
  3349. * @api private
  3350. */
  3351. function long(ms) {
  3352. return plural(ms, d, 'day')
  3353. || plural(ms, h, 'hour')
  3354. || plural(ms, m, 'minute')
  3355. || plural(ms, s, 'second')
  3356. || ms + ' ms';
  3357. }
  3358. /**
  3359. * Pluralization helper.
  3360. */
  3361. function plural(ms, n, name) {
  3362. if (ms < n) return;
  3363. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  3364. return Math.ceil(ms / n) + ' ' + name + 's';
  3365. }
  3366. },{}],25:[function(_dereq_,module,exports){
  3367. (function (global){
  3368. /**
  3369. * Module dependencies.
  3370. */
  3371. var keys = _dereq_('./keys');
  3372. var hasBinary = _dereq_('has-binary');
  3373. var sliceBuffer = _dereq_('arraybuffer.slice');
  3374. var base64encoder = _dereq_('base64-arraybuffer');
  3375. var after = _dereq_('after');
  3376. var utf8 = _dereq_('utf8');
  3377. /**
  3378. * Check if we are running an android browser. That requires us to use
  3379. * ArrayBuffer with polling transports...
  3380. *
  3381. * http://ghinda.net/jpeg-blob-ajax-android/
  3382. */
  3383. var isAndroid = navigator.userAgent.match(/Android/i);
  3384. /**
  3385. * Check if we are running in PhantomJS.
  3386. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  3387. * https://github.com/ariya/phantomjs/issues/11395
  3388. * @type boolean
  3389. */
  3390. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  3391. /**
  3392. * When true, avoids using Blobs to encode payloads.
  3393. * @type boolean
  3394. */
  3395. var dontSendBlobs = isAndroid || isPhantomJS;
  3396. /**
  3397. * Current protocol version.
  3398. */
  3399. exports.protocol = 3;
  3400. /**
  3401. * Packet types.
  3402. */
  3403. var packets = exports.packets = {
  3404. open: 0 // non-ws
  3405. , close: 1 // non-ws
  3406. , ping: 2
  3407. , pong: 3
  3408. , message: 4
  3409. , upgrade: 5
  3410. , noop: 6
  3411. };
  3412. var packetslist = keys(packets);
  3413. /**
  3414. * Premade error packet.
  3415. */
  3416. var err = { type: 'error', data: 'parser error' };
  3417. /**
  3418. * Create a blob api even for blob builder when vendor prefixes exist
  3419. */
  3420. var Blob = _dereq_('blob');
  3421. /**
  3422. * Encodes a packet.
  3423. *
  3424. * <packet type id> [ <data> ]
  3425. *
  3426. * Example:
  3427. *
  3428. * 5hello world
  3429. * 3
  3430. * 4
  3431. *
  3432. * Binary is encoded in an identical principle
  3433. *
  3434. * @api private
  3435. */
  3436. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  3437. if ('function' == typeof supportsBinary) {
  3438. callback = supportsBinary;
  3439. supportsBinary = false;
  3440. }
  3441. if ('function' == typeof utf8encode) {
  3442. callback = utf8encode;
  3443. utf8encode = null;
  3444. }
  3445. var data = (packet.data === undefined)
  3446. ? undefined
  3447. : packet.data.buffer || packet.data;
  3448. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  3449. return encodeArrayBuffer(packet, supportsBinary, callback);
  3450. } else if (Blob && data instanceof global.Blob) {
  3451. return encodeBlob(packet, supportsBinary, callback);
  3452. }
  3453. // might be an object with { base64: true, data: dataAsBase64String }
  3454. if (data && data.base64) {
  3455. return encodeBase64Object(packet, callback);
  3456. }
  3457. // Sending data as a utf-8 string
  3458. var encoded = packets[packet.type];
  3459. // data fragment is optional
  3460. if (undefined !== packet.data) {
  3461. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  3462. }
  3463. return callback('' + encoded);
  3464. };
  3465. function encodeBase64Object(packet, callback) {
  3466. // packet data is an object { base64: true, data: dataAsBase64String }
  3467. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  3468. return callback(message);
  3469. }
  3470. /**
  3471. * Encode packet helpers for binary types
  3472. */
  3473. function encodeArrayBuffer(packet, supportsBinary, callback) {
  3474. if (!supportsBinary) {
  3475. return exports.encodeBase64Packet(packet, callback);
  3476. }
  3477. var data = packet.data;
  3478. var contentArray = new Uint8Array(data);
  3479. var resultBuffer = new Uint8Array(1 + data.byteLength);
  3480. resultBuffer[0] = packets[packet.type];
  3481. for (var i = 0; i < contentArray.length; i++) {
  3482. resultBuffer[i+1] = contentArray[i];
  3483. }
  3484. return callback(resultBuffer.buffer);
  3485. }
  3486. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  3487. if (!supportsBinary) {
  3488. return exports.encodeBase64Packet(packet, callback);
  3489. }
  3490. var fr = new FileReader();
  3491. fr.onload = function() {
  3492. packet.data = fr.result;
  3493. exports.encodePacket(packet, supportsBinary, true, callback);
  3494. };
  3495. return fr.readAsArrayBuffer(packet.data);
  3496. }
  3497. function encodeBlob(packet, supportsBinary, callback) {
  3498. if (!supportsBinary) {
  3499. return exports.encodeBase64Packet(packet, callback);
  3500. }
  3501. if (dontSendBlobs) {
  3502. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  3503. }
  3504. var length = new Uint8Array(1);
  3505. length[0] = packets[packet.type];
  3506. var blob = new Blob([length.buffer, packet.data]);
  3507. return callback(blob);
  3508. }
  3509. /**
  3510. * Encodes a packet with binary data in a base64 string
  3511. *
  3512. * @param {Object} packet, has `type` and `data`
  3513. * @return {String} base64 encoded message
  3514. */
  3515. exports.encodeBase64Packet = function(packet, callback) {
  3516. var message = 'b' + exports.packets[packet.type];
  3517. if (Blob && packet.data instanceof Blob) {
  3518. var fr = new FileReader();
  3519. fr.onload = function() {
  3520. var b64 = fr.result.split(',')[1];
  3521. callback(message + b64);
  3522. };
  3523. return fr.readAsDataURL(packet.data);
  3524. }
  3525. var b64data;
  3526. try {
  3527. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  3528. } catch (e) {
  3529. // iPhone Safari doesn't let you apply with typed arrays
  3530. var typed = new Uint8Array(packet.data);
  3531. var basic = new Array(typed.length);
  3532. for (var i = 0; i < typed.length; i++) {
  3533. basic[i] = typed[i];
  3534. }
  3535. b64data = String.fromCharCode.apply(null, basic);
  3536. }
  3537. message += global.btoa(b64data);
  3538. return callback(message);
  3539. };
  3540. /**
  3541. * Decodes a packet. Changes format to Blob if requested.
  3542. *
  3543. * @return {Object} with `type` and `data` (if any)
  3544. * @api private
  3545. */
  3546. exports.decodePacket = function (data, binaryType, utf8decode) {
  3547. // String data
  3548. if (typeof data == 'string' || data === undefined) {
  3549. if (data.charAt(0) == 'b') {
  3550. return exports.decodeBase64Packet(data.substr(1), binaryType);
  3551. }
  3552. if (utf8decode) {
  3553. try {
  3554. data = utf8.decode(data);
  3555. } catch (e) {
  3556. return err;
  3557. }
  3558. }
  3559. var type = data.charAt(0);
  3560. if (Number(type) != type || !packetslist[type]) {
  3561. return err;
  3562. }
  3563. if (data.length > 1) {
  3564. return { type: packetslist[type], data: data.substring(1) };
  3565. } else {
  3566. return { type: packetslist[type] };
  3567. }
  3568. }
  3569. var asArray = new Uint8Array(data);
  3570. var type = asArray[0];
  3571. var rest = sliceBuffer(data, 1);
  3572. if (Blob && binaryType === 'blob') {
  3573. rest = new Blob([rest]);
  3574. }
  3575. return { type: packetslist[type], data: rest };
  3576. };
  3577. /**
  3578. * Decodes a packet encoded in a base64 string
  3579. *
  3580. * @param {String} base64 encoded message
  3581. * @return {Object} with `type` and `data` (if any)
  3582. */
  3583. exports.decodeBase64Packet = function(msg, binaryType) {
  3584. var type = packetslist[msg.charAt(0)];
  3585. if (!global.ArrayBuffer) {
  3586. return { type: type, data: { base64: true, data: msg.substr(1) } };
  3587. }
  3588. var data = base64encoder.decode(msg.substr(1));
  3589. if (binaryType === 'blob' && Blob) {
  3590. data = new Blob([data]);
  3591. }
  3592. return { type: type, data: data };
  3593. };
  3594. /**
  3595. * Encodes multiple messages (payload).
  3596. *
  3597. * <length>:data
  3598. *
  3599. * Example:
  3600. *
  3601. * 11:hello world2:hi
  3602. *
  3603. * If any contents are binary, they will be encoded as base64 strings. Base64
  3604. * encoded strings are marked with a b before the length specifier
  3605. *
  3606. * @param {Array} packets
  3607. * @api private
  3608. */
  3609. exports.encodePayload = function (packets, supportsBinary, callback) {
  3610. if (typeof supportsBinary == 'function') {
  3611. callback = supportsBinary;
  3612. supportsBinary = null;
  3613. }
  3614. var isBinary = hasBinary(packets);
  3615. if (supportsBinary && isBinary) {
  3616. if (Blob && !dontSendBlobs) {
  3617. return exports.encodePayloadAsBlob(packets, callback);
  3618. }
  3619. return exports.encodePayloadAsArrayBuffer(packets, callback);
  3620. }
  3621. if (!packets.length) {
  3622. return callback('0:');
  3623. }
  3624. function setLengthHeader(message) {
  3625. return message.length + ':' + message;
  3626. }
  3627. function encodeOne(packet, doneCallback) {
  3628. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  3629. doneCallback(null, setLengthHeader(message));
  3630. });
  3631. }
  3632. map(packets, encodeOne, function(err, results) {
  3633. return callback(results.join(''));
  3634. });
  3635. };
  3636. /**
  3637. * Async array map using after
  3638. */
  3639. function map(ary, each, done) {
  3640. var result = new Array(ary.length);
  3641. var next = after(ary.length, done);
  3642. var eachWithIndex = function(i, el, cb) {
  3643. each(el, function(error, msg) {
  3644. result[i] = msg;
  3645. cb(error, result);
  3646. });
  3647. };
  3648. for (var i = 0; i < ary.length; i++) {
  3649. eachWithIndex(i, ary[i], next);
  3650. }
  3651. }
  3652. /*
  3653. * Decodes data when a payload is maybe expected. Possible binary contents are
  3654. * decoded from their base64 representation
  3655. *
  3656. * @param {String} data, callback method
  3657. * @api public
  3658. */
  3659. exports.decodePayload = function (data, binaryType, callback) {
  3660. if (typeof data != 'string') {
  3661. return exports.decodePayloadAsBinary(data, binaryType, callback);
  3662. }
  3663. if (typeof binaryType === 'function') {
  3664. callback = binaryType;
  3665. binaryType = null;
  3666. }
  3667. var packet;
  3668. if (data == '') {
  3669. // parser error - ignoring payload
  3670. return callback(err, 0, 1);
  3671. }
  3672. var length = ''
  3673. , n, msg;
  3674. for (var i = 0, l = data.length; i < l; i++) {
  3675. var chr = data.charAt(i);
  3676. if (':' != chr) {
  3677. length += chr;
  3678. } else {
  3679. if ('' == length || (length != (n = Number(length)))) {
  3680. // parser error - ignoring payload
  3681. return callback(err, 0, 1);
  3682. }
  3683. msg = data.substr(i + 1, n);
  3684. if (length != msg.length) {
  3685. // parser error - ignoring payload
  3686. return callback(err, 0, 1);
  3687. }
  3688. if (msg.length) {
  3689. packet = exports.decodePacket(msg, binaryType, true);
  3690. if (err.type == packet.type && err.data == packet.data) {
  3691. // parser error in individual packet - ignoring payload
  3692. return callback(err, 0, 1);
  3693. }
  3694. var ret = callback(packet, i + n, l);
  3695. if (false === ret) return;
  3696. }
  3697. // advance cursor
  3698. i += n;
  3699. length = '';
  3700. }
  3701. }
  3702. if (length != '') {
  3703. // parser error - ignoring payload
  3704. return callback(err, 0, 1);
  3705. }
  3706. };
  3707. /**
  3708. * Encodes multiple messages (payload) as binary.
  3709. *
  3710. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  3711. * 255><data>
  3712. *
  3713. * Example:
  3714. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  3715. *
  3716. * @param {Array} packets
  3717. * @return {ArrayBuffer} encoded payload
  3718. * @api private
  3719. */
  3720. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  3721. if (!packets.length) {
  3722. return callback(new ArrayBuffer(0));
  3723. }
  3724. function encodeOne(packet, doneCallback) {
  3725. exports.encodePacket(packet, true, true, function(data) {
  3726. return doneCallback(null, data);
  3727. });
  3728. }
  3729. map(packets, encodeOne, function(err, encodedPackets) {
  3730. var totalLength = encodedPackets.reduce(function(acc, p) {
  3731. var len;
  3732. if (typeof p === 'string'){
  3733. len = p.length;
  3734. } else {
  3735. len = p.byteLength;
  3736. }
  3737. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  3738. }, 0);
  3739. var resultArray = new Uint8Array(totalLength);
  3740. var bufferIndex = 0;
  3741. encodedPackets.forEach(function(p) {
  3742. var isString = typeof p === 'string';
  3743. var ab = p;
  3744. if (isString) {
  3745. var view = new Uint8Array(p.length);
  3746. for (var i = 0; i < p.length; i++) {
  3747. view[i] = p.charCodeAt(i);
  3748. }
  3749. ab = view.buffer;
  3750. }
  3751. if (isString) { // not true binary
  3752. resultArray[bufferIndex++] = 0;
  3753. } else { // true binary
  3754. resultArray[bufferIndex++] = 1;
  3755. }
  3756. var lenStr = ab.byteLength.toString();
  3757. for (var i = 0; i < lenStr.length; i++) {
  3758. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  3759. }
  3760. resultArray[bufferIndex++] = 255;
  3761. var view = new Uint8Array(ab);
  3762. for (var i = 0; i < view.length; i++) {
  3763. resultArray[bufferIndex++] = view[i];
  3764. }
  3765. });
  3766. return callback(resultArray.buffer);
  3767. });
  3768. };
  3769. /**
  3770. * Encode as Blob
  3771. */
  3772. exports.encodePayloadAsBlob = function(packets, callback) {
  3773. function encodeOne(packet, doneCallback) {
  3774. exports.encodePacket(packet, true, true, function(encoded) {
  3775. var binaryIdentifier = new Uint8Array(1);
  3776. binaryIdentifier[0] = 1;
  3777. if (typeof encoded === 'string') {
  3778. var view = new Uint8Array(encoded.length);
  3779. for (var i = 0; i < encoded.length; i++) {
  3780. view[i] = encoded.charCodeAt(i);
  3781. }
  3782. encoded = view.buffer;
  3783. binaryIdentifier[0] = 0;
  3784. }
  3785. var len = (encoded instanceof ArrayBuffer)
  3786. ? encoded.byteLength
  3787. : encoded.size;
  3788. var lenStr = len.toString();
  3789. var lengthAry = new Uint8Array(lenStr.length + 1);
  3790. for (var i = 0; i < lenStr.length; i++) {
  3791. lengthAry[i] = parseInt(lenStr[i]);
  3792. }
  3793. lengthAry[lenStr.length] = 255;
  3794. if (Blob) {
  3795. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  3796. doneCallback(null, blob);
  3797. }
  3798. });
  3799. }
  3800. map(packets, encodeOne, function(err, results) {
  3801. return callback(new Blob(results));
  3802. });
  3803. };
  3804. /*
  3805. * Decodes data when a payload is maybe expected. Strings are decoded by
  3806. * interpreting each byte as a key code for entries marked to start with 0. See
  3807. * description of encodePayloadAsBinary
  3808. *
  3809. * @param {ArrayBuffer} data, callback method
  3810. * @api public
  3811. */
  3812. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  3813. if (typeof binaryType === 'function') {
  3814. callback = binaryType;
  3815. binaryType = null;
  3816. }
  3817. var bufferTail = data;
  3818. var buffers = [];
  3819. var numberTooLong = false;
  3820. while (bufferTail.byteLength > 0) {
  3821. var tailArray = new Uint8Array(bufferTail);
  3822. var isString = tailArray[0] === 0;
  3823. var msgLength = '';
  3824. for (var i = 1; ; i++) {
  3825. if (tailArray[i] == 255) break;
  3826. if (msgLength.length > 310) {
  3827. numberTooLong = true;
  3828. break;
  3829. }
  3830. msgLength += tailArray[i];
  3831. }
  3832. if(numberTooLong) return callback(err, 0, 1);
  3833. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  3834. msgLength = parseInt(msgLength);
  3835. var msg = sliceBuffer(bufferTail, 0, msgLength);
  3836. if (isString) {
  3837. try {
  3838. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  3839. } catch (e) {
  3840. // iPhone Safari doesn't let you apply to typed arrays
  3841. var typed = new Uint8Array(msg);
  3842. msg = '';
  3843. for (var i = 0; i < typed.length; i++) {
  3844. msg += String.fromCharCode(typed[i]);
  3845. }
  3846. }
  3847. }
  3848. buffers.push(msg);
  3849. bufferTail = sliceBuffer(bufferTail, msgLength);
  3850. }
  3851. var total = buffers.length;
  3852. buffers.forEach(function(buffer, i) {
  3853. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  3854. });
  3855. };
  3856. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3857. },{"./keys":26,"after":27,"arraybuffer.slice":28,"base64-arraybuffer":29,"blob":30,"has-binary":36,"utf8":31}],26:[function(_dereq_,module,exports){
  3858. /**
  3859. * Gets the keys for an object.
  3860. *
  3861. * @return {Array} keys
  3862. * @api private
  3863. */
  3864. module.exports = Object.keys || function keys (obj){
  3865. var arr = [];
  3866. var has = Object.prototype.hasOwnProperty;
  3867. for (var i in obj) {
  3868. if (has.call(obj, i)) {
  3869. arr.push(i);
  3870. }
  3871. }
  3872. return arr;
  3873. };
  3874. },{}],27:[function(_dereq_,module,exports){
  3875. module.exports = after
  3876. function after(count, callback, err_cb) {
  3877. var bail = false
  3878. err_cb = err_cb || noop
  3879. proxy.count = count
  3880. return (count === 0) ? callback() : proxy
  3881. function proxy(err, result) {
  3882. if (proxy.count <= 0) {
  3883. throw new Error('after called too many times')
  3884. }
  3885. --proxy.count
  3886. // after first error, rest are passed to err_cb
  3887. if (err) {
  3888. bail = true
  3889. callback(err)
  3890. // future error callbacks will go to error handler
  3891. callback = err_cb
  3892. } else if (proxy.count === 0 && !bail) {
  3893. callback(null, result)
  3894. }
  3895. }
  3896. }
  3897. function noop() {}
  3898. },{}],28:[function(_dereq_,module,exports){
  3899. /**
  3900. * An abstraction for slicing an arraybuffer even when
  3901. * ArrayBuffer.prototype.slice is not supported
  3902. *
  3903. * @api public
  3904. */
  3905. module.exports = function(arraybuffer, start, end) {
  3906. var bytes = arraybuffer.byteLength;
  3907. start = start || 0;
  3908. end = end || bytes;
  3909. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  3910. if (start < 0) { start += bytes; }
  3911. if (end < 0) { end += bytes; }
  3912. if (end > bytes) { end = bytes; }
  3913. if (start >= bytes || start >= end || bytes === 0) {
  3914. return new ArrayBuffer(0);
  3915. }
  3916. var abv = new Uint8Array(arraybuffer);
  3917. var result = new Uint8Array(end - start);
  3918. for (var i = start, ii = 0; i < end; i++, ii++) {
  3919. result[ii] = abv[i];
  3920. }
  3921. return result.buffer;
  3922. };
  3923. },{}],29:[function(_dereq_,module,exports){
  3924. /*
  3925. * base64-arraybuffer
  3926. * https://github.com/niklasvh/base64-arraybuffer
  3927. *
  3928. * Copyright (c) 2012 Niklas von Hertzen
  3929. * Licensed under the MIT license.
  3930. */
  3931. (function(chars){
  3932. "use strict";
  3933. exports.encode = function(arraybuffer) {
  3934. var bytes = new Uint8Array(arraybuffer),
  3935. i, len = bytes.length, base64 = "";
  3936. for (i = 0; i < len; i+=3) {
  3937. base64 += chars[bytes[i] >> 2];
  3938. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  3939. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  3940. base64 += chars[bytes[i + 2] & 63];
  3941. }
  3942. if ((len % 3) === 2) {
  3943. base64 = base64.substring(0, base64.length - 1) + "=";
  3944. } else if (len % 3 === 1) {
  3945. base64 = base64.substring(0, base64.length - 2) + "==";
  3946. }
  3947. return base64;
  3948. };
  3949. exports.decode = function(base64) {
  3950. var bufferLength = base64.length * 0.75,
  3951. len = base64.length, i, p = 0,
  3952. encoded1, encoded2, encoded3, encoded4;
  3953. if (base64[base64.length - 1] === "=") {
  3954. bufferLength--;
  3955. if (base64[base64.length - 2] === "=") {
  3956. bufferLength--;
  3957. }
  3958. }
  3959. var arraybuffer = new ArrayBuffer(bufferLength),
  3960. bytes = new Uint8Array(arraybuffer);
  3961. for (i = 0; i < len; i+=4) {
  3962. encoded1 = chars.indexOf(base64[i]);
  3963. encoded2 = chars.indexOf(base64[i+1]);
  3964. encoded3 = chars.indexOf(base64[i+2]);
  3965. encoded4 = chars.indexOf(base64[i+3]);
  3966. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  3967. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  3968. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  3969. }
  3970. return arraybuffer;
  3971. };
  3972. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  3973. },{}],30:[function(_dereq_,module,exports){
  3974. (function (global){
  3975. /**
  3976. * Create a blob builder even when vendor prefixes exist
  3977. */
  3978. var BlobBuilder = global.BlobBuilder
  3979. || global.WebKitBlobBuilder
  3980. || global.MSBlobBuilder
  3981. || global.MozBlobBuilder;
  3982. /**
  3983. * Check if Blob constructor is supported
  3984. */
  3985. var blobSupported = (function() {
  3986. try {
  3987. var a = new Blob(['hi']);
  3988. return a.size === 2;
  3989. } catch(e) {
  3990. return false;
  3991. }
  3992. })();
  3993. /**
  3994. * Check if Blob constructor supports ArrayBufferViews
  3995. * Fails in Safari 6, so we need to map to ArrayBuffers there.
  3996. */
  3997. var blobSupportsArrayBufferView = blobSupported && (function() {
  3998. try {
  3999. var b = new Blob([new Uint8Array([1,2])]);
  4000. return b.size === 2;
  4001. } catch(e) {
  4002. return false;
  4003. }
  4004. })();
  4005. /**
  4006. * Check if BlobBuilder is supported
  4007. */
  4008. var blobBuilderSupported = BlobBuilder
  4009. && BlobBuilder.prototype.append
  4010. && BlobBuilder.prototype.getBlob;
  4011. /**
  4012. * Helper function that maps ArrayBufferViews to ArrayBuffers
  4013. * Used by BlobBuilder constructor and old browsers that didn't
  4014. * support it in the Blob constructor.
  4015. */
  4016. function mapArrayBufferViews(ary) {
  4017. for (var i = 0; i < ary.length; i++) {
  4018. var chunk = ary[i];
  4019. if (chunk.buffer instanceof ArrayBuffer) {
  4020. var buf = chunk.buffer;
  4021. // if this is a subarray, make a copy so we only
  4022. // include the subarray region from the underlying buffer
  4023. if (chunk.byteLength !== buf.byteLength) {
  4024. var copy = new Uint8Array(chunk.byteLength);
  4025. copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
  4026. buf = copy.buffer;
  4027. }
  4028. ary[i] = buf;
  4029. }
  4030. }
  4031. }
  4032. function BlobBuilderConstructor(ary, options) {
  4033. options = options || {};
  4034. var bb = new BlobBuilder();
  4035. mapArrayBufferViews(ary);
  4036. for (var i = 0; i < ary.length; i++) {
  4037. bb.append(ary[i]);
  4038. }
  4039. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  4040. };
  4041. function BlobConstructor(ary, options) {
  4042. mapArrayBufferViews(ary);
  4043. return new Blob(ary, options || {});
  4044. };
  4045. module.exports = (function() {
  4046. if (blobSupported) {
  4047. return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
  4048. } else if (blobBuilderSupported) {
  4049. return BlobBuilderConstructor;
  4050. } else {
  4051. return undefined;
  4052. }
  4053. })();
  4054. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4055. },{}],31:[function(_dereq_,module,exports){
  4056. (function (global){
  4057. /*! https://mths.be/utf8js v2.0.0 by @mathias */
  4058. ;(function(root) {
  4059. // Detect free variables `exports`
  4060. var freeExports = typeof exports == 'object' && exports;
  4061. // Detect free variable `module`
  4062. var freeModule = typeof module == 'object' && module &&
  4063. module.exports == freeExports && module;
  4064. // Detect free variable `global`, from Node.js or Browserified code,
  4065. // and use it as `root`
  4066. var freeGlobal = typeof global == 'object' && global;
  4067. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  4068. root = freeGlobal;
  4069. }
  4070. /*--------------------------------------------------------------------------*/
  4071. var stringFromCharCode = String.fromCharCode;
  4072. // Taken from https://mths.be/punycode
  4073. function ucs2decode(string) {
  4074. var output = [];
  4075. var counter = 0;
  4076. var length = string.length;
  4077. var value;
  4078. var extra;
  4079. while (counter < length) {
  4080. value = string.charCodeAt(counter++);
  4081. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  4082. // high surrogate, and there is a next character
  4083. extra = string.charCodeAt(counter++);
  4084. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  4085. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  4086. } else {
  4087. // unmatched surrogate; only append this code unit, in case the next
  4088. // code unit is the high surrogate of a surrogate pair
  4089. output.push(value);
  4090. counter--;
  4091. }
  4092. } else {
  4093. output.push(value);
  4094. }
  4095. }
  4096. return output;
  4097. }
  4098. // Taken from https://mths.be/punycode
  4099. function ucs2encode(array) {
  4100. var length = array.length;
  4101. var index = -1;
  4102. var value;
  4103. var output = '';
  4104. while (++index < length) {
  4105. value = array[index];
  4106. if (value > 0xFFFF) {
  4107. value -= 0x10000;
  4108. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  4109. value = 0xDC00 | value & 0x3FF;
  4110. }
  4111. output += stringFromCharCode(value);
  4112. }
  4113. return output;
  4114. }
  4115. function checkScalarValue(codePoint) {
  4116. if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
  4117. throw Error(
  4118. 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
  4119. ' is not a scalar value'
  4120. );
  4121. }
  4122. }
  4123. /*--------------------------------------------------------------------------*/
  4124. function createByte(codePoint, shift) {
  4125. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  4126. }
  4127. function encodeCodePoint(codePoint) {
  4128. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  4129. return stringFromCharCode(codePoint);
  4130. }
  4131. var symbol = '';
  4132. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  4133. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  4134. }
  4135. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  4136. checkScalarValue(codePoint);
  4137. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  4138. symbol += createByte(codePoint, 6);
  4139. }
  4140. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  4141. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  4142. symbol += createByte(codePoint, 12);
  4143. symbol += createByte(codePoint, 6);
  4144. }
  4145. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  4146. return symbol;
  4147. }
  4148. function utf8encode(string) {
  4149. var codePoints = ucs2decode(string);
  4150. var length = codePoints.length;
  4151. var index = -1;
  4152. var codePoint;
  4153. var byteString = '';
  4154. while (++index < length) {
  4155. codePoint = codePoints[index];
  4156. byteString += encodeCodePoint(codePoint);
  4157. }
  4158. return byteString;
  4159. }
  4160. /*--------------------------------------------------------------------------*/
  4161. function readContinuationByte() {
  4162. if (byteIndex >= byteCount) {
  4163. throw Error('Invalid byte index');
  4164. }
  4165. var continuationByte = byteArray[byteIndex] & 0xFF;
  4166. byteIndex++;
  4167. if ((continuationByte & 0xC0) == 0x80) {
  4168. return continuationByte & 0x3F;
  4169. }
  4170. // If we end up here, it’s not a continuation byte
  4171. throw Error('Invalid continuation byte');
  4172. }
  4173. function decodeSymbol() {
  4174. var byte1;
  4175. var byte2;
  4176. var byte3;
  4177. var byte4;
  4178. var codePoint;
  4179. if (byteIndex > byteCount) {
  4180. throw Error('Invalid byte index');
  4181. }
  4182. if (byteIndex == byteCount) {
  4183. return false;
  4184. }
  4185. // Read first byte
  4186. byte1 = byteArray[byteIndex] & 0xFF;
  4187. byteIndex++;
  4188. // 1-byte sequence (no continuation bytes)
  4189. if ((byte1 & 0x80) == 0) {
  4190. return byte1;
  4191. }
  4192. // 2-byte sequence
  4193. if ((byte1 & 0xE0) == 0xC0) {
  4194. var byte2 = readContinuationByte();
  4195. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  4196. if (codePoint >= 0x80) {
  4197. return codePoint;
  4198. } else {
  4199. throw Error('Invalid continuation byte');
  4200. }
  4201. }
  4202. // 3-byte sequence (may include unpaired surrogates)
  4203. if ((byte1 & 0xF0) == 0xE0) {
  4204. byte2 = readContinuationByte();
  4205. byte3 = readContinuationByte();
  4206. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  4207. if (codePoint >= 0x0800) {
  4208. checkScalarValue(codePoint);
  4209. return codePoint;
  4210. } else {
  4211. throw Error('Invalid continuation byte');
  4212. }
  4213. }
  4214. // 4-byte sequence
  4215. if ((byte1 & 0xF8) == 0xF0) {
  4216. byte2 = readContinuationByte();
  4217. byte3 = readContinuationByte();
  4218. byte4 = readContinuationByte();
  4219. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  4220. (byte3 << 0x06) | byte4;
  4221. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  4222. return codePoint;
  4223. }
  4224. }
  4225. throw Error('Invalid UTF-8 detected');
  4226. }
  4227. var byteArray;
  4228. var byteCount;
  4229. var byteIndex;
  4230. function utf8decode(byteString) {
  4231. byteArray = ucs2decode(byteString);
  4232. byteCount = byteArray.length;
  4233. byteIndex = 0;
  4234. var codePoints = [];
  4235. var tmp;
  4236. while ((tmp = decodeSymbol()) !== false) {
  4237. codePoints.push(tmp);
  4238. }
  4239. return ucs2encode(codePoints);
  4240. }
  4241. /*--------------------------------------------------------------------------*/
  4242. var utf8 = {
  4243. 'version': '2.0.0',
  4244. 'encode': utf8encode,
  4245. 'decode': utf8decode
  4246. };
  4247. // Some AMD build optimizers, like r.js, check for specific condition patterns
  4248. // like the following:
  4249. if (
  4250. typeof define == 'function' &&
  4251. typeof define.amd == 'object' &&
  4252. define.amd
  4253. ) {
  4254. define(function() {
  4255. return utf8;
  4256. });
  4257. } else if (freeExports && !freeExports.nodeType) {
  4258. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  4259. freeModule.exports = utf8;
  4260. } else { // in Narwhal or RingoJS v0.7.0-
  4261. var object = {};
  4262. var hasOwnProperty = object.hasOwnProperty;
  4263. for (var key in utf8) {
  4264. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  4265. }
  4266. }
  4267. } else { // in Rhino or a web browser
  4268. root.utf8 = utf8;
  4269. }
  4270. }(this));
  4271. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4272. },{}],32:[function(_dereq_,module,exports){
  4273. (function (global){
  4274. /**
  4275. * JSON parse.
  4276. *
  4277. * @see Based on jQuery#parseJSON (MIT) and JSON2
  4278. * @api private
  4279. */
  4280. var rvalidchars = /^[\],:{}\s]*$/;
  4281. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  4282. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  4283. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  4284. var rtrimLeft = /^\s+/;
  4285. var rtrimRight = /\s+$/;
  4286. module.exports = function parsejson(data) {
  4287. if ('string' != typeof data || !data) {
  4288. return null;
  4289. }
  4290. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  4291. // Attempt to parse using the native JSON parser first
  4292. if (global.JSON && JSON.parse) {
  4293. return JSON.parse(data);
  4294. }
  4295. if (rvalidchars.test(data.replace(rvalidescape, '@')
  4296. .replace(rvalidtokens, ']')
  4297. .replace(rvalidbraces, ''))) {
  4298. return (new Function('return ' + data))();
  4299. }
  4300. };
  4301. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4302. },{}],33:[function(_dereq_,module,exports){
  4303. /**
  4304. * Compiles a querystring
  4305. * Returns string representation of the object
  4306. *
  4307. * @param {Object}
  4308. * @api private
  4309. */
  4310. exports.encode = function (obj) {
  4311. var str = '';
  4312. for (var i in obj) {
  4313. if (obj.hasOwnProperty(i)) {
  4314. if (str.length) str += '&';
  4315. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  4316. }
  4317. }
  4318. return str;
  4319. };
  4320. /**
  4321. * Parses a simple querystring into an object
  4322. *
  4323. * @param {String} qs
  4324. * @api private
  4325. */
  4326. exports.decode = function(qs){
  4327. var qry = {};
  4328. var pairs = qs.split('&');
  4329. for (var i = 0, l = pairs.length; i < l; i++) {
  4330. var pair = pairs[i].split('=');
  4331. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  4332. }
  4333. return qry;
  4334. };
  4335. },{}],34:[function(_dereq_,module,exports){
  4336. /**
  4337. * Parses an URI
  4338. *
  4339. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  4340. * @api private
  4341. */
  4342. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  4343. var parts = [
  4344. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  4345. ];
  4346. module.exports = function parseuri(str) {
  4347. var src = str,
  4348. b = str.indexOf('['),
  4349. e = str.indexOf(']');
  4350. if (b != -1 && e != -1) {
  4351. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  4352. }
  4353. var m = re.exec(str || ''),
  4354. uri = {},
  4355. i = 14;
  4356. while (i--) {
  4357. uri[parts[i]] = m[i] || '';
  4358. }
  4359. if (b != -1 && e != -1) {
  4360. uri.source = src;
  4361. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  4362. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  4363. uri.ipv6uri = true;
  4364. }
  4365. return uri;
  4366. };
  4367. },{}],35:[function(_dereq_,module,exports){
  4368. /**
  4369. * Module dependencies.
  4370. */
  4371. var global = (function() { return this; })();
  4372. /**
  4373. * WebSocket constructor.
  4374. */
  4375. var WebSocket = global.WebSocket || global.MozWebSocket;
  4376. /**
  4377. * Module exports.
  4378. */
  4379. module.exports = WebSocket ? ws : null;
  4380. /**
  4381. * WebSocket constructor.
  4382. *
  4383. * The third `opts` options object gets ignored in web browsers, since it's
  4384. * non-standard, and throws a TypeError if passed to the constructor.
  4385. * See: https://github.com/einaros/ws/issues/227
  4386. *
  4387. * @param {String} uri
  4388. * @param {Array} protocols (optional)
  4389. * @param {Object) opts (optional)
  4390. * @api public
  4391. */
  4392. function ws(uri, protocols, opts) {
  4393. var instance;
  4394. if (protocols) {
  4395. instance = new WebSocket(uri, protocols);
  4396. } else {
  4397. instance = new WebSocket(uri);
  4398. }
  4399. return instance;
  4400. }
  4401. if (WebSocket) ws.prototype = WebSocket.prototype;
  4402. },{}],36:[function(_dereq_,module,exports){
  4403. (function (global){
  4404. /*
  4405. * Module requirements.
  4406. */
  4407. var isArray = _dereq_('isarray');
  4408. /**
  4409. * Module exports.
  4410. */
  4411. module.exports = hasBinary;
  4412. /**
  4413. * Checks for binary data.
  4414. *
  4415. * Right now only Buffer and ArrayBuffer are supported..
  4416. *
  4417. * @param {Object} anything
  4418. * @api public
  4419. */
  4420. function hasBinary(data) {
  4421. function _hasBinary(obj) {
  4422. if (!obj) return false;
  4423. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  4424. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  4425. (global.Blob && obj instanceof Blob) ||
  4426. (global.File && obj instanceof File)
  4427. ) {
  4428. return true;
  4429. }
  4430. if (isArray(obj)) {
  4431. for (var i = 0; i < obj.length; i++) {
  4432. if (_hasBinary(obj[i])) {
  4433. return true;
  4434. }
  4435. }
  4436. } else if (obj && 'object' == typeof obj) {
  4437. if (obj.toJSON) {
  4438. obj = obj.toJSON();
  4439. }
  4440. for (var key in obj) {
  4441. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  4442. return true;
  4443. }
  4444. }
  4445. }
  4446. return false;
  4447. }
  4448. return _hasBinary(data);
  4449. }
  4450. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4451. },{"isarray":37}],37:[function(_dereq_,module,exports){
  4452. module.exports = Array.isArray || function (arr) {
  4453. return Object.prototype.toString.call(arr) == '[object Array]';
  4454. };
  4455. },{}],38:[function(_dereq_,module,exports){
  4456. /**
  4457. * Module dependencies.
  4458. */
  4459. var global = _dereq_('global');
  4460. /**
  4461. * Module exports.
  4462. *
  4463. * Logic borrowed from Modernizr:
  4464. *
  4465. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  4466. */
  4467. try {
  4468. module.exports = 'XMLHttpRequest' in global &&
  4469. 'withCredentials' in new global.XMLHttpRequest();
  4470. } catch (err) {
  4471. // if XMLHttp support is disabled in IE then it will throw
  4472. // when trying to create
  4473. module.exports = false;
  4474. }
  4475. },{"global":39}],39:[function(_dereq_,module,exports){
  4476. /**
  4477. * Returns `this`. Execute this without a "context" (i.e. without it being
  4478. * attached to an object of the left-hand side), and `this` points to the
  4479. * "global" scope of the current JS execution.
  4480. */
  4481. module.exports = (function () { return this; })();
  4482. },{}],40:[function(_dereq_,module,exports){
  4483. var indexOf = [].indexOf;
  4484. module.exports = function(arr, obj){
  4485. if (indexOf) return arr.indexOf(obj);
  4486. for (var i = 0; i < arr.length; ++i) {
  4487. if (arr[i] === obj) return i;
  4488. }
  4489. return -1;
  4490. };
  4491. },{}],41:[function(_dereq_,module,exports){
  4492. /**
  4493. * HOP ref.
  4494. */
  4495. var has = Object.prototype.hasOwnProperty;
  4496. /**
  4497. * Return own keys in `obj`.
  4498. *
  4499. * @param {Object} obj
  4500. * @return {Array}
  4501. * @api public
  4502. */
  4503. exports.keys = Object.keys || function(obj){
  4504. var keys = [];
  4505. for (var key in obj) {
  4506. if (has.call(obj, key)) {
  4507. keys.push(key);
  4508. }
  4509. }
  4510. return keys;
  4511. };
  4512. /**
  4513. * Return own values in `obj`.
  4514. *
  4515. * @param {Object} obj
  4516. * @return {Array}
  4517. * @api public
  4518. */
  4519. exports.values = function(obj){
  4520. var vals = [];
  4521. for (var key in obj) {
  4522. if (has.call(obj, key)) {
  4523. vals.push(obj[key]);
  4524. }
  4525. }
  4526. return vals;
  4527. };
  4528. /**
  4529. * Merge `b` into `a`.
  4530. *
  4531. * @param {Object} a
  4532. * @param {Object} b
  4533. * @return {Object} a
  4534. * @api public
  4535. */
  4536. exports.merge = function(a, b){
  4537. for (var key in b) {
  4538. if (has.call(b, key)) {
  4539. a[key] = b[key];
  4540. }
  4541. }
  4542. return a;
  4543. };
  4544. /**
  4545. * Return length of `obj`.
  4546. *
  4547. * @param {Object} obj
  4548. * @return {Number}
  4549. * @api public
  4550. */
  4551. exports.length = function(obj){
  4552. return exports.keys(obj).length;
  4553. };
  4554. /**
  4555. * Check if `obj` is empty.
  4556. *
  4557. * @param {Object} obj
  4558. * @return {Boolean}
  4559. * @api public
  4560. */
  4561. exports.isEmpty = function(obj){
  4562. return 0 == exports.length(obj);
  4563. };
  4564. },{}],42:[function(_dereq_,module,exports){
  4565. /**
  4566. * Parses an URI
  4567. *
  4568. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  4569. * @api private
  4570. */
  4571. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  4572. var parts = [
  4573. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  4574. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  4575. ];
  4576. module.exports = function parseuri(str) {
  4577. var m = re.exec(str || '')
  4578. , uri = {}
  4579. , i = 14;
  4580. while (i--) {
  4581. uri[parts[i]] = m[i] || '';
  4582. }
  4583. return uri;
  4584. };
  4585. },{}],43:[function(_dereq_,module,exports){
  4586. (function (global){
  4587. /*global Blob,File*/
  4588. /**
  4589. * Module requirements
  4590. */
  4591. var isArray = _dereq_('isarray');
  4592. var isBuf = _dereq_('./is-buffer');
  4593. /**
  4594. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  4595. * Anything with blobs or files should be fed through removeBlobs before coming
  4596. * here.
  4597. *
  4598. * @param {Object} packet - socket.io event packet
  4599. * @return {Object} with deconstructed packet and list of buffers
  4600. * @api public
  4601. */
  4602. exports.deconstructPacket = function(packet){
  4603. var buffers = [];
  4604. var packetData = packet.data;
  4605. function _deconstructPacket(data) {
  4606. if (!data) return data;
  4607. if (isBuf(data)) {
  4608. var placeholder = { _placeholder: true, num: buffers.length };
  4609. buffers.push(data);
  4610. return placeholder;
  4611. } else if (isArray(data)) {
  4612. var newData = new Array(data.length);
  4613. for (var i = 0; i < data.length; i++) {
  4614. newData[i] = _deconstructPacket(data[i]);
  4615. }
  4616. return newData;
  4617. } else if ('object' == typeof data && !(data instanceof Date)) {
  4618. var newData = {};
  4619. for (var key in data) {
  4620. newData[key] = _deconstructPacket(data[key]);
  4621. }
  4622. return newData;
  4623. }
  4624. return data;
  4625. }
  4626. var pack = packet;
  4627. pack.data = _deconstructPacket(packetData);
  4628. pack.attachments = buffers.length; // number of binary 'attachments'
  4629. return {packet: pack, buffers: buffers};
  4630. };
  4631. /**
  4632. * Reconstructs a binary packet from its placeholder packet and buffers
  4633. *
  4634. * @param {Object} packet - event packet with placeholders
  4635. * @param {Array} buffers - binary buffers to put in placeholder positions
  4636. * @return {Object} reconstructed packet
  4637. * @api public
  4638. */
  4639. exports.reconstructPacket = function(packet, buffers) {
  4640. var curPlaceHolder = 0;
  4641. function _reconstructPacket(data) {
  4642. if (data && data._placeholder) {
  4643. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  4644. return buf;
  4645. } else if (isArray(data)) {
  4646. for (var i = 0; i < data.length; i++) {
  4647. data[i] = _reconstructPacket(data[i]);
  4648. }
  4649. return data;
  4650. } else if (data && 'object' == typeof data) {
  4651. for (var key in data) {
  4652. data[key] = _reconstructPacket(data[key]);
  4653. }
  4654. return data;
  4655. }
  4656. return data;
  4657. }
  4658. packet.data = _reconstructPacket(packet.data);
  4659. packet.attachments = undefined; // no longer useful
  4660. return packet;
  4661. };
  4662. /**
  4663. * Asynchronously removes Blobs or Files from data via
  4664. * FileReader's readAsArrayBuffer method. Used before encoding
  4665. * data as msgpack. Calls callback with the blobless data.
  4666. *
  4667. * @param {Object} data
  4668. * @param {Function} callback
  4669. * @api private
  4670. */
  4671. exports.removeBlobs = function(data, callback) {
  4672. function _removeBlobs(obj, curKey, containingObject) {
  4673. if (!obj) return obj;
  4674. // convert any blob
  4675. if ((global.Blob && obj instanceof Blob) ||
  4676. (global.File && obj instanceof File)) {
  4677. pendingBlobs++;
  4678. // async filereader
  4679. var fileReader = new FileReader();
  4680. fileReader.onload = function() { // this.result == arraybuffer
  4681. if (containingObject) {
  4682. containingObject[curKey] = this.result;
  4683. }
  4684. else {
  4685. bloblessData = this.result;
  4686. }
  4687. // if nothing pending its callback time
  4688. if(! --pendingBlobs) {
  4689. callback(bloblessData);
  4690. }
  4691. };
  4692. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  4693. } else if (isArray(obj)) { // handle array
  4694. for (var i = 0; i < obj.length; i++) {
  4695. _removeBlobs(obj[i], i, obj);
  4696. }
  4697. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  4698. for (var key in obj) {
  4699. _removeBlobs(obj[key], key, obj);
  4700. }
  4701. }
  4702. }
  4703. var pendingBlobs = 0;
  4704. var bloblessData = data;
  4705. _removeBlobs(bloblessData);
  4706. if (!pendingBlobs) {
  4707. callback(bloblessData);
  4708. }
  4709. };
  4710. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4711. },{"./is-buffer":45,"isarray":46}],44:[function(_dereq_,module,exports){
  4712. /**
  4713. * Module dependencies.
  4714. */
  4715. var debug = _dereq_('debug')('socket.io-parser');
  4716. var json = _dereq_('json3');
  4717. var isArray = _dereq_('isarray');
  4718. var Emitter = _dereq_('component-emitter');
  4719. var binary = _dereq_('./binary');
  4720. var isBuf = _dereq_('./is-buffer');
  4721. /**
  4722. * Protocol version.
  4723. *
  4724. * @api public
  4725. */
  4726. exports.protocol = 4;
  4727. /**
  4728. * Packet types.
  4729. *
  4730. * @api public
  4731. */
  4732. exports.types = [
  4733. 'CONNECT',
  4734. 'DISCONNECT',
  4735. 'EVENT',
  4736. 'BINARY_EVENT',
  4737. 'ACK',
  4738. 'BINARY_ACK',
  4739. 'ERROR'
  4740. ];
  4741. /**
  4742. * Packet type `connect`.
  4743. *
  4744. * @api public
  4745. */
  4746. exports.CONNECT = 0;
  4747. /**
  4748. * Packet type `disconnect`.
  4749. *
  4750. * @api public
  4751. */
  4752. exports.DISCONNECT = 1;
  4753. /**
  4754. * Packet type `event`.
  4755. *
  4756. * @api public
  4757. */
  4758. exports.EVENT = 2;
  4759. /**
  4760. * Packet type `ack`.
  4761. *
  4762. * @api public
  4763. */
  4764. exports.ACK = 3;
  4765. /**
  4766. * Packet type `error`.
  4767. *
  4768. * @api public
  4769. */
  4770. exports.ERROR = 4;
  4771. /**
  4772. * Packet type 'binary event'
  4773. *
  4774. * @api public
  4775. */
  4776. exports.BINARY_EVENT = 5;
  4777. /**
  4778. * Packet type `binary ack`. For acks with binary arguments.
  4779. *
  4780. * @api public
  4781. */
  4782. exports.BINARY_ACK = 6;
  4783. /**
  4784. * Encoder constructor.
  4785. *
  4786. * @api public
  4787. */
  4788. exports.Encoder = Encoder;
  4789. /**
  4790. * Decoder constructor.
  4791. *
  4792. * @api public
  4793. */
  4794. exports.Decoder = Decoder;
  4795. /**
  4796. * A socket.io Encoder instance
  4797. *
  4798. * @api public
  4799. */
  4800. function Encoder() {}
  4801. /**
  4802. * Encode a packet as a single string if non-binary, or as a
  4803. * buffer sequence, depending on packet type.
  4804. *
  4805. * @param {Object} obj - packet object
  4806. * @param {Function} callback - function to handle encodings (likely engine.write)
  4807. * @return Calls callback with Array of encodings
  4808. * @api public
  4809. */
  4810. Encoder.prototype.encode = function(obj, callback){
  4811. debug('encoding packet %j', obj);
  4812. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  4813. encodeAsBinary(obj, callback);
  4814. }
  4815. else {
  4816. var encoding = encodeAsString(obj);
  4817. callback([encoding]);
  4818. }
  4819. };
  4820. /**
  4821. * Encode packet as string.
  4822. *
  4823. * @param {Object} packet
  4824. * @return {String} encoded
  4825. * @api private
  4826. */
  4827. function encodeAsString(obj) {
  4828. var str = '';
  4829. var nsp = false;
  4830. // first is type
  4831. str += obj.type;
  4832. // attachments if we have them
  4833. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  4834. str += obj.attachments;
  4835. str += '-';
  4836. }
  4837. // if we have a namespace other than `/`
  4838. // we append it followed by a comma `,`
  4839. if (obj.nsp && '/' != obj.nsp) {
  4840. nsp = true;
  4841. str += obj.nsp;
  4842. }
  4843. // immediately followed by the id
  4844. if (null != obj.id) {
  4845. if (nsp) {
  4846. str += ',';
  4847. nsp = false;
  4848. }
  4849. str += obj.id;
  4850. }
  4851. // json data
  4852. if (null != obj.data) {
  4853. if (nsp) str += ',';
  4854. str += json.stringify(obj.data);
  4855. }
  4856. debug('encoded %j as %s', obj, str);
  4857. return str;
  4858. }
  4859. /**
  4860. * Encode packet as 'buffer sequence' by removing blobs, and
  4861. * deconstructing packet into object with placeholders and
  4862. * a list of buffers.
  4863. *
  4864. * @param {Object} packet
  4865. * @return {Buffer} encoded
  4866. * @api private
  4867. */
  4868. function encodeAsBinary(obj, callback) {
  4869. function writeEncoding(bloblessData) {
  4870. var deconstruction = binary.deconstructPacket(bloblessData);
  4871. var pack = encodeAsString(deconstruction.packet);
  4872. var buffers = deconstruction.buffers;
  4873. buffers.unshift(pack); // add packet info to beginning of data list
  4874. callback(buffers); // write all the buffers
  4875. }
  4876. binary.removeBlobs(obj, writeEncoding);
  4877. }
  4878. /**
  4879. * A socket.io Decoder instance
  4880. *
  4881. * @return {Object} decoder
  4882. * @api public
  4883. */
  4884. function Decoder() {
  4885. this.reconstructor = null;
  4886. }
  4887. /**
  4888. * Mix in `Emitter` with Decoder.
  4889. */
  4890. Emitter(Decoder.prototype);
  4891. /**
  4892. * Decodes an ecoded packet string into packet JSON.
  4893. *
  4894. * @param {String} obj - encoded packet
  4895. * @return {Object} packet
  4896. * @api public
  4897. */
  4898. Decoder.prototype.add = function(obj) {
  4899. var packet;
  4900. if ('string' == typeof obj) {
  4901. packet = decodeString(obj);
  4902. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  4903. this.reconstructor = new BinaryReconstructor(packet);
  4904. // no attachments, labeled binary but no binary data to follow
  4905. if (this.reconstructor.reconPack.attachments === 0) {
  4906. this.emit('decoded', packet);
  4907. }
  4908. } else { // non-binary full packet
  4909. this.emit('decoded', packet);
  4910. }
  4911. }
  4912. else if (isBuf(obj) || obj.base64) { // raw binary data
  4913. if (!this.reconstructor) {
  4914. throw new Error('got binary data when not reconstructing a packet');
  4915. } else {
  4916. packet = this.reconstructor.takeBinaryData(obj);
  4917. if (packet) { // received final buffer
  4918. this.reconstructor = null;
  4919. this.emit('decoded', packet);
  4920. }
  4921. }
  4922. }
  4923. else {
  4924. throw new Error('Unknown type: ' + obj);
  4925. }
  4926. };
  4927. /**
  4928. * Decode a packet String (JSON data)
  4929. *
  4930. * @param {String} str
  4931. * @return {Object} packet
  4932. * @api private
  4933. */
  4934. function decodeString(str) {
  4935. var p = {};
  4936. var i = 0;
  4937. // look up type
  4938. p.type = Number(str.charAt(0));
  4939. if (null == exports.types[p.type]) return error();
  4940. // look up attachments if type binary
  4941. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  4942. var buf = '';
  4943. while (str.charAt(++i) != '-') {
  4944. buf += str.charAt(i);
  4945. if (i == str.length) break;
  4946. }
  4947. if (buf != Number(buf) || str.charAt(i) != '-') {
  4948. throw new Error('Illegal attachments');
  4949. }
  4950. p.attachments = Number(buf);
  4951. }
  4952. // look up namespace (if any)
  4953. if ('/' == str.charAt(i + 1)) {
  4954. p.nsp = '';
  4955. while (++i) {
  4956. var c = str.charAt(i);
  4957. if (',' == c) break;
  4958. p.nsp += c;
  4959. if (i == str.length) break;
  4960. }
  4961. } else {
  4962. p.nsp = '/';
  4963. }
  4964. // look up id
  4965. var next = str.charAt(i + 1);
  4966. if ('' !== next && Number(next) == next) {
  4967. p.id = '';
  4968. while (++i) {
  4969. var c = str.charAt(i);
  4970. if (null == c || Number(c) != c) {
  4971. --i;
  4972. break;
  4973. }
  4974. p.id += str.charAt(i);
  4975. if (i == str.length) break;
  4976. }
  4977. p.id = Number(p.id);
  4978. }
  4979. // look up json data
  4980. if (str.charAt(++i)) {
  4981. try {
  4982. p.data = json.parse(str.substr(i));
  4983. } catch(e){
  4984. return error();
  4985. }
  4986. }
  4987. debug('decoded %s as %j', str, p);
  4988. return p;
  4989. }
  4990. /**
  4991. * Deallocates a parser's resources
  4992. *
  4993. * @api public
  4994. */
  4995. Decoder.prototype.destroy = function() {
  4996. if (this.reconstructor) {
  4997. this.reconstructor.finishedReconstruction();
  4998. }
  4999. };
  5000. /**
  5001. * A manager of a binary event's 'buffer sequence'. Should
  5002. * be constructed whenever a packet of type BINARY_EVENT is
  5003. * decoded.
  5004. *
  5005. * @param {Object} packet
  5006. * @return {BinaryReconstructor} initialized reconstructor
  5007. * @api private
  5008. */
  5009. function BinaryReconstructor(packet) {
  5010. this.reconPack = packet;
  5011. this.buffers = [];
  5012. }
  5013. /**
  5014. * Method to be called when binary data received from connection
  5015. * after a BINARY_EVENT packet.
  5016. *
  5017. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  5018. * @return {null | Object} returns null if more binary data is expected or
  5019. * a reconstructed packet object if all buffers have been received.
  5020. * @api private
  5021. */
  5022. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  5023. this.buffers.push(binData);
  5024. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  5025. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  5026. this.finishedReconstruction();
  5027. return packet;
  5028. }
  5029. return null;
  5030. };
  5031. /**
  5032. * Cleans up binary packet reconstruction variables.
  5033. *
  5034. * @api private
  5035. */
  5036. BinaryReconstructor.prototype.finishedReconstruction = function() {
  5037. this.reconPack = null;
  5038. this.buffers = [];
  5039. };
  5040. function error(data){
  5041. return {
  5042. type: exports.ERROR,
  5043. data: 'parser error'
  5044. };
  5045. }
  5046. },{"./binary":43,"./is-buffer":45,"component-emitter":9,"debug":10,"isarray":46,"json3":47}],45:[function(_dereq_,module,exports){
  5047. (function (global){
  5048. module.exports = isBuf;
  5049. /**
  5050. * Returns true if obj is a buffer or an arraybuffer.
  5051. *
  5052. * @api private
  5053. */
  5054. function isBuf(obj) {
  5055. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  5056. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  5057. }
  5058. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5059. },{}],46:[function(_dereq_,module,exports){
  5060. module.exports=_dereq_(37)
  5061. },{}],47:[function(_dereq_,module,exports){
  5062. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  5063. ;(function (window) {
  5064. // Convenience aliases.
  5065. var getClass = {}.toString, isProperty, forEach, undef;
  5066. // Detect the `define` function exposed by asynchronous module loaders. The
  5067. // strict `define` check is necessary for compatibility with `r.js`.
  5068. var isLoader = typeof define === "function" && define.amd;
  5069. // Detect native implementations.
  5070. var nativeJSON = typeof JSON == "object" && JSON;
  5071. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  5072. // available.
  5073. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  5074. if (JSON3 && nativeJSON) {
  5075. // Explicitly delegate to the native `stringify` and `parse`
  5076. // implementations in CommonJS environments.
  5077. JSON3.stringify = nativeJSON.stringify;
  5078. JSON3.parse = nativeJSON.parse;
  5079. } else {
  5080. // Export for web browsers, JavaScript engines, and asynchronous module
  5081. // loaders, using the global `JSON` object if available.
  5082. JSON3 = window.JSON = nativeJSON || {};
  5083. }
  5084. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  5085. var isExtended = new Date(-3509827334573292);
  5086. try {
  5087. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  5088. // results for certain dates in Opera >= 10.53.
  5089. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  5090. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  5091. // but clips the values returned by the date methods to the range of
  5092. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  5093. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  5094. } catch (exception) {}
  5095. // Internal: Determines whether the native `JSON.stringify` and `parse`
  5096. // implementations are spec-compliant. Based on work by Ken Snyder.
  5097. function has(name) {
  5098. if (has[name] !== undef) {
  5099. // Return cached feature test result.
  5100. return has[name];
  5101. }
  5102. var isSupported;
  5103. if (name == "bug-string-char-index") {
  5104. // IE <= 7 doesn't support accessing string characters using square
  5105. // bracket notation. IE 8 only supports this for primitives.
  5106. isSupported = "a"[0] != "a";
  5107. } else if (name == "json") {
  5108. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  5109. // supported.
  5110. isSupported = has("json-stringify") && has("json-parse");
  5111. } else {
  5112. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  5113. // Test `JSON.stringify`.
  5114. if (name == "json-stringify") {
  5115. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  5116. if (stringifySupported) {
  5117. // A test function object with a custom `toJSON` method.
  5118. (value = function () {
  5119. return 1;
  5120. }).toJSON = value;
  5121. try {
  5122. stringifySupported =
  5123. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  5124. // primitives as object literals.
  5125. stringify(0) === "0" &&
  5126. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  5127. // literals.
  5128. stringify(new Number()) === "0" &&
  5129. stringify(new String()) == '""' &&
  5130. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  5131. // does not define a canonical JSON representation (this applies to
  5132. // objects with `toJSON` properties as well, *unless* they are nested
  5133. // within an object or array).
  5134. stringify(getClass) === undef &&
  5135. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  5136. // FF 3.1b3 pass this test.
  5137. stringify(undef) === undef &&
  5138. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  5139. // respectively, if the value is omitted entirely.
  5140. stringify() === undef &&
  5141. // FF 3.1b1, 2 throw an error if the given value is not a number,
  5142. // string, array, object, Boolean, or `null` literal. This applies to
  5143. // objects with custom `toJSON` methods as well, unless they are nested
  5144. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  5145. // methods entirely.
  5146. stringify(value) === "1" &&
  5147. stringify([value]) == "[1]" &&
  5148. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  5149. // `"[null]"`.
  5150. stringify([undef]) == "[null]" &&
  5151. // YUI 3.0.0b1 fails to serialize `null` literals.
  5152. stringify(null) == "null" &&
  5153. // FF 3.1b1, 2 halts serialization if an array contains a function:
  5154. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  5155. // elides non-JSON values from objects and arrays, unless they
  5156. // define custom `toJSON` methods.
  5157. stringify([undef, getClass, null]) == "[null,null,null]" &&
  5158. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  5159. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  5160. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  5161. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  5162. stringify(null, value) === "1" &&
  5163. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  5164. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  5165. // serialize extended years.
  5166. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  5167. // The milliseconds are optional in ES 5, but required in 5.1.
  5168. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  5169. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  5170. // four-digit years instead of six-digit years. Credits: @Yaffle.
  5171. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  5172. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  5173. // values less than 1000. Credits: @Yaffle.
  5174. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  5175. } catch (exception) {
  5176. stringifySupported = false;
  5177. }
  5178. }
  5179. isSupported = stringifySupported;
  5180. }
  5181. // Test `JSON.parse`.
  5182. if (name == "json-parse") {
  5183. var parse = JSON3.parse;
  5184. if (typeof parse == "function") {
  5185. try {
  5186. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  5187. // Conforming implementations should also coerce the initial argument to
  5188. // a string prior to parsing.
  5189. if (parse("0") === 0 && !parse(false)) {
  5190. // Simple parsing test.
  5191. value = parse(serialized);
  5192. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  5193. if (parseSupported) {
  5194. try {
  5195. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  5196. parseSupported = !parse('"\t"');
  5197. } catch (exception) {}
  5198. if (parseSupported) {
  5199. try {
  5200. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  5201. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  5202. // certain octal literals.
  5203. parseSupported = parse("01") !== 1;
  5204. } catch (exception) {}
  5205. }
  5206. if (parseSupported) {
  5207. try {
  5208. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  5209. // points. These environments, along with FF 3.1b1 and 2,
  5210. // also allow trailing commas in JSON objects and arrays.
  5211. parseSupported = parse("1.") !== 1;
  5212. } catch (exception) {}
  5213. }
  5214. }
  5215. }
  5216. } catch (exception) {
  5217. parseSupported = false;
  5218. }
  5219. }
  5220. isSupported = parseSupported;
  5221. }
  5222. }
  5223. return has[name] = !!isSupported;
  5224. }
  5225. if (!has("json")) {
  5226. // Common `[[Class]]` name aliases.
  5227. var functionClass = "[object Function]";
  5228. var dateClass = "[object Date]";
  5229. var numberClass = "[object Number]";
  5230. var stringClass = "[object String]";
  5231. var arrayClass = "[object Array]";
  5232. var booleanClass = "[object Boolean]";
  5233. // Detect incomplete support for accessing string characters by index.
  5234. var charIndexBuggy = has("bug-string-char-index");
  5235. // Define additional utility methods if the `Date` methods are buggy.
  5236. if (!isExtended) {
  5237. var floor = Math.floor;
  5238. // A mapping between the months of the year and the number of days between
  5239. // January 1st and the first of the respective month.
  5240. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  5241. // Internal: Calculates the number of days between the Unix epoch and the
  5242. // first day of the given month.
  5243. var getDay = function (year, month) {
  5244. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  5245. };
  5246. }
  5247. // Internal: Determines if a property is a direct property of the given
  5248. // object. Delegates to the native `Object#hasOwnProperty` method.
  5249. if (!(isProperty = {}.hasOwnProperty)) {
  5250. isProperty = function (property) {
  5251. var members = {}, constructor;
  5252. if ((members.__proto__ = null, members.__proto__ = {
  5253. // The *proto* property cannot be set multiple times in recent
  5254. // versions of Firefox and SeaMonkey.
  5255. "toString": 1
  5256. }, members).toString != getClass) {
  5257. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  5258. // supports the mutable *proto* property.
  5259. isProperty = function (property) {
  5260. // Capture and break the object's prototype chain (see section 8.6.2
  5261. // of the ES 5.1 spec). The parenthesized expression prevents an
  5262. // unsafe transformation by the Closure Compiler.
  5263. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  5264. // Restore the original prototype chain.
  5265. this.__proto__ = original;
  5266. return result;
  5267. };
  5268. } else {
  5269. // Capture a reference to the top-level `Object` constructor.
  5270. constructor = members.constructor;
  5271. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  5272. // other environments.
  5273. isProperty = function (property) {
  5274. var parent = (this.constructor || constructor).prototype;
  5275. return property in this && !(property in parent && this[property] === parent[property]);
  5276. };
  5277. }
  5278. members = null;
  5279. return isProperty.call(this, property);
  5280. };
  5281. }
  5282. // Internal: A set of primitive types used by `isHostType`.
  5283. var PrimitiveTypes = {
  5284. 'boolean': 1,
  5285. 'number': 1,
  5286. 'string': 1,
  5287. 'undefined': 1
  5288. };
  5289. // Internal: Determines if the given object `property` value is a
  5290. // non-primitive.
  5291. var isHostType = function (object, property) {
  5292. var type = typeof object[property];
  5293. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  5294. };
  5295. // Internal: Normalizes the `for...in` iteration algorithm across
  5296. // environments. Each enumerated key is yielded to a `callback` function.
  5297. forEach = function (object, callback) {
  5298. var size = 0, Properties, members, property;
  5299. // Tests for bugs in the current environment's `for...in` algorithm. The
  5300. // `valueOf` property inherits the non-enumerable flag from
  5301. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  5302. (Properties = function () {
  5303. this.valueOf = 0;
  5304. }).prototype.valueOf = 0;
  5305. // Iterate over a new instance of the `Properties` class.
  5306. members = new Properties();
  5307. for (property in members) {
  5308. // Ignore all properties inherited from `Object.prototype`.
  5309. if (isProperty.call(members, property)) {
  5310. size++;
  5311. }
  5312. }
  5313. Properties = members = null;
  5314. // Normalize the iteration algorithm.
  5315. if (!size) {
  5316. // A list of non-enumerable properties inherited from `Object.prototype`.
  5317. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  5318. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  5319. // properties.
  5320. forEach = function (object, callback) {
  5321. var isFunction = getClass.call(object) == functionClass, property, length;
  5322. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  5323. for (property in object) {
  5324. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  5325. // certain conditions; IE does not.
  5326. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  5327. callback(property);
  5328. }
  5329. }
  5330. // Manually invoke the callback for each non-enumerable property.
  5331. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  5332. };
  5333. } else if (size == 2) {
  5334. // Safari <= 2.0.4 enumerates shadowed properties twice.
  5335. forEach = function (object, callback) {
  5336. // Create a set of iterated properties.
  5337. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  5338. for (property in object) {
  5339. // Store each property name to prevent double enumeration. The
  5340. // `prototype` property of functions is not enumerated due to cross-
  5341. // environment inconsistencies.
  5342. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  5343. callback(property);
  5344. }
  5345. }
  5346. };
  5347. } else {
  5348. // No bugs detected; use the standard `for...in` algorithm.
  5349. forEach = function (object, callback) {
  5350. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  5351. for (property in object) {
  5352. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  5353. callback(property);
  5354. }
  5355. }
  5356. // Manually invoke the callback for the `constructor` property due to
  5357. // cross-environment inconsistencies.
  5358. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  5359. callback(property);
  5360. }
  5361. };
  5362. }
  5363. return forEach(object, callback);
  5364. };
  5365. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  5366. // `filter` argument may specify either a function that alters how object and
  5367. // array members are serialized, or an array of strings and numbers that
  5368. // indicates which properties should be serialized. The optional `width`
  5369. // argument may be either a string or number that specifies the indentation
  5370. // level of the output.
  5371. if (!has("json-stringify")) {
  5372. // Internal: A map of control characters and their escaped equivalents.
  5373. var Escapes = {
  5374. 92: "\\\\",
  5375. 34: '\\"',
  5376. 8: "\\b",
  5377. 12: "\\f",
  5378. 10: "\\n",
  5379. 13: "\\r",
  5380. 9: "\\t"
  5381. };
  5382. // Internal: Converts `value` into a zero-padded string such that its
  5383. // length is at least equal to `width`. The `width` must be <= 6.
  5384. var leadingZeroes = "000000";
  5385. var toPaddedString = function (width, value) {
  5386. // The `|| 0` expression is necessary to work around a bug in
  5387. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  5388. return (leadingZeroes + (value || 0)).slice(-width);
  5389. };
  5390. // Internal: Double-quotes a string `value`, replacing all ASCII control
  5391. // characters (characters with code unit values between 0 and 31) with
  5392. // their escaped equivalents. This is an implementation of the
  5393. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  5394. var unicodePrefix = "\\u00";
  5395. var quote = function (value) {
  5396. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  5397. if (isLarge) {
  5398. symbols = value.split("");
  5399. }
  5400. for (; index < length; index++) {
  5401. var charCode = value.charCodeAt(index);
  5402. // If the character is a control character, append its Unicode or
  5403. // shorthand escape sequence; otherwise, append the character as-is.
  5404. switch (charCode) {
  5405. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  5406. result += Escapes[charCode];
  5407. break;
  5408. default:
  5409. if (charCode < 32) {
  5410. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  5411. break;
  5412. }
  5413. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  5414. }
  5415. }
  5416. return result + '"';
  5417. };
  5418. // Internal: Recursively serializes an object. Implements the
  5419. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  5420. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  5421. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  5422. try {
  5423. // Necessary for host object support.
  5424. value = object[property];
  5425. } catch (exception) {}
  5426. if (typeof value == "object" && value) {
  5427. className = getClass.call(value);
  5428. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  5429. if (value > -1 / 0 && value < 1 / 0) {
  5430. // Dates are serialized according to the `Date#toJSON` method
  5431. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  5432. // for the ISO 8601 date time string format.
  5433. if (getDay) {
  5434. // Manually compute the year, month, date, hours, minutes,
  5435. // seconds, and milliseconds if the `getUTC*` methods are
  5436. // buggy. Adapted from @Yaffle's `date-shim` project.
  5437. date = floor(value / 864e5);
  5438. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  5439. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  5440. date = 1 + date - getDay(year, month);
  5441. // The `time` value specifies the time within the day (see ES
  5442. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  5443. // to compute `A modulo B`, as the `%` operator does not
  5444. // correspond to the `modulo` operation for negative numbers.
  5445. time = (value % 864e5 + 864e5) % 864e5;
  5446. // The hours, minutes, seconds, and milliseconds are obtained by
  5447. // decomposing the time within the day. See section 15.9.1.10.
  5448. hours = floor(time / 36e5) % 24;
  5449. minutes = floor(time / 6e4) % 60;
  5450. seconds = floor(time / 1e3) % 60;
  5451. milliseconds = time % 1e3;
  5452. } else {
  5453. year = value.getUTCFullYear();
  5454. month = value.getUTCMonth();
  5455. date = value.getUTCDate();
  5456. hours = value.getUTCHours();
  5457. minutes = value.getUTCMinutes();
  5458. seconds = value.getUTCSeconds();
  5459. milliseconds = value.getUTCMilliseconds();
  5460. }
  5461. // Serialize extended years correctly.
  5462. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  5463. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  5464. // Months, dates, hours, minutes, and seconds should have two
  5465. // digits; milliseconds should have three.
  5466. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  5467. // Milliseconds are optional in ES 5.0, but required in 5.1.
  5468. "." + toPaddedString(3, milliseconds) + "Z";
  5469. } else {
  5470. value = null;
  5471. }
  5472. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  5473. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  5474. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  5475. // ignores all `toJSON` methods on these objects unless they are
  5476. // defined directly on an instance.
  5477. value = value.toJSON(property);
  5478. }
  5479. }
  5480. if (callback) {
  5481. // If a replacement function was provided, call it to obtain the value
  5482. // for serialization.
  5483. value = callback.call(object, property, value);
  5484. }
  5485. if (value === null) {
  5486. return "null";
  5487. }
  5488. className = getClass.call(value);
  5489. if (className == booleanClass) {
  5490. // Booleans are represented literally.
  5491. return "" + value;
  5492. } else if (className == numberClass) {
  5493. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  5494. // `"null"`.
  5495. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  5496. } else if (className == stringClass) {
  5497. // Strings are double-quoted and escaped.
  5498. return quote("" + value);
  5499. }
  5500. // Recursively serialize objects and arrays.
  5501. if (typeof value == "object") {
  5502. // Check for cyclic structures. This is a linear search; performance
  5503. // is inversely proportional to the number of unique nested objects.
  5504. for (length = stack.length; length--;) {
  5505. if (stack[length] === value) {
  5506. // Cyclic structures cannot be serialized by `JSON.stringify`.
  5507. throw TypeError();
  5508. }
  5509. }
  5510. // Add the object to the stack of traversed objects.
  5511. stack.push(value);
  5512. results = [];
  5513. // Save the current indentation level and indent one additional level.
  5514. prefix = indentation;
  5515. indentation += whitespace;
  5516. if (className == arrayClass) {
  5517. // Recursively serialize array elements.
  5518. for (index = 0, length = value.length; index < length; index++) {
  5519. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  5520. results.push(element === undef ? "null" : element);
  5521. }
  5522. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  5523. } else {
  5524. // Recursively serialize object members. Members are selected from
  5525. // either a user-specified list of property names, or the object
  5526. // itself.
  5527. forEach(properties || value, function (property) {
  5528. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  5529. if (element !== undef) {
  5530. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  5531. // is not the empty string, let `member` {quote(property) + ":"}
  5532. // be the concatenation of `member` and the `space` character."
  5533. // The "`space` character" refers to the literal space
  5534. // character, not the `space` {width} argument provided to
  5535. // `JSON.stringify`.
  5536. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  5537. }
  5538. });
  5539. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  5540. }
  5541. // Remove the object from the traversed object stack.
  5542. stack.pop();
  5543. return result;
  5544. }
  5545. };
  5546. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  5547. JSON3.stringify = function (source, filter, width) {
  5548. var whitespace, callback, properties, className;
  5549. if (typeof filter == "function" || typeof filter == "object" && filter) {
  5550. if ((className = getClass.call(filter)) == functionClass) {
  5551. callback = filter;
  5552. } else if (className == arrayClass) {
  5553. // Convert the property names array into a makeshift set.
  5554. properties = {};
  5555. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  5556. }
  5557. }
  5558. if (width) {
  5559. if ((className = getClass.call(width)) == numberClass) {
  5560. // Convert the `width` to an integer and create a string containing
  5561. // `width` number of space characters.
  5562. if ((width -= width % 1) > 0) {
  5563. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  5564. }
  5565. } else if (className == stringClass) {
  5566. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  5567. }
  5568. }
  5569. // Opera <= 7.54u2 discards the values associated with empty string keys
  5570. // (`""`) only if they are used directly within an object member list
  5571. // (e.g., `!("" in { "": 1})`).
  5572. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  5573. };
  5574. }
  5575. // Public: Parses a JSON source string.
  5576. if (!has("json-parse")) {
  5577. var fromCharCode = String.fromCharCode;
  5578. // Internal: A map of escaped control characters and their unescaped
  5579. // equivalents.
  5580. var Unescapes = {
  5581. 92: "\\",
  5582. 34: '"',
  5583. 47: "/",
  5584. 98: "\b",
  5585. 116: "\t",
  5586. 110: "\n",
  5587. 102: "\f",
  5588. 114: "\r"
  5589. };
  5590. // Internal: Stores the parser state.
  5591. var Index, Source;
  5592. // Internal: Resets the parser state and throws a `SyntaxError`.
  5593. var abort = function() {
  5594. Index = Source = null;
  5595. throw SyntaxError();
  5596. };
  5597. // Internal: Returns the next token, or `"$"` if the parser has reached
  5598. // the end of the source string. A token may be a string, number, `null`
  5599. // literal, or Boolean literal.
  5600. var lex = function () {
  5601. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  5602. while (Index < length) {
  5603. charCode = source.charCodeAt(Index);
  5604. switch (charCode) {
  5605. case 9: case 10: case 13: case 32:
  5606. // Skip whitespace tokens, including tabs, carriage returns, line
  5607. // feeds, and space characters.
  5608. Index++;
  5609. break;
  5610. case 123: case 125: case 91: case 93: case 58: case 44:
  5611. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  5612. // the current position.
  5613. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  5614. Index++;
  5615. return value;
  5616. case 34:
  5617. // `"` delimits a JSON string; advance to the next character and
  5618. // begin parsing the string. String tokens are prefixed with the
  5619. // sentinel `@` character to distinguish them from punctuators and
  5620. // end-of-string tokens.
  5621. for (value = "@", Index++; Index < length;) {
  5622. charCode = source.charCodeAt(Index);
  5623. if (charCode < 32) {
  5624. // Unescaped ASCII control characters (those with a code unit
  5625. // less than the space character) are not permitted.
  5626. abort();
  5627. } else if (charCode == 92) {
  5628. // A reverse solidus (`\`) marks the beginning of an escaped
  5629. // control character (including `"`, `\`, and `/`) or Unicode
  5630. // escape sequence.
  5631. charCode = source.charCodeAt(++Index);
  5632. switch (charCode) {
  5633. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  5634. // Revive escaped control characters.
  5635. value += Unescapes[charCode];
  5636. Index++;
  5637. break;
  5638. case 117:
  5639. // `\u` marks the beginning of a Unicode escape sequence.
  5640. // Advance to the first character and validate the
  5641. // four-digit code point.
  5642. begin = ++Index;
  5643. for (position = Index + 4; Index < position; Index++) {
  5644. charCode = source.charCodeAt(Index);
  5645. // A valid sequence comprises four hexdigits (case-
  5646. // insensitive) that form a single hexadecimal value.
  5647. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  5648. // Invalid Unicode escape sequence.
  5649. abort();
  5650. }
  5651. }
  5652. // Revive the escaped character.
  5653. value += fromCharCode("0x" + source.slice(begin, Index));
  5654. break;
  5655. default:
  5656. // Invalid escape sequence.
  5657. abort();
  5658. }
  5659. } else {
  5660. if (charCode == 34) {
  5661. // An unescaped double-quote character marks the end of the
  5662. // string.
  5663. break;
  5664. }
  5665. charCode = source.charCodeAt(Index);
  5666. begin = Index;
  5667. // Optimize for the common case where a string is valid.
  5668. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  5669. charCode = source.charCodeAt(++Index);
  5670. }
  5671. // Append the string as-is.
  5672. value += source.slice(begin, Index);
  5673. }
  5674. }
  5675. if (source.charCodeAt(Index) == 34) {
  5676. // Advance to the next character and return the revived string.
  5677. Index++;
  5678. return value;
  5679. }
  5680. // Unterminated string.
  5681. abort();
  5682. default:
  5683. // Parse numbers and literals.
  5684. begin = Index;
  5685. // Advance past the negative sign, if one is specified.
  5686. if (charCode == 45) {
  5687. isSigned = true;
  5688. charCode = source.charCodeAt(++Index);
  5689. }
  5690. // Parse an integer or floating-point value.
  5691. if (charCode >= 48 && charCode <= 57) {
  5692. // Leading zeroes are interpreted as octal literals.
  5693. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  5694. // Illegal octal literal.
  5695. abort();
  5696. }
  5697. isSigned = false;
  5698. // Parse the integer component.
  5699. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  5700. // Floats cannot contain a leading decimal point; however, this
  5701. // case is already accounted for by the parser.
  5702. if (source.charCodeAt(Index) == 46) {
  5703. position = ++Index;
  5704. // Parse the decimal component.
  5705. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  5706. if (position == Index) {
  5707. // Illegal trailing decimal.
  5708. abort();
  5709. }
  5710. Index = position;
  5711. }
  5712. // Parse exponents. The `e` denoting the exponent is
  5713. // case-insensitive.
  5714. charCode = source.charCodeAt(Index);
  5715. if (charCode == 101 || charCode == 69) {
  5716. charCode = source.charCodeAt(++Index);
  5717. // Skip past the sign following the exponent, if one is
  5718. // specified.
  5719. if (charCode == 43 || charCode == 45) {
  5720. Index++;
  5721. }
  5722. // Parse the exponential component.
  5723. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  5724. if (position == Index) {
  5725. // Illegal empty exponent.
  5726. abort();
  5727. }
  5728. Index = position;
  5729. }
  5730. // Coerce the parsed value to a JavaScript number.
  5731. return +source.slice(begin, Index);
  5732. }
  5733. // A negative sign may only precede numbers.
  5734. if (isSigned) {
  5735. abort();
  5736. }
  5737. // `true`, `false`, and `null` literals.
  5738. if (source.slice(Index, Index + 4) == "true") {
  5739. Index += 4;
  5740. return true;
  5741. } else if (source.slice(Index, Index + 5) == "false") {
  5742. Index += 5;
  5743. return false;
  5744. } else if (source.slice(Index, Index + 4) == "null") {
  5745. Index += 4;
  5746. return null;
  5747. }
  5748. // Unrecognized token.
  5749. abort();
  5750. }
  5751. }
  5752. // Return the sentinel `$` character if the parser has reached the end
  5753. // of the source string.
  5754. return "$";
  5755. };
  5756. // Internal: Parses a JSON `value` token.
  5757. var get = function (value) {
  5758. var results, hasMembers;
  5759. if (value == "$") {
  5760. // Unexpected end of input.
  5761. abort();
  5762. }
  5763. if (typeof value == "string") {
  5764. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  5765. // Remove the sentinel `@` character.
  5766. return value.slice(1);
  5767. }
  5768. // Parse object and array literals.
  5769. if (value == "[") {
  5770. // Parses a JSON array, returning a new JavaScript array.
  5771. results = [];
  5772. for (;; hasMembers || (hasMembers = true)) {
  5773. value = lex();
  5774. // A closing square bracket marks the end of the array literal.
  5775. if (value == "]") {
  5776. break;
  5777. }
  5778. // If the array literal contains elements, the current token
  5779. // should be a comma separating the previous element from the
  5780. // next.
  5781. if (hasMembers) {
  5782. if (value == ",") {
  5783. value = lex();
  5784. if (value == "]") {
  5785. // Unexpected trailing `,` in array literal.
  5786. abort();
  5787. }
  5788. } else {
  5789. // A `,` must separate each array element.
  5790. abort();
  5791. }
  5792. }
  5793. // Elisions and leading commas are not permitted.
  5794. if (value == ",") {
  5795. abort();
  5796. }
  5797. results.push(get(value));
  5798. }
  5799. return results;
  5800. } else if (value == "{") {
  5801. // Parses a JSON object, returning a new JavaScript object.
  5802. results = {};
  5803. for (;; hasMembers || (hasMembers = true)) {
  5804. value = lex();
  5805. // A closing curly brace marks the end of the object literal.
  5806. if (value == "}") {
  5807. break;
  5808. }
  5809. // If the object literal contains members, the current token
  5810. // should be a comma separator.
  5811. if (hasMembers) {
  5812. if (value == ",") {
  5813. value = lex();
  5814. if (value == "}") {
  5815. // Unexpected trailing `,` in object literal.
  5816. abort();
  5817. }
  5818. } else {
  5819. // A `,` must separate each object member.
  5820. abort();
  5821. }
  5822. }
  5823. // Leading commas are not permitted, object property names must be
  5824. // double-quoted strings, and a `:` must separate each property
  5825. // name and value.
  5826. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  5827. abort();
  5828. }
  5829. results[value.slice(1)] = get(lex());
  5830. }
  5831. return results;
  5832. }
  5833. // Unexpected token encountered.
  5834. abort();
  5835. }
  5836. return value;
  5837. };
  5838. // Internal: Updates a traversed object member.
  5839. var update = function(source, property, callback) {
  5840. var element = walk(source, property, callback);
  5841. if (element === undef) {
  5842. delete source[property];
  5843. } else {
  5844. source[property] = element;
  5845. }
  5846. };
  5847. // Internal: Recursively traverses a parsed JSON object, invoking the
  5848. // `callback` function for each value. This is an implementation of the
  5849. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  5850. var walk = function (source, property, callback) {
  5851. var value = source[property], length;
  5852. if (typeof value == "object" && value) {
  5853. // `forEach` can't be used to traverse an array in Opera <= 8.54
  5854. // because its `Object#hasOwnProperty` implementation returns `false`
  5855. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  5856. if (getClass.call(value) == arrayClass) {
  5857. for (length = value.length; length--;) {
  5858. update(value, length, callback);
  5859. }
  5860. } else {
  5861. forEach(value, function (property) {
  5862. update(value, property, callback);
  5863. });
  5864. }
  5865. }
  5866. return callback.call(source, property, value);
  5867. };
  5868. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  5869. JSON3.parse = function (source, callback) {
  5870. var result, value;
  5871. Index = 0;
  5872. Source = "" + source;
  5873. result = get(lex());
  5874. // If a JSON string contains multiple tokens, it is invalid.
  5875. if (lex() != "$") {
  5876. abort();
  5877. }
  5878. // Reset the parser state.
  5879. Index = Source = null;
  5880. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  5881. };
  5882. }
  5883. }
  5884. // Export for asynchronous module loaders.
  5885. if (isLoader) {
  5886. define(function () {
  5887. return JSON3;
  5888. });
  5889. }
  5890. }(this));
  5891. },{}],48:[function(_dereq_,module,exports){
  5892. module.exports = toArray
  5893. function toArray(list, index) {
  5894. var array = []
  5895. index = index || 0
  5896. for (var i = index || 0; i < list.length; i++) {
  5897. array[i - index] = list[i]
  5898. }
  5899. return array
  5900. }
  5901. },{}]},{},[1])
  5902. (1)
  5903. });