websocket.js 197 KB

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