s.js 269 KB

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