sockjs.js 180 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817
  1. /* sockjs-client v1.3.0 | http://sockjs.org | MIT license */
  2. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.SockJS = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  3. (function (global){
  4. 'use strict';
  5. var transportList = require('./transport-list');
  6. module.exports = require('./main')(transportList);
  7. // TODO can't get rid of this until all servers do
  8. if ('_sockjs_onload' in global) {
  9. setTimeout(global._sockjs_onload, 1);
  10. }
  11. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12. },{"./main":14,"./transport-list":16}],2:[function(require,module,exports){
  13. 'use strict';
  14. var inherits = require('inherits')
  15. , Event = require('./event')
  16. ;
  17. function CloseEvent() {
  18. Event.call(this);
  19. this.initEvent('close', false, false);
  20. this.wasClean = false;
  21. this.code = 0;
  22. this.reason = '';
  23. }
  24. inherits(CloseEvent, Event);
  25. module.exports = CloseEvent;
  26. },{"./event":4,"inherits":57}],3:[function(require,module,exports){
  27. 'use strict';
  28. var inherits = require('inherits')
  29. , EventTarget = require('./eventtarget')
  30. ;
  31. function EventEmitter() {
  32. EventTarget.call(this);
  33. }
  34. inherits(EventEmitter, EventTarget);
  35. EventEmitter.prototype.removeAllListeners = function(type) {
  36. if (type) {
  37. delete this._listeners[type];
  38. } else {
  39. this._listeners = {};
  40. }
  41. };
  42. EventEmitter.prototype.once = function(type, listener) {
  43. var self = this
  44. , fired = false;
  45. function g() {
  46. self.removeListener(type, g);
  47. if (!fired) {
  48. fired = true;
  49. listener.apply(this, arguments);
  50. }
  51. }
  52. this.on(type, g);
  53. };
  54. EventEmitter.prototype.emit = function() {
  55. var type = arguments[0];
  56. var listeners = this._listeners[type];
  57. if (!listeners) {
  58. return;
  59. }
  60. // equivalent of Array.prototype.slice.call(arguments, 1);
  61. var l = arguments.length;
  62. var args = new Array(l - 1);
  63. for (var ai = 1; ai < l; ai++) {
  64. args[ai - 1] = arguments[ai];
  65. }
  66. for (var i = 0; i < listeners.length; i++) {
  67. listeners[i].apply(this, args);
  68. }
  69. };
  70. EventEmitter.prototype.on = EventEmitter.prototype.addListener = EventTarget.prototype.addEventListener;
  71. EventEmitter.prototype.removeListener = EventTarget.prototype.removeEventListener;
  72. module.exports.EventEmitter = EventEmitter;
  73. },{"./eventtarget":5,"inherits":57}],4:[function(require,module,exports){
  74. 'use strict';
  75. function Event(eventType) {
  76. this.type = eventType;
  77. }
  78. Event.prototype.initEvent = function(eventType, canBubble, cancelable) {
  79. this.type = eventType;
  80. this.bubbles = canBubble;
  81. this.cancelable = cancelable;
  82. this.timeStamp = +new Date();
  83. return this;
  84. };
  85. Event.prototype.stopPropagation = function() {};
  86. Event.prototype.preventDefault = function() {};
  87. Event.CAPTURING_PHASE = 1;
  88. Event.AT_TARGET = 2;
  89. Event.BUBBLING_PHASE = 3;
  90. module.exports = Event;
  91. },{}],5:[function(require,module,exports){
  92. 'use strict';
  93. /* Simplified implementation of DOM2 EventTarget.
  94. * http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget
  95. */
  96. function EventTarget() {
  97. this._listeners = {};
  98. }
  99. EventTarget.prototype.addEventListener = function(eventType, listener) {
  100. if (!(eventType in this._listeners)) {
  101. this._listeners[eventType] = [];
  102. }
  103. var arr = this._listeners[eventType];
  104. // #4
  105. if (arr.indexOf(listener) === -1) {
  106. // Make a copy so as not to interfere with a current dispatchEvent.
  107. arr = arr.concat([listener]);
  108. }
  109. this._listeners[eventType] = arr;
  110. };
  111. EventTarget.prototype.removeEventListener = function(eventType, listener) {
  112. var arr = this._listeners[eventType];
  113. if (!arr) {
  114. return;
  115. }
  116. var idx = arr.indexOf(listener);
  117. if (idx !== -1) {
  118. if (arr.length > 1) {
  119. // Make a copy so as not to interfere with a current dispatchEvent.
  120. this._listeners[eventType] = arr.slice(0, idx).concat(arr.slice(idx + 1));
  121. } else {
  122. delete this._listeners[eventType];
  123. }
  124. return;
  125. }
  126. };
  127. EventTarget.prototype.dispatchEvent = function() {
  128. var event = arguments[0];
  129. var t = event.type;
  130. // equivalent of Array.prototype.slice.call(arguments, 0);
  131. var args = arguments.length === 1 ? [event] : Array.apply(null, arguments);
  132. // TODO: This doesn't match the real behavior; per spec, onfoo get
  133. // their place in line from the /first/ time they're set from
  134. // non-null. Although WebKit bumps it to the end every time it's
  135. // set.
  136. if (this['on' + t]) {
  137. this['on' + t].apply(this, args);
  138. }
  139. if (t in this._listeners) {
  140. // Grab a reference to the listeners list. removeEventListener may alter the list.
  141. var listeners = this._listeners[t];
  142. for (var i = 0; i < listeners.length; i++) {
  143. listeners[i].apply(this, args);
  144. }
  145. }
  146. };
  147. module.exports = EventTarget;
  148. },{}],6:[function(require,module,exports){
  149. 'use strict';
  150. var inherits = require('inherits')
  151. , Event = require('./event')
  152. ;
  153. function TransportMessageEvent(data) {
  154. Event.call(this);
  155. this.initEvent('message', false, false);
  156. this.data = data;
  157. }
  158. inherits(TransportMessageEvent, Event);
  159. module.exports = TransportMessageEvent;
  160. },{"./event":4,"inherits":57}],7:[function(require,module,exports){
  161. 'use strict';
  162. var JSON3 = require('json3')
  163. , iframeUtils = require('./utils/iframe')
  164. ;
  165. function FacadeJS(transport) {
  166. this._transport = transport;
  167. transport.on('message', this._transportMessage.bind(this));
  168. transport.on('close', this._transportClose.bind(this));
  169. }
  170. FacadeJS.prototype._transportClose = function(code, reason) {
  171. iframeUtils.postMessage('c', JSON3.stringify([code, reason]));
  172. };
  173. FacadeJS.prototype._transportMessage = function(frame) {
  174. iframeUtils.postMessage('t', frame);
  175. };
  176. FacadeJS.prototype._send = function(data) {
  177. this._transport.send(data);
  178. };
  179. FacadeJS.prototype._close = function() {
  180. this._transport.close();
  181. this._transport.removeAllListeners();
  182. };
  183. module.exports = FacadeJS;
  184. },{"./utils/iframe":47,"json3":58}],8:[function(require,module,exports){
  185. (function (process){
  186. 'use strict';
  187. var urlUtils = require('./utils/url')
  188. , eventUtils = require('./utils/event')
  189. , JSON3 = require('json3')
  190. , FacadeJS = require('./facade')
  191. , InfoIframeReceiver = require('./info-iframe-receiver')
  192. , iframeUtils = require('./utils/iframe')
  193. , loc = require('./location')
  194. ;
  195. var debug = function() {};
  196. if (process.env.NODE_ENV !== 'production') {
  197. debug = require('debug')('sockjs-client:iframe-bootstrap');
  198. }
  199. module.exports = function(SockJS, availableTransports) {
  200. var transportMap = {};
  201. availableTransports.forEach(function(at) {
  202. if (at.facadeTransport) {
  203. transportMap[at.facadeTransport.transportName] = at.facadeTransport;
  204. }
  205. });
  206. // hard-coded for the info iframe
  207. // TODO see if we can make this more dynamic
  208. transportMap[InfoIframeReceiver.transportName] = InfoIframeReceiver;
  209. var parentOrigin;
  210. /* eslint-disable camelcase */
  211. SockJS.bootstrap_iframe = function() {
  212. /* eslint-enable camelcase */
  213. var facade;
  214. iframeUtils.currentWindowId = loc.hash.slice(1);
  215. var onMessage = function(e) {
  216. if (e.source !== parent) {
  217. return;
  218. }
  219. if (typeof parentOrigin === 'undefined') {
  220. parentOrigin = e.origin;
  221. }
  222. if (e.origin !== parentOrigin) {
  223. return;
  224. }
  225. var iframeMessage;
  226. try {
  227. iframeMessage = JSON3.parse(e.data);
  228. } catch (ignored) {
  229. debug('bad json', e.data);
  230. return;
  231. }
  232. if (iframeMessage.windowId !== iframeUtils.currentWindowId) {
  233. return;
  234. }
  235. switch (iframeMessage.type) {
  236. case 's':
  237. var p;
  238. try {
  239. p = JSON3.parse(iframeMessage.data);
  240. } catch (ignored) {
  241. debug('bad json', iframeMessage.data);
  242. break;
  243. }
  244. var version = p[0];
  245. var transport = p[1];
  246. var transUrl = p[2];
  247. var baseUrl = p[3];
  248. debug(version, transport, transUrl, baseUrl);
  249. // change this to semver logic
  250. if (version !== SockJS.version) {
  251. throw new Error('Incompatible SockJS! Main site uses:' +
  252. ' "' + version + '", the iframe:' +
  253. ' "' + SockJS.version + '".');
  254. }
  255. if (!urlUtils.isOriginEqual(transUrl, loc.href) ||
  256. !urlUtils.isOriginEqual(baseUrl, loc.href)) {
  257. throw new Error('Can\'t connect to different domain from within an ' +
  258. 'iframe. (' + loc.href + ', ' + transUrl + ', ' + baseUrl + ')');
  259. }
  260. facade = new FacadeJS(new transportMap[transport](transUrl, baseUrl));
  261. break;
  262. case 'm':
  263. facade._send(iframeMessage.data);
  264. break;
  265. case 'c':
  266. if (facade) {
  267. facade._close();
  268. }
  269. facade = null;
  270. break;
  271. }
  272. };
  273. eventUtils.attachEvent('message', onMessage);
  274. // Start
  275. iframeUtils.postMessage('s');
  276. };
  277. };
  278. }).call(this,{ env: {} })
  279. },{"./facade":7,"./info-iframe-receiver":10,"./location":13,"./utils/event":46,"./utils/iframe":47,"./utils/url":52,"debug":55,"json3":58}],9:[function(require,module,exports){
  280. (function (process){
  281. 'use strict';
  282. var EventEmitter = require('events').EventEmitter
  283. , inherits = require('inherits')
  284. , JSON3 = require('json3')
  285. , objectUtils = require('./utils/object')
  286. ;
  287. var debug = function() {};
  288. if (process.env.NODE_ENV !== 'production') {
  289. debug = require('debug')('sockjs-client:info-ajax');
  290. }
  291. function InfoAjax(url, AjaxObject) {
  292. EventEmitter.call(this);
  293. var self = this;
  294. var t0 = +new Date();
  295. this.xo = new AjaxObject('GET', url);
  296. this.xo.once('finish', function(status, text) {
  297. var info, rtt;
  298. if (status === 200) {
  299. rtt = (+new Date()) - t0;
  300. if (text) {
  301. try {
  302. info = JSON3.parse(text);
  303. } catch (e) {
  304. debug('bad json', text);
  305. }
  306. }
  307. if (!objectUtils.isObject(info)) {
  308. info = {};
  309. }
  310. }
  311. self.emit('finish', info, rtt);
  312. self.removeAllListeners();
  313. });
  314. }
  315. inherits(InfoAjax, EventEmitter);
  316. InfoAjax.prototype.close = function() {
  317. this.removeAllListeners();
  318. this.xo.close();
  319. };
  320. module.exports = InfoAjax;
  321. }).call(this,{ env: {} })
  322. },{"./utils/object":49,"debug":55,"events":3,"inherits":57,"json3":58}],10:[function(require,module,exports){
  323. 'use strict';
  324. var inherits = require('inherits')
  325. , EventEmitter = require('events').EventEmitter
  326. , JSON3 = require('json3')
  327. , XHRLocalObject = require('./transport/sender/xhr-local')
  328. , InfoAjax = require('./info-ajax')
  329. ;
  330. function InfoReceiverIframe(transUrl) {
  331. var self = this;
  332. EventEmitter.call(this);
  333. this.ir = new InfoAjax(transUrl, XHRLocalObject);
  334. this.ir.once('finish', function(info, rtt) {
  335. self.ir = null;
  336. self.emit('message', JSON3.stringify([info, rtt]));
  337. });
  338. }
  339. inherits(InfoReceiverIframe, EventEmitter);
  340. InfoReceiverIframe.transportName = 'iframe-info-receiver';
  341. InfoReceiverIframe.prototype.close = function() {
  342. if (this.ir) {
  343. this.ir.close();
  344. this.ir = null;
  345. }
  346. this.removeAllListeners();
  347. };
  348. module.exports = InfoReceiverIframe;
  349. },{"./info-ajax":9,"./transport/sender/xhr-local":37,"events":3,"inherits":57,"json3":58}],11:[function(require,module,exports){
  350. (function (process,global){
  351. 'use strict';
  352. var EventEmitter = require('events').EventEmitter
  353. , inherits = require('inherits')
  354. , JSON3 = require('json3')
  355. , utils = require('./utils/event')
  356. , IframeTransport = require('./transport/iframe')
  357. , InfoReceiverIframe = require('./info-iframe-receiver')
  358. ;
  359. var debug = function() {};
  360. if (process.env.NODE_ENV !== 'production') {
  361. debug = require('debug')('sockjs-client:info-iframe');
  362. }
  363. function InfoIframe(baseUrl, url) {
  364. var self = this;
  365. EventEmitter.call(this);
  366. var go = function() {
  367. var ifr = self.ifr = new IframeTransport(InfoReceiverIframe.transportName, url, baseUrl);
  368. ifr.once('message', function(msg) {
  369. if (msg) {
  370. var d;
  371. try {
  372. d = JSON3.parse(msg);
  373. } catch (e) {
  374. debug('bad json', msg);
  375. self.emit('finish');
  376. self.close();
  377. return;
  378. }
  379. var info = d[0], rtt = d[1];
  380. self.emit('finish', info, rtt);
  381. }
  382. self.close();
  383. });
  384. ifr.once('close', function() {
  385. self.emit('finish');
  386. self.close();
  387. });
  388. };
  389. // TODO this seems the same as the 'needBody' from transports
  390. if (!global.document.body) {
  391. utils.attachEvent('load', go);
  392. } else {
  393. go();
  394. }
  395. }
  396. inherits(InfoIframe, EventEmitter);
  397. InfoIframe.enabled = function() {
  398. return IframeTransport.enabled();
  399. };
  400. InfoIframe.prototype.close = function() {
  401. if (this.ifr) {
  402. this.ifr.close();
  403. }
  404. this.removeAllListeners();
  405. this.ifr = null;
  406. };
  407. module.exports = InfoIframe;
  408. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  409. },{"./info-iframe-receiver":10,"./transport/iframe":22,"./utils/event":46,"debug":55,"events":3,"inherits":57,"json3":58}],12:[function(require,module,exports){
  410. (function (process){
  411. 'use strict';
  412. var EventEmitter = require('events').EventEmitter
  413. , inherits = require('inherits')
  414. , urlUtils = require('./utils/url')
  415. , XDR = require('./transport/sender/xdr')
  416. , XHRCors = require('./transport/sender/xhr-cors')
  417. , XHRLocal = require('./transport/sender/xhr-local')
  418. , XHRFake = require('./transport/sender/xhr-fake')
  419. , InfoIframe = require('./info-iframe')
  420. , InfoAjax = require('./info-ajax')
  421. ;
  422. var debug = function() {};
  423. if (process.env.NODE_ENV !== 'production') {
  424. debug = require('debug')('sockjs-client:info-receiver');
  425. }
  426. function InfoReceiver(baseUrl, urlInfo) {
  427. debug(baseUrl);
  428. var self = this;
  429. EventEmitter.call(this);
  430. setTimeout(function() {
  431. self.doXhr(baseUrl, urlInfo);
  432. }, 0);
  433. }
  434. inherits(InfoReceiver, EventEmitter);
  435. // TODO this is currently ignoring the list of available transports and the whitelist
  436. InfoReceiver._getReceiver = function(baseUrl, url, urlInfo) {
  437. // determine method of CORS support (if needed)
  438. if (urlInfo.sameOrigin) {
  439. return new InfoAjax(url, XHRLocal);
  440. }
  441. if (XHRCors.enabled) {
  442. return new InfoAjax(url, XHRCors);
  443. }
  444. if (XDR.enabled && urlInfo.sameScheme) {
  445. return new InfoAjax(url, XDR);
  446. }
  447. if (InfoIframe.enabled()) {
  448. return new InfoIframe(baseUrl, url);
  449. }
  450. return new InfoAjax(url, XHRFake);
  451. };
  452. InfoReceiver.prototype.doXhr = function(baseUrl, urlInfo) {
  453. var self = this
  454. , url = urlUtils.addPath(baseUrl, '/info')
  455. ;
  456. debug('doXhr', url);
  457. this.xo = InfoReceiver._getReceiver(baseUrl, url, urlInfo);
  458. this.timeoutRef = setTimeout(function() {
  459. debug('timeout');
  460. self._cleanup(false);
  461. self.emit('finish');
  462. }, InfoReceiver.timeout);
  463. this.xo.once('finish', function(info, rtt) {
  464. debug('finish', info, rtt);
  465. self._cleanup(true);
  466. self.emit('finish', info, rtt);
  467. });
  468. };
  469. InfoReceiver.prototype._cleanup = function(wasClean) {
  470. debug('_cleanup');
  471. clearTimeout(this.timeoutRef);
  472. this.timeoutRef = null;
  473. if (!wasClean && this.xo) {
  474. this.xo.close();
  475. }
  476. this.xo = null;
  477. };
  478. InfoReceiver.prototype.close = function() {
  479. debug('close');
  480. this.removeAllListeners();
  481. this._cleanup(false);
  482. };
  483. InfoReceiver.timeout = 8000;
  484. module.exports = InfoReceiver;
  485. }).call(this,{ env: {} })
  486. },{"./info-ajax":9,"./info-iframe":11,"./transport/sender/xdr":34,"./transport/sender/xhr-cors":35,"./transport/sender/xhr-fake":36,"./transport/sender/xhr-local":37,"./utils/url":52,"debug":55,"events":3,"inherits":57}],13:[function(require,module,exports){
  487. (function (global){
  488. 'use strict';
  489. module.exports = global.location || {
  490. origin: 'http://localhost:80'
  491. , protocol: 'http:'
  492. , host: 'localhost'
  493. , port: 80
  494. , href: 'http://localhost/'
  495. , hash: ''
  496. };
  497. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  498. },{}],14:[function(require,module,exports){
  499. (function (process,global){
  500. 'use strict';
  501. require('./shims');
  502. var URL = require('url-parse')
  503. , inherits = require('inherits')
  504. , JSON3 = require('json3')
  505. , random = require('./utils/random')
  506. , escape = require('./utils/escape')
  507. , urlUtils = require('./utils/url')
  508. , eventUtils = require('./utils/event')
  509. , transport = require('./utils/transport')
  510. , objectUtils = require('./utils/object')
  511. , browser = require('./utils/browser')
  512. , log = require('./utils/log')
  513. , Event = require('./event/event')
  514. , EventTarget = require('./event/eventtarget')
  515. , loc = require('./location')
  516. , CloseEvent = require('./event/close')
  517. , TransportMessageEvent = require('./event/trans-message')
  518. , InfoReceiver = require('./info-receiver')
  519. ;
  520. var debug = function() {};
  521. if (process.env.NODE_ENV !== 'production') {
  522. debug = require('debug')('sockjs-client:main');
  523. }
  524. var transports;
  525. // follow constructor steps defined at http://dev.w3.org/html5/websockets/#the-websocket-interface
  526. function SockJS(url, protocols, options) {
  527. if (!(this instanceof SockJS)) {
  528. return new SockJS(url, protocols, options);
  529. }
  530. if (arguments.length < 1) {
  531. throw new TypeError("Failed to construct 'SockJS: 1 argument required, but only 0 present");
  532. }
  533. EventTarget.call(this);
  534. this.readyState = SockJS.CONNECTING;
  535. this.extensions = '';
  536. this.protocol = '';
  537. // non-standard extension
  538. options = options || {};
  539. if (options.protocols_whitelist) {
  540. log.warn("'protocols_whitelist' is DEPRECATED. Use 'transports' instead.");
  541. }
  542. this._transportsWhitelist = options.transports;
  543. this._transportOptions = options.transportOptions || {};
  544. var sessionId = options.sessionId || 8;
  545. if (typeof sessionId === 'function') {
  546. this._generateSessionId = sessionId;
  547. } else if (typeof sessionId === 'number') {
  548. this._generateSessionId = function() {
  549. return random.string(sessionId);
  550. };
  551. } else {
  552. throw new TypeError('If sessionId is used in the options, it needs to be a number or a function.');
  553. }
  554. this._server = options.server || random.numberString(1000);
  555. // Step 1 of WS spec - parse and validate the url. Issue #8
  556. var parsedUrl = new URL(url);
  557. if (!parsedUrl.host || !parsedUrl.protocol) {
  558. throw new SyntaxError("The URL '" + url + "' is invalid");
  559. } else if (parsedUrl.hash) {
  560. throw new SyntaxError('The URL must not contain a fragment');
  561. } else if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
  562. throw new SyntaxError("The URL's scheme must be either 'http:' or 'https:'. '" + parsedUrl.protocol + "' is not allowed.");
  563. }
  564. var secure = parsedUrl.protocol === 'https:';
  565. // Step 2 - don't allow secure origin with an insecure protocol
  566. if (loc.protocol === 'https:' && !secure) {
  567. throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS');
  568. }
  569. // Step 3 - check port access - no need here
  570. // Step 4 - parse protocols argument
  571. if (!protocols) {
  572. protocols = [];
  573. } else if (!Array.isArray(protocols)) {
  574. protocols = [protocols];
  575. }
  576. // Step 5 - check protocols argument
  577. var sortedProtocols = protocols.sort();
  578. sortedProtocols.forEach(function(proto, i) {
  579. if (!proto) {
  580. throw new SyntaxError("The protocols entry '" + proto + "' is invalid.");
  581. }
  582. if (i < (sortedProtocols.length - 1) && proto === sortedProtocols[i + 1]) {
  583. throw new SyntaxError("The protocols entry '" + proto + "' is duplicated.");
  584. }
  585. });
  586. // Step 6 - convert origin
  587. var o = urlUtils.getOrigin(loc.href);
  588. this._origin = o ? o.toLowerCase() : null;
  589. // remove the trailing slash
  590. parsedUrl.set('pathname', parsedUrl.pathname.replace(/\/+$/, ''));
  591. // store the sanitized url
  592. this.url = parsedUrl.href;
  593. debug('using url', this.url);
  594. // Step 7 - start connection in background
  595. // obtain server info
  596. // http://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-26
  597. this._urlInfo = {
  598. nullOrigin: !browser.hasDomain()
  599. , sameOrigin: urlUtils.isOriginEqual(this.url, loc.href)
  600. , sameScheme: urlUtils.isSchemeEqual(this.url, loc.href)
  601. };
  602. this._ir = new InfoReceiver(this.url, this._urlInfo);
  603. this._ir.once('finish', this._receiveInfo.bind(this));
  604. }
  605. inherits(SockJS, EventTarget);
  606. function userSetCode(code) {
  607. return code === 1000 || (code >= 3000 && code <= 4999);
  608. }
  609. SockJS.prototype.close = function(code, reason) {
  610. // Step 1
  611. if (code && !userSetCode(code)) {
  612. throw new Error('InvalidAccessError: Invalid code');
  613. }
  614. // Step 2.4 states the max is 123 bytes, but we are just checking length
  615. if (reason && reason.length > 123) {
  616. throw new SyntaxError('reason argument has an invalid length');
  617. }
  618. // Step 3.1
  619. if (this.readyState === SockJS.CLOSING || this.readyState === SockJS.CLOSED) {
  620. return;
  621. }
  622. // TODO look at docs to determine how to set this
  623. var wasClean = true;
  624. this._close(code || 1000, reason || 'Normal closure', wasClean);
  625. };
  626. SockJS.prototype.send = function(data) {
  627. // #13 - convert anything non-string to string
  628. // TODO this currently turns objects into [object Object]
  629. if (typeof data !== 'string') {
  630. data = '' + data;
  631. }
  632. if (this.readyState === SockJS.CONNECTING) {
  633. throw new Error('InvalidStateError: The connection has not been established yet');
  634. }
  635. if (this.readyState !== SockJS.OPEN) {
  636. return;
  637. }
  638. this._transport.send(escape.quote(data));
  639. };
  640. SockJS.version = require('./version');
  641. SockJS.CONNECTING = 0;
  642. SockJS.OPEN = 1;
  643. SockJS.CLOSING = 2;
  644. SockJS.CLOSED = 3;
  645. SockJS.prototype._receiveInfo = function(info, rtt) {
  646. debug('_receiveInfo', rtt);
  647. this._ir = null;
  648. if (!info) {
  649. this._close(1002, 'Cannot connect to server');
  650. return;
  651. }
  652. // establish a round-trip timeout (RTO) based on the
  653. // round-trip time (RTT)
  654. this._rto = this.countRTO(rtt);
  655. // allow server to override url used for the actual transport
  656. this._transUrl = info.base_url ? info.base_url : this.url;
  657. info = objectUtils.extend(info, this._urlInfo);
  658. debug('info', info);
  659. // determine list of desired and supported transports
  660. var enabledTransports = transports.filterToEnabled(this._transportsWhitelist, info);
  661. this._transports = enabledTransports.main;
  662. debug(this._transports.length + ' enabled transports');
  663. this._connect();
  664. };
  665. SockJS.prototype._connect = function() {
  666. for (var Transport = this._transports.shift(); Transport; Transport = this._transports.shift()) {
  667. debug('attempt', Transport.transportName);
  668. if (Transport.needBody) {
  669. if (!global.document.body ||
  670. (typeof global.document.readyState !== 'undefined' &&
  671. global.document.readyState !== 'complete' &&
  672. global.document.readyState !== 'interactive')) {
  673. debug('waiting for body');
  674. this._transports.unshift(Transport);
  675. eventUtils.attachEvent('load', this._connect.bind(this));
  676. return;
  677. }
  678. }
  679. // calculate timeout based on RTO and round trips. Default to 5s
  680. var timeoutMs = (this._rto * Transport.roundTrips) || 5000;
  681. this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs);
  682. debug('using timeout', timeoutMs);
  683. var transportUrl = urlUtils.addPath(this._transUrl, '/' + this._server + '/' + this._generateSessionId());
  684. var options = this._transportOptions[Transport.transportName];
  685. debug('transport url', transportUrl);
  686. var transportObj = new Transport(transportUrl, this._transUrl, options);
  687. transportObj.on('message', this._transportMessage.bind(this));
  688. transportObj.once('close', this._transportClose.bind(this));
  689. transportObj.transportName = Transport.transportName;
  690. this._transport = transportObj;
  691. return;
  692. }
  693. this._close(2000, 'All transports failed', false);
  694. };
  695. SockJS.prototype._transportTimeout = function() {
  696. debug('_transportTimeout');
  697. if (this.readyState === SockJS.CONNECTING) {
  698. if (this._transport) {
  699. this._transport.close();
  700. }
  701. this._transportClose(2007, 'Transport timed out');
  702. }
  703. };
  704. SockJS.prototype._transportMessage = function(msg) {
  705. debug('_transportMessage', msg);
  706. var self = this
  707. , type = msg.slice(0, 1)
  708. , content = msg.slice(1)
  709. , payload
  710. ;
  711. // first check for messages that don't need a payload
  712. switch (type) {
  713. case 'o':
  714. this._open();
  715. return;
  716. case 'h':
  717. this.dispatchEvent(new Event('heartbeat'));
  718. debug('heartbeat', this.transport);
  719. return;
  720. }
  721. if (content) {
  722. try {
  723. payload = JSON3.parse(content);
  724. } catch (e) {
  725. debug('bad json', content);
  726. }
  727. }
  728. if (typeof payload === 'undefined') {
  729. debug('empty payload', content);
  730. return;
  731. }
  732. switch (type) {
  733. case 'a':
  734. if (Array.isArray(payload)) {
  735. payload.forEach(function(p) {
  736. debug('message', self.transport, p);
  737. self.dispatchEvent(new TransportMessageEvent(p));
  738. });
  739. }
  740. break;
  741. case 'm':
  742. debug('message', this.transport, payload);
  743. this.dispatchEvent(new TransportMessageEvent(payload));
  744. break;
  745. case 'c':
  746. if (Array.isArray(payload) && payload.length === 2) {
  747. this._close(payload[0], payload[1], true);
  748. }
  749. break;
  750. }
  751. };
  752. SockJS.prototype._transportClose = function(code, reason) {
  753. debug('_transportClose', this.transport, code, reason);
  754. if (this._transport) {
  755. this._transport.removeAllListeners();
  756. this._transport = null;
  757. this.transport = null;
  758. }
  759. if (!userSetCode(code) && code !== 2000 && this.readyState === SockJS.CONNECTING) {
  760. this._connect();
  761. return;
  762. }
  763. this._close(code, reason);
  764. };
  765. SockJS.prototype._open = function() {
  766. debug('_open', this._transport.transportName, this.readyState);
  767. if (this.readyState === SockJS.CONNECTING) {
  768. if (this._transportTimeoutId) {
  769. clearTimeout(this._transportTimeoutId);
  770. this._transportTimeoutId = null;
  771. }
  772. this.readyState = SockJS.OPEN;
  773. this.transport = this._transport.transportName;
  774. this.dispatchEvent(new Event('open'));
  775. debug('connected', this.transport);
  776. } else {
  777. // The server might have been restarted, and lost track of our
  778. // connection.
  779. this._close(1006, 'Server lost session');
  780. }
  781. };
  782. SockJS.prototype._close = function(code, reason, wasClean) {
  783. debug('_close', this.transport, code, reason, wasClean, this.readyState);
  784. var forceFail = false;
  785. if (this._ir) {
  786. forceFail = true;
  787. this._ir.close();
  788. this._ir = null;
  789. }
  790. if (this._transport) {
  791. this._transport.close();
  792. this._transport = null;
  793. this.transport = null;
  794. }
  795. if (this.readyState === SockJS.CLOSED) {
  796. throw new Error('InvalidStateError: SockJS has already been closed');
  797. }
  798. this.readyState = SockJS.CLOSING;
  799. setTimeout(function() {
  800. this.readyState = SockJS.CLOSED;
  801. if (forceFail) {
  802. this.dispatchEvent(new Event('error'));
  803. }
  804. var e = new CloseEvent('close');
  805. e.wasClean = wasClean || false;
  806. e.code = code || 1000;
  807. e.reason = reason;
  808. this.dispatchEvent(e);
  809. this.onmessage = this.onclose = this.onerror = null;
  810. debug('disconnected');
  811. }.bind(this), 0);
  812. };
  813. // See: http://www.erg.abdn.ac.uk/~gerrit/dccp/notes/ccid2/rto_estimator/
  814. // and RFC 2988.
  815. SockJS.prototype.countRTO = function(rtt) {
  816. // In a local environment, when using IE8/9 and the `jsonp-polling`
  817. // transport the time needed to establish a connection (the time that pass
  818. // from the opening of the transport to the call of `_dispatchOpen`) is
  819. // around 200msec (the lower bound used in the article above) and this
  820. // causes spurious timeouts. For this reason we calculate a value slightly
  821. // larger than that used in the article.
  822. if (rtt > 100) {
  823. return 4 * rtt; // rto > 400msec
  824. }
  825. return 300 + rtt; // 300msec < rto <= 400msec
  826. };
  827. module.exports = function(availableTransports) {
  828. transports = transport(availableTransports);
  829. require('./iframe-bootstrap')(SockJS, availableTransports);
  830. return SockJS;
  831. };
  832. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  833. },{"./event/close":2,"./event/event":4,"./event/eventtarget":5,"./event/trans-message":6,"./iframe-bootstrap":8,"./info-receiver":12,"./location":13,"./shims":15,"./utils/browser":44,"./utils/escape":45,"./utils/event":46,"./utils/log":48,"./utils/object":49,"./utils/random":50,"./utils/transport":51,"./utils/url":52,"./version":53,"debug":55,"inherits":57,"json3":58,"url-parse":61}],15:[function(require,module,exports){
  834. /* eslint-disable */
  835. /* jscs: disable */
  836. 'use strict';
  837. // pulled specific shims from https://github.com/es-shims/es5-shim
  838. var ArrayPrototype = Array.prototype;
  839. var ObjectPrototype = Object.prototype;
  840. var FunctionPrototype = Function.prototype;
  841. var StringPrototype = String.prototype;
  842. var array_slice = ArrayPrototype.slice;
  843. var _toString = ObjectPrototype.toString;
  844. var isFunction = function (val) {
  845. return ObjectPrototype.toString.call(val) === '[object Function]';
  846. };
  847. var isArray = function isArray(obj) {
  848. return _toString.call(obj) === '[object Array]';
  849. };
  850. var isString = function isString(obj) {
  851. return _toString.call(obj) === '[object String]';
  852. };
  853. var supportsDescriptors = Object.defineProperty && (function () {
  854. try {
  855. Object.defineProperty({}, 'x', {});
  856. return true;
  857. } catch (e) { /* this is ES3 */
  858. return false;
  859. }
  860. }());
  861. // Define configurable, writable and non-enumerable props
  862. // if they don't exist.
  863. var defineProperty;
  864. if (supportsDescriptors) {
  865. defineProperty = function (object, name, method, forceAssign) {
  866. if (!forceAssign && (name in object)) { return; }
  867. Object.defineProperty(object, name, {
  868. configurable: true,
  869. enumerable: false,
  870. writable: true,
  871. value: method
  872. });
  873. };
  874. } else {
  875. defineProperty = function (object, name, method, forceAssign) {
  876. if (!forceAssign && (name in object)) { return; }
  877. object[name] = method;
  878. };
  879. }
  880. var defineProperties = function (object, map, forceAssign) {
  881. for (var name in map) {
  882. if (ObjectPrototype.hasOwnProperty.call(map, name)) {
  883. defineProperty(object, name, map[name], forceAssign);
  884. }
  885. }
  886. };
  887. var toObject = function (o) {
  888. if (o == null) { // this matches both null and undefined
  889. throw new TypeError("can't convert " + o + ' to object');
  890. }
  891. return Object(o);
  892. };
  893. //
  894. // Util
  895. // ======
  896. //
  897. // ES5 9.4
  898. // http://es5.github.com/#x9.4
  899. // http://jsperf.com/to-integer
  900. function toInteger(num) {
  901. var n = +num;
  902. if (n !== n) { // isNaN
  903. n = 0;
  904. } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  905. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  906. }
  907. return n;
  908. }
  909. function ToUint32(x) {
  910. return x >>> 0;
  911. }
  912. //
  913. // Function
  914. // ========
  915. //
  916. // ES-5 15.3.4.5
  917. // http://es5.github.com/#x15.3.4.5
  918. function Empty() {}
  919. defineProperties(FunctionPrototype, {
  920. bind: function bind(that) { // .length is 1
  921. // 1. Let Target be the this value.
  922. var target = this;
  923. // 2. If IsCallable(Target) is false, throw a TypeError exception.
  924. if (!isFunction(target)) {
  925. throw new TypeError('Function.prototype.bind called on incompatible ' + target);
  926. }
  927. // 3. Let A be a new (possibly empty) internal list of all of the
  928. // argument values provided after thisArg (arg1, arg2 etc), in order.
  929. // XXX slicedArgs will stand in for "A" if used
  930. var args = array_slice.call(arguments, 1); // for normal call
  931. // 4. Let F be a new native ECMAScript object.
  932. // 11. Set the [[Prototype]] internal property of F to the standard
  933. // built-in Function prototype object as specified in 15.3.3.1.
  934. // 12. Set the [[Call]] internal property of F as described in
  935. // 15.3.4.5.1.
  936. // 13. Set the [[Construct]] internal property of F as described in
  937. // 15.3.4.5.2.
  938. // 14. Set the [[HasInstance]] internal property of F as described in
  939. // 15.3.4.5.3.
  940. var binder = function () {
  941. if (this instanceof bound) {
  942. // 15.3.4.5.2 [[Construct]]
  943. // When the [[Construct]] internal method of a function object,
  944. // F that was created using the bind function is called with a
  945. // list of arguments ExtraArgs, the following steps are taken:
  946. // 1. Let target be the value of F's [[TargetFunction]]
  947. // internal property.
  948. // 2. If target has no [[Construct]] internal method, a
  949. // TypeError exception is thrown.
  950. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal
  951. // property.
  952. // 4. Let args be a new list containing the same values as the
  953. // list boundArgs in the same order followed by the same
  954. // values as the list ExtraArgs in the same order.
  955. // 5. Return the result of calling the [[Construct]] internal
  956. // method of target providing args as the arguments.
  957. var result = target.apply(
  958. this,
  959. args.concat(array_slice.call(arguments))
  960. );
  961. if (Object(result) === result) {
  962. return result;
  963. }
  964. return this;
  965. } else {
  966. // 15.3.4.5.1 [[Call]]
  967. // When the [[Call]] internal method of a function object, F,
  968. // which was created using the bind function is called with a
  969. // this value and a list of arguments ExtraArgs, the following
  970. // steps are taken:
  971. // 1. Let boundArgs be the value of F's [[BoundArgs]] internal
  972. // property.
  973. // 2. Let boundThis be the value of F's [[BoundThis]] internal
  974. // property.
  975. // 3. Let target be the value of F's [[TargetFunction]] internal
  976. // property.
  977. // 4. Let args be a new list containing the same values as the
  978. // list boundArgs in the same order followed by the same
  979. // values as the list ExtraArgs in the same order.
  980. // 5. Return the result of calling the [[Call]] internal method
  981. // of target providing boundThis as the this value and
  982. // providing args as the arguments.
  983. // equiv: target.call(this, ...boundArgs, ...args)
  984. return target.apply(
  985. that,
  986. args.concat(array_slice.call(arguments))
  987. );
  988. }
  989. };
  990. // 15. If the [[Class]] internal property of Target is "Function", then
  991. // a. Let L be the length property of Target minus the length of A.
  992. // b. Set the length own property of F to either 0 or L, whichever is
  993. // larger.
  994. // 16. Else set the length own property of F to 0.
  995. var boundLength = Math.max(0, target.length - args.length);
  996. // 17. Set the attributes of the length own property of F to the values
  997. // specified in 15.3.5.1.
  998. var boundArgs = [];
  999. for (var i = 0; i < boundLength; i++) {
  1000. boundArgs.push('$' + i);
  1001. }
  1002. // XXX Build a dynamic function with desired amount of arguments is the only
  1003. // way to set the length property of a function.
  1004. // In environments where Content Security Policies enabled (Chrome extensions,
  1005. // for ex.) all use of eval or Function costructor throws an exception.
  1006. // However in all of these environments Function.prototype.bind exists
  1007. // and so this code will never be executed.
  1008. var bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this, arguments); }')(binder);
  1009. if (target.prototype) {
  1010. Empty.prototype = target.prototype;
  1011. bound.prototype = new Empty();
  1012. // Clean up dangling references.
  1013. Empty.prototype = null;
  1014. }
  1015. // TODO
  1016. // 18. Set the [[Extensible]] internal property of F to true.
  1017. // TODO
  1018. // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
  1019. // 20. Call the [[DefineOwnProperty]] internal method of F with
  1020. // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
  1021. // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
  1022. // false.
  1023. // 21. Call the [[DefineOwnProperty]] internal method of F with
  1024. // arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
  1025. // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
  1026. // and false.
  1027. // TODO
  1028. // NOTE Function objects created using Function.prototype.bind do not
  1029. // have a prototype property or the [[Code]], [[FormalParameters]], and
  1030. // [[Scope]] internal properties.
  1031. // XXX can't delete prototype in pure-js.
  1032. // 22. Return F.
  1033. return bound;
  1034. }
  1035. });
  1036. //
  1037. // Array
  1038. // =====
  1039. //
  1040. // ES5 15.4.3.2
  1041. // http://es5.github.com/#x15.4.3.2
  1042. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
  1043. defineProperties(Array, { isArray: isArray });
  1044. var boxedString = Object('a');
  1045. var splitString = boxedString[0] !== 'a' || !(0 in boxedString);
  1046. var properlyBoxesContext = function properlyBoxed(method) {
  1047. // Check node 0.6.21 bug where third parameter is not boxed
  1048. var properlyBoxesNonStrict = true;
  1049. var properlyBoxesStrict = true;
  1050. if (method) {
  1051. method.call('foo', function (_, __, context) {
  1052. if (typeof context !== 'object') { properlyBoxesNonStrict = false; }
  1053. });
  1054. method.call([1], function () {
  1055. 'use strict';
  1056. properlyBoxesStrict = typeof this === 'string';
  1057. }, 'x');
  1058. }
  1059. return !!method && properlyBoxesNonStrict && properlyBoxesStrict;
  1060. };
  1061. defineProperties(ArrayPrototype, {
  1062. forEach: function forEach(fun /*, thisp*/) {
  1063. var object = toObject(this),
  1064. self = splitString && isString(this) ? this.split('') : object,
  1065. thisp = arguments[1],
  1066. i = -1,
  1067. length = self.length >>> 0;
  1068. // If no callback function or if callback is not a callable function
  1069. if (!isFunction(fun)) {
  1070. throw new TypeError(); // TODO message
  1071. }
  1072. while (++i < length) {
  1073. if (i in self) {
  1074. // Invoke the callback function with call, passing arguments:
  1075. // context, property value, property key, thisArg object
  1076. // context
  1077. fun.call(thisp, self[i], i, object);
  1078. }
  1079. }
  1080. }
  1081. }, !properlyBoxesContext(ArrayPrototype.forEach));
  1082. // ES5 15.4.4.14
  1083. // http://es5.github.com/#x15.4.4.14
  1084. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
  1085. var hasFirefox2IndexOfBug = Array.prototype.indexOf && [0, 1].indexOf(1, 2) !== -1;
  1086. defineProperties(ArrayPrototype, {
  1087. indexOf: function indexOf(sought /*, fromIndex */ ) {
  1088. var self = splitString && isString(this) ? this.split('') : toObject(this),
  1089. length = self.length >>> 0;
  1090. if (!length) {
  1091. return -1;
  1092. }
  1093. var i = 0;
  1094. if (arguments.length > 1) {
  1095. i = toInteger(arguments[1]);
  1096. }
  1097. // handle negative indices
  1098. i = i >= 0 ? i : Math.max(0, length + i);
  1099. for (; i < length; i++) {
  1100. if (i in self && self[i] === sought) {
  1101. return i;
  1102. }
  1103. }
  1104. return -1;
  1105. }
  1106. }, hasFirefox2IndexOfBug);
  1107. //
  1108. // String
  1109. // ======
  1110. //
  1111. // ES5 15.5.4.14
  1112. // http://es5.github.com/#x15.5.4.14
  1113. // [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers]
  1114. // Many browsers do not split properly with regular expressions or they
  1115. // do not perform the split correctly under obscure conditions.
  1116. // See http://blog.stevenlevithan.com/archives/cross-browser-split
  1117. // I've tested in many browsers and this seems to cover the deviant ones:
  1118. // 'ab'.split(/(?:ab)*/) should be ["", ""], not [""]
  1119. // '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""]
  1120. // 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not
  1121. // [undefined, "t", undefined, "e", ...]
  1122. // ''.split(/.?/) should be [], not [""]
  1123. // '.'.split(/()()/) should be ["."], not ["", "", "."]
  1124. var string_split = StringPrototype.split;
  1125. if (
  1126. 'ab'.split(/(?:ab)*/).length !== 2 ||
  1127. '.'.split(/(.?)(.?)/).length !== 4 ||
  1128. 'tesst'.split(/(s)*/)[1] === 't' ||
  1129. 'test'.split(/(?:)/, -1).length !== 4 ||
  1130. ''.split(/.?/).length ||
  1131. '.'.split(/()()/).length > 1
  1132. ) {
  1133. (function () {
  1134. var compliantExecNpcg = /()??/.exec('')[1] === void 0; // NPCG: nonparticipating capturing group
  1135. StringPrototype.split = function (separator, limit) {
  1136. var string = this;
  1137. if (separator === void 0 && limit === 0) {
  1138. return [];
  1139. }
  1140. // If `separator` is not a regex, use native split
  1141. if (_toString.call(separator) !== '[object RegExp]') {
  1142. return string_split.call(this, separator, limit);
  1143. }
  1144. var output = [],
  1145. flags = (separator.ignoreCase ? 'i' : '') +
  1146. (separator.multiline ? 'm' : '') +
  1147. (separator.extended ? 'x' : '') + // Proposed for ES6
  1148. (separator.sticky ? 'y' : ''), // Firefox 3+
  1149. lastLastIndex = 0,
  1150. // Make `global` and avoid `lastIndex` issues by working with a copy
  1151. separator2, match, lastIndex, lastLength;
  1152. separator = new RegExp(separator.source, flags + 'g');
  1153. string += ''; // Type-convert
  1154. if (!compliantExecNpcg) {
  1155. // Doesn't need flags gy, but they don't hurt
  1156. separator2 = new RegExp('^' + separator.source + '$(?!\\s)', flags);
  1157. }
  1158. /* Values for `limit`, per the spec:
  1159. * If undefined: 4294967295 // Math.pow(2, 32) - 1
  1160. * If 0, Infinity, or NaN: 0
  1161. * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
  1162. * If negative number: 4294967296 - Math.floor(Math.abs(limit))
  1163. * If other: Type-convert, then use the above rules
  1164. */
  1165. limit = limit === void 0 ?
  1166. -1 >>> 0 : // Math.pow(2, 32) - 1
  1167. ToUint32(limit);
  1168. while (match = separator.exec(string)) {
  1169. // `separator.lastIndex` is not reliable cross-browser
  1170. lastIndex = match.index + match[0].length;
  1171. if (lastIndex > lastLastIndex) {
  1172. output.push(string.slice(lastLastIndex, match.index));
  1173. // Fix browsers whose `exec` methods don't consistently return `undefined` for
  1174. // nonparticipating capturing groups
  1175. if (!compliantExecNpcg && match.length > 1) {
  1176. match[0].replace(separator2, function () {
  1177. for (var i = 1; i < arguments.length - 2; i++) {
  1178. if (arguments[i] === void 0) {
  1179. match[i] = void 0;
  1180. }
  1181. }
  1182. });
  1183. }
  1184. if (match.length > 1 && match.index < string.length) {
  1185. ArrayPrototype.push.apply(output, match.slice(1));
  1186. }
  1187. lastLength = match[0].length;
  1188. lastLastIndex = lastIndex;
  1189. if (output.length >= limit) {
  1190. break;
  1191. }
  1192. }
  1193. if (separator.lastIndex === match.index) {
  1194. separator.lastIndex++; // Avoid an infinite loop
  1195. }
  1196. }
  1197. if (lastLastIndex === string.length) {
  1198. if (lastLength || !separator.test('')) {
  1199. output.push('');
  1200. }
  1201. } else {
  1202. output.push(string.slice(lastLastIndex));
  1203. }
  1204. return output.length > limit ? output.slice(0, limit) : output;
  1205. };
  1206. }());
  1207. // [bugfix, chrome]
  1208. // If separator is undefined, then the result array contains just one String,
  1209. // which is the this value (converted to a String). If limit is not undefined,
  1210. // then the output array is truncated so that it contains no more than limit
  1211. // elements.
  1212. // "0".split(undefined, 0) -> []
  1213. } else if ('0'.split(void 0, 0).length) {
  1214. StringPrototype.split = function split(separator, limit) {
  1215. if (separator === void 0 && limit === 0) { return []; }
  1216. return string_split.call(this, separator, limit);
  1217. };
  1218. }
  1219. // ECMA-262, 3rd B.2.3
  1220. // Not an ECMAScript standard, although ECMAScript 3rd Edition has a
  1221. // non-normative section suggesting uniform semantics and it should be
  1222. // normalized across all browsers
  1223. // [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE
  1224. var string_substr = StringPrototype.substr;
  1225. var hasNegativeSubstrBug = ''.substr && '0b'.substr(-1) !== 'b';
  1226. defineProperties(StringPrototype, {
  1227. substr: function substr(start, length) {
  1228. return string_substr.call(
  1229. this,
  1230. start < 0 ? ((start = this.length + start) < 0 ? 0 : start) : start,
  1231. length
  1232. );
  1233. }
  1234. }, hasNegativeSubstrBug);
  1235. },{}],16:[function(require,module,exports){
  1236. 'use strict';
  1237. module.exports = [
  1238. // streaming transports
  1239. require('./transport/websocket')
  1240. , require('./transport/xhr-streaming')
  1241. , require('./transport/xdr-streaming')
  1242. , require('./transport/eventsource')
  1243. , require('./transport/lib/iframe-wrap')(require('./transport/eventsource'))
  1244. // polling transports
  1245. , require('./transport/htmlfile')
  1246. , require('./transport/lib/iframe-wrap')(require('./transport/htmlfile'))
  1247. , require('./transport/xhr-polling')
  1248. , require('./transport/xdr-polling')
  1249. , require('./transport/lib/iframe-wrap')(require('./transport/xhr-polling'))
  1250. , require('./transport/jsonp-polling')
  1251. ];
  1252. },{"./transport/eventsource":20,"./transport/htmlfile":21,"./transport/jsonp-polling":23,"./transport/lib/iframe-wrap":26,"./transport/websocket":38,"./transport/xdr-polling":39,"./transport/xdr-streaming":40,"./transport/xhr-polling":41,"./transport/xhr-streaming":42}],17:[function(require,module,exports){
  1253. (function (process,global){
  1254. 'use strict';
  1255. var EventEmitter = require('events').EventEmitter
  1256. , inherits = require('inherits')
  1257. , utils = require('../../utils/event')
  1258. , urlUtils = require('../../utils/url')
  1259. , XHR = global.XMLHttpRequest
  1260. ;
  1261. var debug = function() {};
  1262. if (process.env.NODE_ENV !== 'production') {
  1263. debug = require('debug')('sockjs-client:browser:xhr');
  1264. }
  1265. function AbstractXHRObject(method, url, payload, opts) {
  1266. debug(method, url);
  1267. var self = this;
  1268. EventEmitter.call(this);
  1269. setTimeout(function () {
  1270. self._start(method, url, payload, opts);
  1271. }, 0);
  1272. }
  1273. inherits(AbstractXHRObject, EventEmitter);
  1274. AbstractXHRObject.prototype._start = function(method, url, payload, opts) {
  1275. var self = this;
  1276. try {
  1277. this.xhr = new XHR();
  1278. } catch (x) {
  1279. // intentionally empty
  1280. }
  1281. if (!this.xhr) {
  1282. debug('no xhr');
  1283. this.emit('finish', 0, 'no xhr support');
  1284. this._cleanup();
  1285. return;
  1286. }
  1287. // several browsers cache POSTs
  1288. url = urlUtils.addQuery(url, 't=' + (+new Date()));
  1289. // Explorer tends to keep connection open, even after the
  1290. // tab gets closed: http://bugs.jquery.com/ticket/5280
  1291. this.unloadRef = utils.unloadAdd(function() {
  1292. debug('unload cleanup');
  1293. self._cleanup(true);
  1294. });
  1295. try {
  1296. this.xhr.open(method, url, true);
  1297. if (this.timeout && 'timeout' in this.xhr) {
  1298. this.xhr.timeout = this.timeout;
  1299. this.xhr.ontimeout = function() {
  1300. debug('xhr timeout');
  1301. self.emit('finish', 0, '');
  1302. self._cleanup(false);
  1303. };
  1304. }
  1305. } catch (e) {
  1306. debug('exception', e);
  1307. // IE raises an exception on wrong port.
  1308. this.emit('finish', 0, '');
  1309. this._cleanup(false);
  1310. return;
  1311. }
  1312. if ((!opts || !opts.noCredentials) && AbstractXHRObject.supportsCORS) {
  1313. debug('withCredentials');
  1314. // Mozilla docs says https://developer.mozilla.org/en/XMLHttpRequest :
  1315. // "This never affects same-site requests."
  1316. this.xhr.withCredentials = true;
  1317. }
  1318. if (opts && opts.headers) {
  1319. for (var key in opts.headers) {
  1320. this.xhr.setRequestHeader(key, opts.headers[key]);
  1321. }
  1322. }
  1323. this.xhr.onreadystatechange = function() {
  1324. if (self.xhr) {
  1325. var x = self.xhr;
  1326. var text, status;
  1327. debug('readyState', x.readyState);
  1328. switch (x.readyState) {
  1329. case 3:
  1330. // IE doesn't like peeking into responseText or status
  1331. // on Microsoft.XMLHTTP and readystate=3
  1332. try {
  1333. status = x.status;
  1334. text = x.responseText;
  1335. } catch (e) {
  1336. // intentionally empty
  1337. }
  1338. debug('status', status);
  1339. // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450
  1340. if (status === 1223) {
  1341. status = 204;
  1342. }
  1343. // IE does return readystate == 3 for 404 answers.
  1344. if (status === 200 && text && text.length > 0) {
  1345. debug('chunk');
  1346. self.emit('chunk', status, text);
  1347. }
  1348. break;
  1349. case 4:
  1350. status = x.status;
  1351. debug('status', status);
  1352. // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450
  1353. if (status === 1223) {
  1354. status = 204;
  1355. }
  1356. // IE returns this for a bad port
  1357. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa383770(v=vs.85).aspx
  1358. if (status === 12005 || status === 12029) {
  1359. status = 0;
  1360. }
  1361. debug('finish', status, x.responseText);
  1362. self.emit('finish', status, x.responseText);
  1363. self._cleanup(false);
  1364. break;
  1365. }
  1366. }
  1367. };
  1368. try {
  1369. self.xhr.send(payload);
  1370. } catch (e) {
  1371. self.emit('finish', 0, '');
  1372. self._cleanup(false);
  1373. }
  1374. };
  1375. AbstractXHRObject.prototype._cleanup = function(abort) {
  1376. debug('cleanup');
  1377. if (!this.xhr) {
  1378. return;
  1379. }
  1380. this.removeAllListeners();
  1381. utils.unloadDel(this.unloadRef);
  1382. // IE needs this field to be a function
  1383. this.xhr.onreadystatechange = function() {};
  1384. if (this.xhr.ontimeout) {
  1385. this.xhr.ontimeout = null;
  1386. }
  1387. if (abort) {
  1388. try {
  1389. this.xhr.abort();
  1390. } catch (x) {
  1391. // intentionally empty
  1392. }
  1393. }
  1394. this.unloadRef = this.xhr = null;
  1395. };
  1396. AbstractXHRObject.prototype.close = function() {
  1397. debug('close');
  1398. this._cleanup(true);
  1399. };
  1400. AbstractXHRObject.enabled = !!XHR;
  1401. // override XMLHttpRequest for IE6/7
  1402. // obfuscate to avoid firewalls
  1403. var axo = ['Active'].concat('Object').join('X');
  1404. if (!AbstractXHRObject.enabled && (axo in global)) {
  1405. debug('overriding xmlhttprequest');
  1406. XHR = function() {
  1407. try {
  1408. return new global[axo]('Microsoft.XMLHTTP');
  1409. } catch (e) {
  1410. return null;
  1411. }
  1412. };
  1413. AbstractXHRObject.enabled = !!new XHR();
  1414. }
  1415. var cors = false;
  1416. try {
  1417. cors = 'withCredentials' in new XHR();
  1418. } catch (ignored) {
  1419. // intentionally empty
  1420. }
  1421. AbstractXHRObject.supportsCORS = cors;
  1422. module.exports = AbstractXHRObject;
  1423. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1424. },{"../../utils/event":46,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],18:[function(require,module,exports){
  1425. (function (global){
  1426. module.exports = global.EventSource;
  1427. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1428. },{}],19:[function(require,module,exports){
  1429. (function (global){
  1430. 'use strict';
  1431. var Driver = global.WebSocket || global.MozWebSocket;
  1432. if (Driver) {
  1433. module.exports = function WebSocketBrowserDriver(url) {
  1434. return new Driver(url);
  1435. };
  1436. } else {
  1437. module.exports = undefined;
  1438. }
  1439. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1440. },{}],20:[function(require,module,exports){
  1441. 'use strict';
  1442. var inherits = require('inherits')
  1443. , AjaxBasedTransport = require('./lib/ajax-based')
  1444. , EventSourceReceiver = require('./receiver/eventsource')
  1445. , XHRCorsObject = require('./sender/xhr-cors')
  1446. , EventSourceDriver = require('eventsource')
  1447. ;
  1448. function EventSourceTransport(transUrl) {
  1449. if (!EventSourceTransport.enabled()) {
  1450. throw new Error('Transport created when disabled');
  1451. }
  1452. AjaxBasedTransport.call(this, transUrl, '/eventsource', EventSourceReceiver, XHRCorsObject);
  1453. }
  1454. inherits(EventSourceTransport, AjaxBasedTransport);
  1455. EventSourceTransport.enabled = function() {
  1456. return !!EventSourceDriver;
  1457. };
  1458. EventSourceTransport.transportName = 'eventsource';
  1459. EventSourceTransport.roundTrips = 2;
  1460. module.exports = EventSourceTransport;
  1461. },{"./lib/ajax-based":24,"./receiver/eventsource":29,"./sender/xhr-cors":35,"eventsource":18,"inherits":57}],21:[function(require,module,exports){
  1462. 'use strict';
  1463. var inherits = require('inherits')
  1464. , HtmlfileReceiver = require('./receiver/htmlfile')
  1465. , XHRLocalObject = require('./sender/xhr-local')
  1466. , AjaxBasedTransport = require('./lib/ajax-based')
  1467. ;
  1468. function HtmlFileTransport(transUrl) {
  1469. if (!HtmlfileReceiver.enabled) {
  1470. throw new Error('Transport created when disabled');
  1471. }
  1472. AjaxBasedTransport.call(this, transUrl, '/htmlfile', HtmlfileReceiver, XHRLocalObject);
  1473. }
  1474. inherits(HtmlFileTransport, AjaxBasedTransport);
  1475. HtmlFileTransport.enabled = function(info) {
  1476. return HtmlfileReceiver.enabled && info.sameOrigin;
  1477. };
  1478. HtmlFileTransport.transportName = 'htmlfile';
  1479. HtmlFileTransport.roundTrips = 2;
  1480. module.exports = HtmlFileTransport;
  1481. },{"./lib/ajax-based":24,"./receiver/htmlfile":30,"./sender/xhr-local":37,"inherits":57}],22:[function(require,module,exports){
  1482. (function (process){
  1483. 'use strict';
  1484. // Few cool transports do work only for same-origin. In order to make
  1485. // them work cross-domain we shall use iframe, served from the
  1486. // remote domain. New browsers have capabilities to communicate with
  1487. // cross domain iframe using postMessage(). In IE it was implemented
  1488. // from IE 8+, but of course, IE got some details wrong:
  1489. // http://msdn.microsoft.com/en-us/library/cc197015(v=VS.85).aspx
  1490. // http://stevesouders.com/misc/test-postmessage.php
  1491. var inherits = require('inherits')
  1492. , JSON3 = require('json3')
  1493. , EventEmitter = require('events').EventEmitter
  1494. , version = require('../version')
  1495. , urlUtils = require('../utils/url')
  1496. , iframeUtils = require('../utils/iframe')
  1497. , eventUtils = require('../utils/event')
  1498. , random = require('../utils/random')
  1499. ;
  1500. var debug = function() {};
  1501. if (process.env.NODE_ENV !== 'production') {
  1502. debug = require('debug')('sockjs-client:transport:iframe');
  1503. }
  1504. function IframeTransport(transport, transUrl, baseUrl) {
  1505. if (!IframeTransport.enabled()) {
  1506. throw new Error('Transport created when disabled');
  1507. }
  1508. EventEmitter.call(this);
  1509. var self = this;
  1510. this.origin = urlUtils.getOrigin(baseUrl);
  1511. this.baseUrl = baseUrl;
  1512. this.transUrl = transUrl;
  1513. this.transport = transport;
  1514. this.windowId = random.string(8);
  1515. var iframeUrl = urlUtils.addPath(baseUrl, '/iframe.html') + '#' + this.windowId;
  1516. debug(transport, transUrl, iframeUrl);
  1517. this.iframeObj = iframeUtils.createIframe(iframeUrl, function(r) {
  1518. debug('err callback');
  1519. self.emit('close', 1006, 'Unable to load an iframe (' + r + ')');
  1520. self.close();
  1521. });
  1522. this.onmessageCallback = this._message.bind(this);
  1523. eventUtils.attachEvent('message', this.onmessageCallback);
  1524. }
  1525. inherits(IframeTransport, EventEmitter);
  1526. IframeTransport.prototype.close = function() {
  1527. debug('close');
  1528. this.removeAllListeners();
  1529. if (this.iframeObj) {
  1530. eventUtils.detachEvent('message', this.onmessageCallback);
  1531. try {
  1532. // When the iframe is not loaded, IE raises an exception
  1533. // on 'contentWindow'.
  1534. this.postMessage('c');
  1535. } catch (x) {
  1536. // intentionally empty
  1537. }
  1538. this.iframeObj.cleanup();
  1539. this.iframeObj = null;
  1540. this.onmessageCallback = this.iframeObj = null;
  1541. }
  1542. };
  1543. IframeTransport.prototype._message = function(e) {
  1544. debug('message', e.data);
  1545. if (!urlUtils.isOriginEqual(e.origin, this.origin)) {
  1546. debug('not same origin', e.origin, this.origin);
  1547. return;
  1548. }
  1549. var iframeMessage;
  1550. try {
  1551. iframeMessage = JSON3.parse(e.data);
  1552. } catch (ignored) {
  1553. debug('bad json', e.data);
  1554. return;
  1555. }
  1556. if (iframeMessage.windowId !== this.windowId) {
  1557. debug('mismatched window id', iframeMessage.windowId, this.windowId);
  1558. return;
  1559. }
  1560. switch (iframeMessage.type) {
  1561. case 's':
  1562. this.iframeObj.loaded();
  1563. // window global dependency
  1564. this.postMessage('s', JSON3.stringify([
  1565. version
  1566. , this.transport
  1567. , this.transUrl
  1568. , this.baseUrl
  1569. ]));
  1570. break;
  1571. case 't':
  1572. this.emit('message', iframeMessage.data);
  1573. break;
  1574. case 'c':
  1575. var cdata;
  1576. try {
  1577. cdata = JSON3.parse(iframeMessage.data);
  1578. } catch (ignored) {
  1579. debug('bad json', iframeMessage.data);
  1580. return;
  1581. }
  1582. this.emit('close', cdata[0], cdata[1]);
  1583. this.close();
  1584. break;
  1585. }
  1586. };
  1587. IframeTransport.prototype.postMessage = function(type, data) {
  1588. debug('postMessage', type, data);
  1589. this.iframeObj.post(JSON3.stringify({
  1590. windowId: this.windowId
  1591. , type: type
  1592. , data: data || ''
  1593. }), this.origin);
  1594. };
  1595. IframeTransport.prototype.send = function(message) {
  1596. debug('send', message);
  1597. this.postMessage('m', message);
  1598. };
  1599. IframeTransport.enabled = function() {
  1600. return iframeUtils.iframeEnabled;
  1601. };
  1602. IframeTransport.transportName = 'iframe';
  1603. IframeTransport.roundTrips = 2;
  1604. module.exports = IframeTransport;
  1605. }).call(this,{ env: {} })
  1606. },{"../utils/event":46,"../utils/iframe":47,"../utils/random":50,"../utils/url":52,"../version":53,"debug":55,"events":3,"inherits":57,"json3":58}],23:[function(require,module,exports){
  1607. (function (global){
  1608. 'use strict';
  1609. // The simplest and most robust transport, using the well-know cross
  1610. // domain hack - JSONP. This transport is quite inefficient - one
  1611. // message could use up to one http request. But at least it works almost
  1612. // everywhere.
  1613. // Known limitations:
  1614. // o you will get a spinning cursor
  1615. // o for Konqueror a dumb timer is needed to detect errors
  1616. var inherits = require('inherits')
  1617. , SenderReceiver = require('./lib/sender-receiver')
  1618. , JsonpReceiver = require('./receiver/jsonp')
  1619. , jsonpSender = require('./sender/jsonp')
  1620. ;
  1621. function JsonPTransport(transUrl) {
  1622. if (!JsonPTransport.enabled()) {
  1623. throw new Error('Transport created when disabled');
  1624. }
  1625. SenderReceiver.call(this, transUrl, '/jsonp', jsonpSender, JsonpReceiver);
  1626. }
  1627. inherits(JsonPTransport, SenderReceiver);
  1628. JsonPTransport.enabled = function() {
  1629. return !!global.document;
  1630. };
  1631. JsonPTransport.transportName = 'jsonp-polling';
  1632. JsonPTransport.roundTrips = 1;
  1633. JsonPTransport.needBody = true;
  1634. module.exports = JsonPTransport;
  1635. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1636. },{"./lib/sender-receiver":28,"./receiver/jsonp":31,"./sender/jsonp":33,"inherits":57}],24:[function(require,module,exports){
  1637. (function (process){
  1638. 'use strict';
  1639. var inherits = require('inherits')
  1640. , urlUtils = require('../../utils/url')
  1641. , SenderReceiver = require('./sender-receiver')
  1642. ;
  1643. var debug = function() {};
  1644. if (process.env.NODE_ENV !== 'production') {
  1645. debug = require('debug')('sockjs-client:ajax-based');
  1646. }
  1647. function createAjaxSender(AjaxObject) {
  1648. return function(url, payload, callback) {
  1649. debug('create ajax sender', url, payload);
  1650. var opt = {};
  1651. if (typeof payload === 'string') {
  1652. opt.headers = {'Content-type': 'text/plain'};
  1653. }
  1654. var ajaxUrl = urlUtils.addPath(url, '/xhr_send');
  1655. var xo = new AjaxObject('POST', ajaxUrl, payload, opt);
  1656. xo.once('finish', function(status) {
  1657. debug('finish', status);
  1658. xo = null;
  1659. if (status !== 200 && status !== 204) {
  1660. return callback(new Error('http status ' + status));
  1661. }
  1662. callback();
  1663. });
  1664. return function() {
  1665. debug('abort');
  1666. xo.close();
  1667. xo = null;
  1668. var err = new Error('Aborted');
  1669. err.code = 1000;
  1670. callback(err);
  1671. };
  1672. };
  1673. }
  1674. function AjaxBasedTransport(transUrl, urlSuffix, Receiver, AjaxObject) {
  1675. SenderReceiver.call(this, transUrl, urlSuffix, createAjaxSender(AjaxObject), Receiver, AjaxObject);
  1676. }
  1677. inherits(AjaxBasedTransport, SenderReceiver);
  1678. module.exports = AjaxBasedTransport;
  1679. }).call(this,{ env: {} })
  1680. },{"../../utils/url":52,"./sender-receiver":28,"debug":55,"inherits":57}],25:[function(require,module,exports){
  1681. (function (process){
  1682. 'use strict';
  1683. var inherits = require('inherits')
  1684. , EventEmitter = require('events').EventEmitter
  1685. ;
  1686. var debug = function() {};
  1687. if (process.env.NODE_ENV !== 'production') {
  1688. debug = require('debug')('sockjs-client:buffered-sender');
  1689. }
  1690. function BufferedSender(url, sender) {
  1691. debug(url);
  1692. EventEmitter.call(this);
  1693. this.sendBuffer = [];
  1694. this.sender = sender;
  1695. this.url = url;
  1696. }
  1697. inherits(BufferedSender, EventEmitter);
  1698. BufferedSender.prototype.send = function(message) {
  1699. debug('send', message);
  1700. this.sendBuffer.push(message);
  1701. if (!this.sendStop) {
  1702. this.sendSchedule();
  1703. }
  1704. };
  1705. // For polling transports in a situation when in the message callback,
  1706. // new message is being send. If the sending connection was started
  1707. // before receiving one, it is possible to saturate the network and
  1708. // timeout due to the lack of receiving socket. To avoid that we delay
  1709. // sending messages by some small time, in order to let receiving
  1710. // connection be started beforehand. This is only a halfmeasure and
  1711. // does not fix the big problem, but it does make the tests go more
  1712. // stable on slow networks.
  1713. BufferedSender.prototype.sendScheduleWait = function() {
  1714. debug('sendScheduleWait');
  1715. var self = this;
  1716. var tref;
  1717. this.sendStop = function() {
  1718. debug('sendStop');
  1719. self.sendStop = null;
  1720. clearTimeout(tref);
  1721. };
  1722. tref = setTimeout(function() {
  1723. debug('timeout');
  1724. self.sendStop = null;
  1725. self.sendSchedule();
  1726. }, 25);
  1727. };
  1728. BufferedSender.prototype.sendSchedule = function() {
  1729. debug('sendSchedule', this.sendBuffer.length);
  1730. var self = this;
  1731. if (this.sendBuffer.length > 0) {
  1732. var payload = '[' + this.sendBuffer.join(',') + ']';
  1733. this.sendStop = this.sender(this.url, payload, function(err) {
  1734. self.sendStop = null;
  1735. if (err) {
  1736. debug('error', err);
  1737. self.emit('close', err.code || 1006, 'Sending error: ' + err);
  1738. self.close();
  1739. } else {
  1740. self.sendScheduleWait();
  1741. }
  1742. });
  1743. this.sendBuffer = [];
  1744. }
  1745. };
  1746. BufferedSender.prototype._cleanup = function() {
  1747. debug('_cleanup');
  1748. this.removeAllListeners();
  1749. };
  1750. BufferedSender.prototype.close = function() {
  1751. debug('close');
  1752. this._cleanup();
  1753. if (this.sendStop) {
  1754. this.sendStop();
  1755. this.sendStop = null;
  1756. }
  1757. };
  1758. module.exports = BufferedSender;
  1759. }).call(this,{ env: {} })
  1760. },{"debug":55,"events":3,"inherits":57}],26:[function(require,module,exports){
  1761. (function (global){
  1762. 'use strict';
  1763. var inherits = require('inherits')
  1764. , IframeTransport = require('../iframe')
  1765. , objectUtils = require('../../utils/object')
  1766. ;
  1767. module.exports = function(transport) {
  1768. function IframeWrapTransport(transUrl, baseUrl) {
  1769. IframeTransport.call(this, transport.transportName, transUrl, baseUrl);
  1770. }
  1771. inherits(IframeWrapTransport, IframeTransport);
  1772. IframeWrapTransport.enabled = function(url, info) {
  1773. if (!global.document) {
  1774. return false;
  1775. }
  1776. var iframeInfo = objectUtils.extend({}, info);
  1777. iframeInfo.sameOrigin = true;
  1778. return transport.enabled(iframeInfo) && IframeTransport.enabled();
  1779. };
  1780. IframeWrapTransport.transportName = 'iframe-' + transport.transportName;
  1781. IframeWrapTransport.needBody = true;
  1782. IframeWrapTransport.roundTrips = IframeTransport.roundTrips + transport.roundTrips - 1; // html, javascript (2) + transport - no CORS (1)
  1783. IframeWrapTransport.facadeTransport = transport;
  1784. return IframeWrapTransport;
  1785. };
  1786. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1787. },{"../../utils/object":49,"../iframe":22,"inherits":57}],27:[function(require,module,exports){
  1788. (function (process){
  1789. 'use strict';
  1790. var inherits = require('inherits')
  1791. , EventEmitter = require('events').EventEmitter
  1792. ;
  1793. var debug = function() {};
  1794. if (process.env.NODE_ENV !== 'production') {
  1795. debug = require('debug')('sockjs-client:polling');
  1796. }
  1797. function Polling(Receiver, receiveUrl, AjaxObject) {
  1798. debug(receiveUrl);
  1799. EventEmitter.call(this);
  1800. this.Receiver = Receiver;
  1801. this.receiveUrl = receiveUrl;
  1802. this.AjaxObject = AjaxObject;
  1803. this._scheduleReceiver();
  1804. }
  1805. inherits(Polling, EventEmitter);
  1806. Polling.prototype._scheduleReceiver = function() {
  1807. debug('_scheduleReceiver');
  1808. var self = this;
  1809. var poll = this.poll = new this.Receiver(this.receiveUrl, this.AjaxObject);
  1810. poll.on('message', function(msg) {
  1811. debug('message', msg);
  1812. self.emit('message', msg);
  1813. });
  1814. poll.once('close', function(code, reason) {
  1815. debug('close', code, reason, self.pollIsClosing);
  1816. self.poll = poll = null;
  1817. if (!self.pollIsClosing) {
  1818. if (reason === 'network') {
  1819. self._scheduleReceiver();
  1820. } else {
  1821. self.emit('close', code || 1006, reason);
  1822. self.removeAllListeners();
  1823. }
  1824. }
  1825. });
  1826. };
  1827. Polling.prototype.abort = function() {
  1828. debug('abort');
  1829. this.removeAllListeners();
  1830. this.pollIsClosing = true;
  1831. if (this.poll) {
  1832. this.poll.abort();
  1833. }
  1834. };
  1835. module.exports = Polling;
  1836. }).call(this,{ env: {} })
  1837. },{"debug":55,"events":3,"inherits":57}],28:[function(require,module,exports){
  1838. (function (process){
  1839. 'use strict';
  1840. var inherits = require('inherits')
  1841. , urlUtils = require('../../utils/url')
  1842. , BufferedSender = require('./buffered-sender')
  1843. , Polling = require('./polling')
  1844. ;
  1845. var debug = function() {};
  1846. if (process.env.NODE_ENV !== 'production') {
  1847. debug = require('debug')('sockjs-client:sender-receiver');
  1848. }
  1849. function SenderReceiver(transUrl, urlSuffix, senderFunc, Receiver, AjaxObject) {
  1850. var pollUrl = urlUtils.addPath(transUrl, urlSuffix);
  1851. debug(pollUrl);
  1852. var self = this;
  1853. BufferedSender.call(this, transUrl, senderFunc);
  1854. this.poll = new Polling(Receiver, pollUrl, AjaxObject);
  1855. this.poll.on('message', function(msg) {
  1856. debug('poll message', msg);
  1857. self.emit('message', msg);
  1858. });
  1859. this.poll.once('close', function(code, reason) {
  1860. debug('poll close', code, reason);
  1861. self.poll = null;
  1862. self.emit('close', code, reason);
  1863. self.close();
  1864. });
  1865. }
  1866. inherits(SenderReceiver, BufferedSender);
  1867. SenderReceiver.prototype.close = function() {
  1868. BufferedSender.prototype.close.call(this);
  1869. debug('close');
  1870. this.removeAllListeners();
  1871. if (this.poll) {
  1872. this.poll.abort();
  1873. this.poll = null;
  1874. }
  1875. };
  1876. module.exports = SenderReceiver;
  1877. }).call(this,{ env: {} })
  1878. },{"../../utils/url":52,"./buffered-sender":25,"./polling":27,"debug":55,"inherits":57}],29:[function(require,module,exports){
  1879. (function (process){
  1880. 'use strict';
  1881. var inherits = require('inherits')
  1882. , EventEmitter = require('events').EventEmitter
  1883. , EventSourceDriver = require('eventsource')
  1884. ;
  1885. var debug = function() {};
  1886. if (process.env.NODE_ENV !== 'production') {
  1887. debug = require('debug')('sockjs-client:receiver:eventsource');
  1888. }
  1889. function EventSourceReceiver(url) {
  1890. debug(url);
  1891. EventEmitter.call(this);
  1892. var self = this;
  1893. var es = this.es = new EventSourceDriver(url);
  1894. es.onmessage = function(e) {
  1895. debug('message', e.data);
  1896. self.emit('message', decodeURI(e.data));
  1897. };
  1898. es.onerror = function(e) {
  1899. debug('error', es.readyState, e);
  1900. // ES on reconnection has readyState = 0 or 1.
  1901. // on network error it's CLOSED = 2
  1902. var reason = (es.readyState !== 2 ? 'network' : 'permanent');
  1903. self._cleanup();
  1904. self._close(reason);
  1905. };
  1906. }
  1907. inherits(EventSourceReceiver, EventEmitter);
  1908. EventSourceReceiver.prototype.abort = function() {
  1909. debug('abort');
  1910. this._cleanup();
  1911. this._close('user');
  1912. };
  1913. EventSourceReceiver.prototype._cleanup = function() {
  1914. debug('cleanup');
  1915. var es = this.es;
  1916. if (es) {
  1917. es.onmessage = es.onerror = null;
  1918. es.close();
  1919. this.es = null;
  1920. }
  1921. };
  1922. EventSourceReceiver.prototype._close = function(reason) {
  1923. debug('close', reason);
  1924. var self = this;
  1925. // Safari and chrome < 15 crash if we close window before
  1926. // waiting for ES cleanup. See:
  1927. // https://code.google.com/p/chromium/issues/detail?id=89155
  1928. setTimeout(function() {
  1929. self.emit('close', null, reason);
  1930. self.removeAllListeners();
  1931. }, 200);
  1932. };
  1933. module.exports = EventSourceReceiver;
  1934. }).call(this,{ env: {} })
  1935. },{"debug":55,"events":3,"eventsource":18,"inherits":57}],30:[function(require,module,exports){
  1936. (function (process,global){
  1937. 'use strict';
  1938. var inherits = require('inherits')
  1939. , iframeUtils = require('../../utils/iframe')
  1940. , urlUtils = require('../../utils/url')
  1941. , EventEmitter = require('events').EventEmitter
  1942. , random = require('../../utils/random')
  1943. ;
  1944. var debug = function() {};
  1945. if (process.env.NODE_ENV !== 'production') {
  1946. debug = require('debug')('sockjs-client:receiver:htmlfile');
  1947. }
  1948. function HtmlfileReceiver(url) {
  1949. debug(url);
  1950. EventEmitter.call(this);
  1951. var self = this;
  1952. iframeUtils.polluteGlobalNamespace();
  1953. this.id = 'a' + random.string(6);
  1954. url = urlUtils.addQuery(url, 'c=' + decodeURIComponent(iframeUtils.WPrefix + '.' + this.id));
  1955. debug('using htmlfile', HtmlfileReceiver.htmlfileEnabled);
  1956. var constructFunc = HtmlfileReceiver.htmlfileEnabled ?
  1957. iframeUtils.createHtmlfile : iframeUtils.createIframe;
  1958. global[iframeUtils.WPrefix][this.id] = {
  1959. start: function() {
  1960. debug('start');
  1961. self.iframeObj.loaded();
  1962. }
  1963. , message: function(data) {
  1964. debug('message', data);
  1965. self.emit('message', data);
  1966. }
  1967. , stop: function() {
  1968. debug('stop');
  1969. self._cleanup();
  1970. self._close('network');
  1971. }
  1972. };
  1973. this.iframeObj = constructFunc(url, function() {
  1974. debug('callback');
  1975. self._cleanup();
  1976. self._close('permanent');
  1977. });
  1978. }
  1979. inherits(HtmlfileReceiver, EventEmitter);
  1980. HtmlfileReceiver.prototype.abort = function() {
  1981. debug('abort');
  1982. this._cleanup();
  1983. this._close('user');
  1984. };
  1985. HtmlfileReceiver.prototype._cleanup = function() {
  1986. debug('_cleanup');
  1987. if (this.iframeObj) {
  1988. this.iframeObj.cleanup();
  1989. this.iframeObj = null;
  1990. }
  1991. delete global[iframeUtils.WPrefix][this.id];
  1992. };
  1993. HtmlfileReceiver.prototype._close = function(reason) {
  1994. debug('_close', reason);
  1995. this.emit('close', null, reason);
  1996. this.removeAllListeners();
  1997. };
  1998. HtmlfileReceiver.htmlfileEnabled = false;
  1999. // obfuscate to avoid firewalls
  2000. var axo = ['Active'].concat('Object').join('X');
  2001. if (axo in global) {
  2002. try {
  2003. HtmlfileReceiver.htmlfileEnabled = !!new global[axo]('htmlfile');
  2004. } catch (x) {
  2005. // intentionally empty
  2006. }
  2007. }
  2008. HtmlfileReceiver.enabled = HtmlfileReceiver.htmlfileEnabled || iframeUtils.iframeEnabled;
  2009. module.exports = HtmlfileReceiver;
  2010. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2011. },{"../../utils/iframe":47,"../../utils/random":50,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],31:[function(require,module,exports){
  2012. (function (process,global){
  2013. 'use strict';
  2014. var utils = require('../../utils/iframe')
  2015. , random = require('../../utils/random')
  2016. , browser = require('../../utils/browser')
  2017. , urlUtils = require('../../utils/url')
  2018. , inherits = require('inherits')
  2019. , EventEmitter = require('events').EventEmitter
  2020. ;
  2021. var debug = function() {};
  2022. if (process.env.NODE_ENV !== 'production') {
  2023. debug = require('debug')('sockjs-client:receiver:jsonp');
  2024. }
  2025. function JsonpReceiver(url) {
  2026. debug(url);
  2027. var self = this;
  2028. EventEmitter.call(this);
  2029. utils.polluteGlobalNamespace();
  2030. this.id = 'a' + random.string(6);
  2031. var urlWithId = urlUtils.addQuery(url, 'c=' + encodeURIComponent(utils.WPrefix + '.' + this.id));
  2032. global[utils.WPrefix][this.id] = this._callback.bind(this);
  2033. this._createScript(urlWithId);
  2034. // Fallback mostly for Konqueror - stupid timer, 35 seconds shall be plenty.
  2035. this.timeoutId = setTimeout(function() {
  2036. debug('timeout');
  2037. self._abort(new Error('JSONP script loaded abnormally (timeout)'));
  2038. }, JsonpReceiver.timeout);
  2039. }
  2040. inherits(JsonpReceiver, EventEmitter);
  2041. JsonpReceiver.prototype.abort = function() {
  2042. debug('abort');
  2043. if (global[utils.WPrefix][this.id]) {
  2044. var err = new Error('JSONP user aborted read');
  2045. err.code = 1000;
  2046. this._abort(err);
  2047. }
  2048. };
  2049. JsonpReceiver.timeout = 35000;
  2050. JsonpReceiver.scriptErrorTimeout = 1000;
  2051. JsonpReceiver.prototype._callback = function(data) {
  2052. debug('_callback', data);
  2053. this._cleanup();
  2054. if (this.aborting) {
  2055. return;
  2056. }
  2057. if (data) {
  2058. debug('message', data);
  2059. this.emit('message', data);
  2060. }
  2061. this.emit('close', null, 'network');
  2062. this.removeAllListeners();
  2063. };
  2064. JsonpReceiver.prototype._abort = function(err) {
  2065. debug('_abort', err);
  2066. this._cleanup();
  2067. this.aborting = true;
  2068. this.emit('close', err.code, err.message);
  2069. this.removeAllListeners();
  2070. };
  2071. JsonpReceiver.prototype._cleanup = function() {
  2072. debug('_cleanup');
  2073. clearTimeout(this.timeoutId);
  2074. if (this.script2) {
  2075. this.script2.parentNode.removeChild(this.script2);
  2076. this.script2 = null;
  2077. }
  2078. if (this.script) {
  2079. var script = this.script;
  2080. // Unfortunately, you can't really abort script loading of
  2081. // the script.
  2082. script.parentNode.removeChild(script);
  2083. script.onreadystatechange = script.onerror =
  2084. script.onload = script.onclick = null;
  2085. this.script = null;
  2086. }
  2087. delete global[utils.WPrefix][this.id];
  2088. };
  2089. JsonpReceiver.prototype._scriptError = function() {
  2090. debug('_scriptError');
  2091. var self = this;
  2092. if (this.errorTimer) {
  2093. return;
  2094. }
  2095. this.errorTimer = setTimeout(function() {
  2096. if (!self.loadedOkay) {
  2097. self._abort(new Error('JSONP script loaded abnormally (onerror)'));
  2098. }
  2099. }, JsonpReceiver.scriptErrorTimeout);
  2100. };
  2101. JsonpReceiver.prototype._createScript = function(url) {
  2102. debug('_createScript', url);
  2103. var self = this;
  2104. var script = this.script = global.document.createElement('script');
  2105. var script2; // Opera synchronous load trick.
  2106. script.id = 'a' + random.string(8);
  2107. script.src = url;
  2108. script.type = 'text/javascript';
  2109. script.charset = 'UTF-8';
  2110. script.onerror = this._scriptError.bind(this);
  2111. script.onload = function() {
  2112. debug('onload');
  2113. self._abort(new Error('JSONP script loaded abnormally (onload)'));
  2114. };
  2115. // IE9 fires 'error' event after onreadystatechange or before, in random order.
  2116. // Use loadedOkay to determine if actually errored
  2117. script.onreadystatechange = function() {
  2118. debug('onreadystatechange', script.readyState);
  2119. if (/loaded|closed/.test(script.readyState)) {
  2120. if (script && script.htmlFor && script.onclick) {
  2121. self.loadedOkay = true;
  2122. try {
  2123. // In IE, actually execute the script.
  2124. script.onclick();
  2125. } catch (x) {
  2126. // intentionally empty
  2127. }
  2128. }
  2129. if (script) {
  2130. self._abort(new Error('JSONP script loaded abnormally (onreadystatechange)'));
  2131. }
  2132. }
  2133. };
  2134. // IE: event/htmlFor/onclick trick.
  2135. // One can't rely on proper order for onreadystatechange. In order to
  2136. // make sure, set a 'htmlFor' and 'event' properties, so that
  2137. // script code will be installed as 'onclick' handler for the
  2138. // script object. Later, onreadystatechange, manually execute this
  2139. // code. FF and Chrome doesn't work with 'event' and 'htmlFor'
  2140. // set. For reference see:
  2141. // http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html
  2142. // Also, read on that about script ordering:
  2143. // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
  2144. if (typeof script.async === 'undefined' && global.document.attachEvent) {
  2145. // According to mozilla docs, in recent browsers script.async defaults
  2146. // to 'true', so we may use it to detect a good browser:
  2147. // https://developer.mozilla.org/en/HTML/Element/script
  2148. if (!browser.isOpera()) {
  2149. // Naively assume we're in IE
  2150. try {
  2151. script.htmlFor = script.id;
  2152. script.event = 'onclick';
  2153. } catch (x) {
  2154. // intentionally empty
  2155. }
  2156. script.async = true;
  2157. } else {
  2158. // Opera, second sync script hack
  2159. script2 = this.script2 = global.document.createElement('script');
  2160. script2.text = "try{var a = document.getElementById('" + script.id + "'); if(a)a.onerror();}catch(x){};";
  2161. script.async = script2.async = false;
  2162. }
  2163. }
  2164. if (typeof script.async !== 'undefined') {
  2165. script.async = true;
  2166. }
  2167. var head = global.document.getElementsByTagName('head')[0];
  2168. head.insertBefore(script, head.firstChild);
  2169. if (script2) {
  2170. head.insertBefore(script2, head.firstChild);
  2171. }
  2172. };
  2173. module.exports = JsonpReceiver;
  2174. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2175. },{"../../utils/browser":44,"../../utils/iframe":47,"../../utils/random":50,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],32:[function(require,module,exports){
  2176. (function (process){
  2177. 'use strict';
  2178. var inherits = require('inherits')
  2179. , EventEmitter = require('events').EventEmitter
  2180. ;
  2181. var debug = function() {};
  2182. if (process.env.NODE_ENV !== 'production') {
  2183. debug = require('debug')('sockjs-client:receiver:xhr');
  2184. }
  2185. function XhrReceiver(url, AjaxObject) {
  2186. debug(url);
  2187. EventEmitter.call(this);
  2188. var self = this;
  2189. this.bufferPosition = 0;
  2190. this.xo = new AjaxObject('POST', url, null);
  2191. this.xo.on('chunk', this._chunkHandler.bind(this));
  2192. this.xo.once('finish', function(status, text) {
  2193. debug('finish', status, text);
  2194. self._chunkHandler(status, text);
  2195. self.xo = null;
  2196. var reason = status === 200 ? 'network' : 'permanent';
  2197. debug('close', reason);
  2198. self.emit('close', null, reason);
  2199. self._cleanup();
  2200. });
  2201. }
  2202. inherits(XhrReceiver, EventEmitter);
  2203. XhrReceiver.prototype._chunkHandler = function(status, text) {
  2204. debug('_chunkHandler', status);
  2205. if (status !== 200 || !text) {
  2206. return;
  2207. }
  2208. for (var idx = -1; ; this.bufferPosition += idx + 1) {
  2209. var buf = text.slice(this.bufferPosition);
  2210. idx = buf.indexOf('\n');
  2211. if (idx === -1) {
  2212. break;
  2213. }
  2214. var msg = buf.slice(0, idx);
  2215. if (msg) {
  2216. debug('message', msg);
  2217. this.emit('message', msg);
  2218. }
  2219. }
  2220. };
  2221. XhrReceiver.prototype._cleanup = function() {
  2222. debug('_cleanup');
  2223. this.removeAllListeners();
  2224. };
  2225. XhrReceiver.prototype.abort = function() {
  2226. debug('abort');
  2227. if (this.xo) {
  2228. this.xo.close();
  2229. debug('close');
  2230. this.emit('close', null, 'user');
  2231. this.xo = null;
  2232. }
  2233. this._cleanup();
  2234. };
  2235. module.exports = XhrReceiver;
  2236. }).call(this,{ env: {} })
  2237. },{"debug":55,"events":3,"inherits":57}],33:[function(require,module,exports){
  2238. (function (process,global){
  2239. 'use strict';
  2240. var random = require('../../utils/random')
  2241. , urlUtils = require('../../utils/url')
  2242. ;
  2243. var debug = function() {};
  2244. if (process.env.NODE_ENV !== 'production') {
  2245. debug = require('debug')('sockjs-client:sender:jsonp');
  2246. }
  2247. var form, area;
  2248. function createIframe(id) {
  2249. debug('createIframe', id);
  2250. try {
  2251. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  2252. return global.document.createElement('<iframe name="' + id + '">');
  2253. } catch (x) {
  2254. var iframe = global.document.createElement('iframe');
  2255. iframe.name = id;
  2256. return iframe;
  2257. }
  2258. }
  2259. function createForm() {
  2260. debug('createForm');
  2261. form = global.document.createElement('form');
  2262. form.style.display = 'none';
  2263. form.style.position = 'absolute';
  2264. form.method = 'POST';
  2265. form.enctype = 'application/x-www-form-urlencoded';
  2266. form.acceptCharset = 'UTF-8';
  2267. area = global.document.createElement('textarea');
  2268. area.name = 'd';
  2269. form.appendChild(area);
  2270. global.document.body.appendChild(form);
  2271. }
  2272. module.exports = function(url, payload, callback) {
  2273. debug(url, payload);
  2274. if (!form) {
  2275. createForm();
  2276. }
  2277. var id = 'a' + random.string(8);
  2278. form.target = id;
  2279. form.action = urlUtils.addQuery(urlUtils.addPath(url, '/jsonp_send'), 'i=' + id);
  2280. var iframe = createIframe(id);
  2281. iframe.id = id;
  2282. iframe.style.display = 'none';
  2283. form.appendChild(iframe);
  2284. try {
  2285. area.value = payload;
  2286. } catch (e) {
  2287. // seriously broken browsers get here
  2288. }
  2289. form.submit();
  2290. var completed = function(err) {
  2291. debug('completed', id, err);
  2292. if (!iframe.onerror) {
  2293. return;
  2294. }
  2295. iframe.onreadystatechange = iframe.onerror = iframe.onload = null;
  2296. // Opera mini doesn't like if we GC iframe
  2297. // immediately, thus this timeout.
  2298. setTimeout(function() {
  2299. debug('cleaning up', id);
  2300. iframe.parentNode.removeChild(iframe);
  2301. iframe = null;
  2302. }, 500);
  2303. area.value = '';
  2304. // It is not possible to detect if the iframe succeeded or
  2305. // failed to submit our form.
  2306. callback(err);
  2307. };
  2308. iframe.onerror = function() {
  2309. debug('onerror', id);
  2310. completed();
  2311. };
  2312. iframe.onload = function() {
  2313. debug('onload', id);
  2314. completed();
  2315. };
  2316. iframe.onreadystatechange = function(e) {
  2317. debug('onreadystatechange', id, iframe.readyState, e);
  2318. if (iframe.readyState === 'complete') {
  2319. completed();
  2320. }
  2321. };
  2322. return function() {
  2323. debug('aborted', id);
  2324. completed(new Error('Aborted'));
  2325. };
  2326. };
  2327. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2328. },{"../../utils/random":50,"../../utils/url":52,"debug":55}],34:[function(require,module,exports){
  2329. (function (process,global){
  2330. 'use strict';
  2331. var EventEmitter = require('events').EventEmitter
  2332. , inherits = require('inherits')
  2333. , eventUtils = require('../../utils/event')
  2334. , browser = require('../../utils/browser')
  2335. , urlUtils = require('../../utils/url')
  2336. ;
  2337. var debug = function() {};
  2338. if (process.env.NODE_ENV !== 'production') {
  2339. debug = require('debug')('sockjs-client:sender:xdr');
  2340. }
  2341. // References:
  2342. // http://ajaxian.com/archives/100-line-ajax-wrapper
  2343. // http://msdn.microsoft.com/en-us/library/cc288060(v=VS.85).aspx
  2344. function XDRObject(method, url, payload) {
  2345. debug(method, url);
  2346. var self = this;
  2347. EventEmitter.call(this);
  2348. setTimeout(function() {
  2349. self._start(method, url, payload);
  2350. }, 0);
  2351. }
  2352. inherits(XDRObject, EventEmitter);
  2353. XDRObject.prototype._start = function(method, url, payload) {
  2354. debug('_start');
  2355. var self = this;
  2356. var xdr = new global.XDomainRequest();
  2357. // IE caches even POSTs
  2358. url = urlUtils.addQuery(url, 't=' + (+new Date()));
  2359. xdr.onerror = function() {
  2360. debug('onerror');
  2361. self._error();
  2362. };
  2363. xdr.ontimeout = function() {
  2364. debug('ontimeout');
  2365. self._error();
  2366. };
  2367. xdr.onprogress = function() {
  2368. debug('progress', xdr.responseText);
  2369. self.emit('chunk', 200, xdr.responseText);
  2370. };
  2371. xdr.onload = function() {
  2372. debug('load');
  2373. self.emit('finish', 200, xdr.responseText);
  2374. self._cleanup(false);
  2375. };
  2376. this.xdr = xdr;
  2377. this.unloadRef = eventUtils.unloadAdd(function() {
  2378. self._cleanup(true);
  2379. });
  2380. try {
  2381. // Fails with AccessDenied if port number is bogus
  2382. this.xdr.open(method, url);
  2383. if (this.timeout) {
  2384. this.xdr.timeout = this.timeout;
  2385. }
  2386. this.xdr.send(payload);
  2387. } catch (x) {
  2388. this._error();
  2389. }
  2390. };
  2391. XDRObject.prototype._error = function() {
  2392. this.emit('finish', 0, '');
  2393. this._cleanup(false);
  2394. };
  2395. XDRObject.prototype._cleanup = function(abort) {
  2396. debug('cleanup', abort);
  2397. if (!this.xdr) {
  2398. return;
  2399. }
  2400. this.removeAllListeners();
  2401. eventUtils.unloadDel(this.unloadRef);
  2402. this.xdr.ontimeout = this.xdr.onerror = this.xdr.onprogress = this.xdr.onload = null;
  2403. if (abort) {
  2404. try {
  2405. this.xdr.abort();
  2406. } catch (x) {
  2407. // intentionally empty
  2408. }
  2409. }
  2410. this.unloadRef = this.xdr = null;
  2411. };
  2412. XDRObject.prototype.close = function() {
  2413. debug('close');
  2414. this._cleanup(true);
  2415. };
  2416. // IE 8/9 if the request target uses the same scheme - #79
  2417. XDRObject.enabled = !!(global.XDomainRequest && browser.hasDomain());
  2418. module.exports = XDRObject;
  2419. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2420. },{"../../utils/browser":44,"../../utils/event":46,"../../utils/url":52,"debug":55,"events":3,"inherits":57}],35:[function(require,module,exports){
  2421. 'use strict';
  2422. var inherits = require('inherits')
  2423. , XhrDriver = require('../driver/xhr')
  2424. ;
  2425. function XHRCorsObject(method, url, payload, opts) {
  2426. XhrDriver.call(this, method, url, payload, opts);
  2427. }
  2428. inherits(XHRCorsObject, XhrDriver);
  2429. XHRCorsObject.enabled = XhrDriver.enabled && XhrDriver.supportsCORS;
  2430. module.exports = XHRCorsObject;
  2431. },{"../driver/xhr":17,"inherits":57}],36:[function(require,module,exports){
  2432. 'use strict';
  2433. var EventEmitter = require('events').EventEmitter
  2434. , inherits = require('inherits')
  2435. ;
  2436. function XHRFake(/* method, url, payload, opts */) {
  2437. var self = this;
  2438. EventEmitter.call(this);
  2439. this.to = setTimeout(function() {
  2440. self.emit('finish', 200, '{}');
  2441. }, XHRFake.timeout);
  2442. }
  2443. inherits(XHRFake, EventEmitter);
  2444. XHRFake.prototype.close = function() {
  2445. clearTimeout(this.to);
  2446. };
  2447. XHRFake.timeout = 2000;
  2448. module.exports = XHRFake;
  2449. },{"events":3,"inherits":57}],37:[function(require,module,exports){
  2450. 'use strict';
  2451. var inherits = require('inherits')
  2452. , XhrDriver = require('../driver/xhr')
  2453. ;
  2454. function XHRLocalObject(method, url, payload /*, opts */) {
  2455. XhrDriver.call(this, method, url, payload, {
  2456. noCredentials: true
  2457. });
  2458. }
  2459. inherits(XHRLocalObject, XhrDriver);
  2460. XHRLocalObject.enabled = XhrDriver.enabled;
  2461. module.exports = XHRLocalObject;
  2462. },{"../driver/xhr":17,"inherits":57}],38:[function(require,module,exports){
  2463. (function (process){
  2464. 'use strict';
  2465. var utils = require('../utils/event')
  2466. , urlUtils = require('../utils/url')
  2467. , inherits = require('inherits')
  2468. , EventEmitter = require('events').EventEmitter
  2469. , WebsocketDriver = require('./driver/websocket')
  2470. ;
  2471. var debug = function() {};
  2472. if (process.env.NODE_ENV !== 'production') {
  2473. debug = require('debug')('sockjs-client:websocket');
  2474. }
  2475. function WebSocketTransport(transUrl, ignore, options) {
  2476. if (!WebSocketTransport.enabled()) {
  2477. throw new Error('Transport created when disabled');
  2478. }
  2479. EventEmitter.call(this);
  2480. debug('constructor', transUrl);
  2481. var self = this;
  2482. var url = urlUtils.addPath(transUrl, '/websocket');
  2483. if (url.slice(0, 5) === 'https') {
  2484. url = 'wss' + url.slice(5);
  2485. } else {
  2486. url = 'ws' + url.slice(4);
  2487. }
  2488. this.url = url;
  2489. this.ws = new WebsocketDriver(this.url, [], options);
  2490. this.ws.onmessage = function(e) {
  2491. debug('message event', e.data);
  2492. self.emit('message', e.data);
  2493. };
  2494. // Firefox has an interesting bug. If a websocket connection is
  2495. // created after onunload, it stays alive even when user
  2496. // navigates away from the page. In such situation let's lie -
  2497. // let's not open the ws connection at all. See:
  2498. // https://github.com/sockjs/sockjs-client/issues/28
  2499. // https://bugzilla.mozilla.org/show_bug.cgi?id=696085
  2500. this.unloadRef = utils.unloadAdd(function() {
  2501. debug('unload');
  2502. self.ws.close();
  2503. });
  2504. this.ws.onclose = function(e) {
  2505. debug('close event', e.code, e.reason);
  2506. self.emit('close', e.code, e.reason);
  2507. self._cleanup();
  2508. };
  2509. this.ws.onerror = function(e) {
  2510. debug('error event', e);
  2511. self.emit('close', 1006, 'WebSocket connection broken');
  2512. self._cleanup();
  2513. };
  2514. }
  2515. inherits(WebSocketTransport, EventEmitter);
  2516. WebSocketTransport.prototype.send = function(data) {
  2517. var msg = '[' + data + ']';
  2518. debug('send', msg);
  2519. this.ws.send(msg);
  2520. };
  2521. WebSocketTransport.prototype.close = function() {
  2522. debug('close');
  2523. var ws = this.ws;
  2524. this._cleanup();
  2525. if (ws) {
  2526. ws.close();
  2527. }
  2528. };
  2529. WebSocketTransport.prototype._cleanup = function() {
  2530. debug('_cleanup');
  2531. var ws = this.ws;
  2532. if (ws) {
  2533. ws.onmessage = ws.onclose = ws.onerror = null;
  2534. }
  2535. utils.unloadDel(this.unloadRef);
  2536. this.unloadRef = this.ws = null;
  2537. this.removeAllListeners();
  2538. };
  2539. WebSocketTransport.enabled = function() {
  2540. debug('enabled');
  2541. return !!WebsocketDriver;
  2542. };
  2543. WebSocketTransport.transportName = 'websocket';
  2544. // In theory, ws should require 1 round trip. But in chrome, this is
  2545. // not very stable over SSL. Most likely a ws connection requires a
  2546. // separate SSL connection, in which case 2 round trips are an
  2547. // absolute minumum.
  2548. WebSocketTransport.roundTrips = 2;
  2549. module.exports = WebSocketTransport;
  2550. }).call(this,{ env: {} })
  2551. },{"../utils/event":46,"../utils/url":52,"./driver/websocket":19,"debug":55,"events":3,"inherits":57}],39:[function(require,module,exports){
  2552. 'use strict';
  2553. var inherits = require('inherits')
  2554. , AjaxBasedTransport = require('./lib/ajax-based')
  2555. , XdrStreamingTransport = require('./xdr-streaming')
  2556. , XhrReceiver = require('./receiver/xhr')
  2557. , XDRObject = require('./sender/xdr')
  2558. ;
  2559. function XdrPollingTransport(transUrl) {
  2560. if (!XDRObject.enabled) {
  2561. throw new Error('Transport created when disabled');
  2562. }
  2563. AjaxBasedTransport.call(this, transUrl, '/xhr', XhrReceiver, XDRObject);
  2564. }
  2565. inherits(XdrPollingTransport, AjaxBasedTransport);
  2566. XdrPollingTransport.enabled = XdrStreamingTransport.enabled;
  2567. XdrPollingTransport.transportName = 'xdr-polling';
  2568. XdrPollingTransport.roundTrips = 2; // preflight, ajax
  2569. module.exports = XdrPollingTransport;
  2570. },{"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xdr":34,"./xdr-streaming":40,"inherits":57}],40:[function(require,module,exports){
  2571. 'use strict';
  2572. var inherits = require('inherits')
  2573. , AjaxBasedTransport = require('./lib/ajax-based')
  2574. , XhrReceiver = require('./receiver/xhr')
  2575. , XDRObject = require('./sender/xdr')
  2576. ;
  2577. // According to:
  2578. // http://stackoverflow.com/questions/1641507/detect-browser-support-for-cross-domain-xmlhttprequests
  2579. // http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
  2580. function XdrStreamingTransport(transUrl) {
  2581. if (!XDRObject.enabled) {
  2582. throw new Error('Transport created when disabled');
  2583. }
  2584. AjaxBasedTransport.call(this, transUrl, '/xhr_streaming', XhrReceiver, XDRObject);
  2585. }
  2586. inherits(XdrStreamingTransport, AjaxBasedTransport);
  2587. XdrStreamingTransport.enabled = function(info) {
  2588. if (info.cookie_needed || info.nullOrigin) {
  2589. return false;
  2590. }
  2591. return XDRObject.enabled && info.sameScheme;
  2592. };
  2593. XdrStreamingTransport.transportName = 'xdr-streaming';
  2594. XdrStreamingTransport.roundTrips = 2; // preflight, ajax
  2595. module.exports = XdrStreamingTransport;
  2596. },{"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xdr":34,"inherits":57}],41:[function(require,module,exports){
  2597. 'use strict';
  2598. var inherits = require('inherits')
  2599. , AjaxBasedTransport = require('./lib/ajax-based')
  2600. , XhrReceiver = require('./receiver/xhr')
  2601. , XHRCorsObject = require('./sender/xhr-cors')
  2602. , XHRLocalObject = require('./sender/xhr-local')
  2603. ;
  2604. function XhrPollingTransport(transUrl) {
  2605. if (!XHRLocalObject.enabled && !XHRCorsObject.enabled) {
  2606. throw new Error('Transport created when disabled');
  2607. }
  2608. AjaxBasedTransport.call(this, transUrl, '/xhr', XhrReceiver, XHRCorsObject);
  2609. }
  2610. inherits(XhrPollingTransport, AjaxBasedTransport);
  2611. XhrPollingTransport.enabled = function(info) {
  2612. if (info.nullOrigin) {
  2613. return false;
  2614. }
  2615. if (XHRLocalObject.enabled && info.sameOrigin) {
  2616. return true;
  2617. }
  2618. return XHRCorsObject.enabled;
  2619. };
  2620. XhrPollingTransport.transportName = 'xhr-polling';
  2621. XhrPollingTransport.roundTrips = 2; // preflight, ajax
  2622. module.exports = XhrPollingTransport;
  2623. },{"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xhr-cors":35,"./sender/xhr-local":37,"inherits":57}],42:[function(require,module,exports){
  2624. (function (global){
  2625. 'use strict';
  2626. var inherits = require('inherits')
  2627. , AjaxBasedTransport = require('./lib/ajax-based')
  2628. , XhrReceiver = require('./receiver/xhr')
  2629. , XHRCorsObject = require('./sender/xhr-cors')
  2630. , XHRLocalObject = require('./sender/xhr-local')
  2631. , browser = require('../utils/browser')
  2632. ;
  2633. function XhrStreamingTransport(transUrl) {
  2634. if (!XHRLocalObject.enabled && !XHRCorsObject.enabled) {
  2635. throw new Error('Transport created when disabled');
  2636. }
  2637. AjaxBasedTransport.call(this, transUrl, '/xhr_streaming', XhrReceiver, XHRCorsObject);
  2638. }
  2639. inherits(XhrStreamingTransport, AjaxBasedTransport);
  2640. XhrStreamingTransport.enabled = function(info) {
  2641. if (info.nullOrigin) {
  2642. return false;
  2643. }
  2644. // Opera doesn't support xhr-streaming #60
  2645. // But it might be able to #92
  2646. if (browser.isOpera()) {
  2647. return false;
  2648. }
  2649. return XHRCorsObject.enabled;
  2650. };
  2651. XhrStreamingTransport.transportName = 'xhr-streaming';
  2652. XhrStreamingTransport.roundTrips = 2; // preflight, ajax
  2653. // Safari gets confused when a streaming ajax request is started
  2654. // before onload. This causes the load indicator to spin indefinetely.
  2655. // Only require body when used in a browser
  2656. XhrStreamingTransport.needBody = !!global.document;
  2657. module.exports = XhrStreamingTransport;
  2658. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2659. },{"../utils/browser":44,"./lib/ajax-based":24,"./receiver/xhr":32,"./sender/xhr-cors":35,"./sender/xhr-local":37,"inherits":57}],43:[function(require,module,exports){
  2660. (function (global){
  2661. 'use strict';
  2662. if (global.crypto && global.crypto.getRandomValues) {
  2663. module.exports.randomBytes = function(length) {
  2664. var bytes = new Uint8Array(length);
  2665. global.crypto.getRandomValues(bytes);
  2666. return bytes;
  2667. };
  2668. } else {
  2669. module.exports.randomBytes = function(length) {
  2670. var bytes = new Array(length);
  2671. for (var i = 0; i < length; i++) {
  2672. bytes[i] = Math.floor(Math.random() * 256);
  2673. }
  2674. return bytes;
  2675. };
  2676. }
  2677. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2678. },{}],44:[function(require,module,exports){
  2679. (function (global){
  2680. 'use strict';
  2681. module.exports = {
  2682. isOpera: function() {
  2683. return global.navigator &&
  2684. /opera/i.test(global.navigator.userAgent);
  2685. }
  2686. , isKonqueror: function() {
  2687. return global.navigator &&
  2688. /konqueror/i.test(global.navigator.userAgent);
  2689. }
  2690. // #187 wrap document.domain in try/catch because of WP8 from file:///
  2691. , hasDomain: function () {
  2692. // non-browser client always has a domain
  2693. if (!global.document) {
  2694. return true;
  2695. }
  2696. try {
  2697. return !!global.document.domain;
  2698. } catch (e) {
  2699. return false;
  2700. }
  2701. }
  2702. };
  2703. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2704. },{}],45:[function(require,module,exports){
  2705. 'use strict';
  2706. var JSON3 = require('json3');
  2707. // Some extra characters that Chrome gets wrong, and substitutes with
  2708. // something else on the wire.
  2709. // eslint-disable-next-line no-control-regex
  2710. var extraEscapable = /[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g
  2711. , extraLookup;
  2712. // This may be quite slow, so let's delay until user actually uses bad
  2713. // characters.
  2714. var unrollLookup = function(escapable) {
  2715. var i;
  2716. var unrolled = {};
  2717. var c = [];
  2718. for (i = 0; i < 65536; i++) {
  2719. c.push( String.fromCharCode(i) );
  2720. }
  2721. escapable.lastIndex = 0;
  2722. c.join('').replace(escapable, function(a) {
  2723. unrolled[ a ] = '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  2724. return '';
  2725. });
  2726. escapable.lastIndex = 0;
  2727. return unrolled;
  2728. };
  2729. // Quote string, also taking care of unicode characters that browsers
  2730. // often break. Especially, take care of unicode surrogates:
  2731. // http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Surrogates
  2732. module.exports = {
  2733. quote: function(string) {
  2734. var quoted = JSON3.stringify(string);
  2735. // In most cases this should be very fast and good enough.
  2736. extraEscapable.lastIndex = 0;
  2737. if (!extraEscapable.test(quoted)) {
  2738. return quoted;
  2739. }
  2740. if (!extraLookup) {
  2741. extraLookup = unrollLookup(extraEscapable);
  2742. }
  2743. return quoted.replace(extraEscapable, function(a) {
  2744. return extraLookup[a];
  2745. });
  2746. }
  2747. };
  2748. },{"json3":58}],46:[function(require,module,exports){
  2749. (function (global){
  2750. 'use strict';
  2751. var random = require('./random');
  2752. var onUnload = {}
  2753. , afterUnload = false
  2754. // detect google chrome packaged apps because they don't allow the 'unload' event
  2755. , isChromePackagedApp = global.chrome && global.chrome.app && global.chrome.app.runtime
  2756. ;
  2757. module.exports = {
  2758. attachEvent: function(event, listener) {
  2759. if (typeof global.addEventListener !== 'undefined') {
  2760. global.addEventListener(event, listener, false);
  2761. } else if (global.document && global.attachEvent) {
  2762. // IE quirks.
  2763. // According to: http://stevesouders.com/misc/test-postmessage.php
  2764. // the message gets delivered only to 'document', not 'window'.
  2765. global.document.attachEvent('on' + event, listener);
  2766. // I get 'window' for ie8.
  2767. global.attachEvent('on' + event, listener);
  2768. }
  2769. }
  2770. , detachEvent: function(event, listener) {
  2771. if (typeof global.addEventListener !== 'undefined') {
  2772. global.removeEventListener(event, listener, false);
  2773. } else if (global.document && global.detachEvent) {
  2774. global.document.detachEvent('on' + event, listener);
  2775. global.detachEvent('on' + event, listener);
  2776. }
  2777. }
  2778. , unloadAdd: function(listener) {
  2779. if (isChromePackagedApp) {
  2780. return null;
  2781. }
  2782. var ref = random.string(8);
  2783. onUnload[ref] = listener;
  2784. if (afterUnload) {
  2785. setTimeout(this.triggerUnloadCallbacks, 0);
  2786. }
  2787. return ref;
  2788. }
  2789. , unloadDel: function(ref) {
  2790. if (ref in onUnload) {
  2791. delete onUnload[ref];
  2792. }
  2793. }
  2794. , triggerUnloadCallbacks: function() {
  2795. for (var ref in onUnload) {
  2796. onUnload[ref]();
  2797. delete onUnload[ref];
  2798. }
  2799. }
  2800. };
  2801. var unloadTriggered = function() {
  2802. if (afterUnload) {
  2803. return;
  2804. }
  2805. afterUnload = true;
  2806. module.exports.triggerUnloadCallbacks();
  2807. };
  2808. // 'unload' alone is not reliable in opera within an iframe, but we
  2809. // can't use `beforeunload` as IE fires it on javascript: links.
  2810. if (!isChromePackagedApp) {
  2811. module.exports.attachEvent('unload', unloadTriggered);
  2812. }
  2813. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2814. },{"./random":50}],47:[function(require,module,exports){
  2815. (function (process,global){
  2816. 'use strict';
  2817. var eventUtils = require('./event')
  2818. , JSON3 = require('json3')
  2819. , browser = require('./browser')
  2820. ;
  2821. var debug = function() {};
  2822. if (process.env.NODE_ENV !== 'production') {
  2823. debug = require('debug')('sockjs-client:utils:iframe');
  2824. }
  2825. module.exports = {
  2826. WPrefix: '_jp'
  2827. , currentWindowId: null
  2828. , polluteGlobalNamespace: function() {
  2829. if (!(module.exports.WPrefix in global)) {
  2830. global[module.exports.WPrefix] = {};
  2831. }
  2832. }
  2833. , postMessage: function(type, data) {
  2834. if (global.parent !== global) {
  2835. global.parent.postMessage(JSON3.stringify({
  2836. windowId: module.exports.currentWindowId
  2837. , type: type
  2838. , data: data || ''
  2839. }), '*');
  2840. } else {
  2841. debug('Cannot postMessage, no parent window.', type, data);
  2842. }
  2843. }
  2844. , createIframe: function(iframeUrl, errorCallback) {
  2845. var iframe = global.document.createElement('iframe');
  2846. var tref, unloadRef;
  2847. var unattach = function() {
  2848. debug('unattach');
  2849. clearTimeout(tref);
  2850. // Explorer had problems with that.
  2851. try {
  2852. iframe.onload = null;
  2853. } catch (x) {
  2854. // intentionally empty
  2855. }
  2856. iframe.onerror = null;
  2857. };
  2858. var cleanup = function() {
  2859. debug('cleanup');
  2860. if (iframe) {
  2861. unattach();
  2862. // This timeout makes chrome fire onbeforeunload event
  2863. // within iframe. Without the timeout it goes straight to
  2864. // onunload.
  2865. setTimeout(function() {
  2866. if (iframe) {
  2867. iframe.parentNode.removeChild(iframe);
  2868. }
  2869. iframe = null;
  2870. }, 0);
  2871. eventUtils.unloadDel(unloadRef);
  2872. }
  2873. };
  2874. var onerror = function(err) {
  2875. debug('onerror', err);
  2876. if (iframe) {
  2877. cleanup();
  2878. errorCallback(err);
  2879. }
  2880. };
  2881. var post = function(msg, origin) {
  2882. debug('post', msg, origin);
  2883. setTimeout(function() {
  2884. try {
  2885. // When the iframe is not loaded, IE raises an exception
  2886. // on 'contentWindow'.
  2887. if (iframe && iframe.contentWindow) {
  2888. iframe.contentWindow.postMessage(msg, origin);
  2889. }
  2890. } catch (x) {
  2891. // intentionally empty
  2892. }
  2893. }, 0);
  2894. };
  2895. iframe.src = iframeUrl;
  2896. iframe.style.display = 'none';
  2897. iframe.style.position = 'absolute';
  2898. iframe.onerror = function() {
  2899. onerror('onerror');
  2900. };
  2901. iframe.onload = function() {
  2902. debug('onload');
  2903. // `onload` is triggered before scripts on the iframe are
  2904. // executed. Give it few seconds to actually load stuff.
  2905. clearTimeout(tref);
  2906. tref = setTimeout(function() {
  2907. onerror('onload timeout');
  2908. }, 2000);
  2909. };
  2910. global.document.body.appendChild(iframe);
  2911. tref = setTimeout(function() {
  2912. onerror('timeout');
  2913. }, 15000);
  2914. unloadRef = eventUtils.unloadAdd(cleanup);
  2915. return {
  2916. post: post
  2917. , cleanup: cleanup
  2918. , loaded: unattach
  2919. };
  2920. }
  2921. /* eslint no-undef: "off", new-cap: "off" */
  2922. , createHtmlfile: function(iframeUrl, errorCallback) {
  2923. var axo = ['Active'].concat('Object').join('X');
  2924. var doc = new global[axo]('htmlfile');
  2925. var tref, unloadRef;
  2926. var iframe;
  2927. var unattach = function() {
  2928. clearTimeout(tref);
  2929. iframe.onerror = null;
  2930. };
  2931. var cleanup = function() {
  2932. if (doc) {
  2933. unattach();
  2934. eventUtils.unloadDel(unloadRef);
  2935. iframe.parentNode.removeChild(iframe);
  2936. iframe = doc = null;
  2937. CollectGarbage();
  2938. }
  2939. };
  2940. var onerror = function(r) {
  2941. debug('onerror', r);
  2942. if (doc) {
  2943. cleanup();
  2944. errorCallback(r);
  2945. }
  2946. };
  2947. var post = function(msg, origin) {
  2948. try {
  2949. // When the iframe is not loaded, IE raises an exception
  2950. // on 'contentWindow'.
  2951. setTimeout(function() {
  2952. if (iframe && iframe.contentWindow) {
  2953. iframe.contentWindow.postMessage(msg, origin);
  2954. }
  2955. }, 0);
  2956. } catch (x) {
  2957. // intentionally empty
  2958. }
  2959. };
  2960. doc.open();
  2961. doc.write('<html><s' + 'cript>' +
  2962. 'document.domain="' + global.document.domain + '";' +
  2963. '</s' + 'cript></html>');
  2964. doc.close();
  2965. doc.parentWindow[module.exports.WPrefix] = global[module.exports.WPrefix];
  2966. var c = doc.createElement('div');
  2967. doc.body.appendChild(c);
  2968. iframe = doc.createElement('iframe');
  2969. c.appendChild(iframe);
  2970. iframe.src = iframeUrl;
  2971. iframe.onerror = function() {
  2972. onerror('onerror');
  2973. };
  2974. tref = setTimeout(function() {
  2975. onerror('timeout');
  2976. }, 15000);
  2977. unloadRef = eventUtils.unloadAdd(cleanup);
  2978. return {
  2979. post: post
  2980. , cleanup: cleanup
  2981. , loaded: unattach
  2982. };
  2983. }
  2984. };
  2985. module.exports.iframeEnabled = false;
  2986. if (global.document) {
  2987. // postMessage misbehaves in konqueror 4.6.5 - the messages are delivered with
  2988. // huge delay, or not at all.
  2989. module.exports.iframeEnabled = (typeof global.postMessage === 'function' ||
  2990. typeof global.postMessage === 'object') && (!browser.isKonqueror());
  2991. }
  2992. }).call(this,{ env: {} },typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2993. },{"./browser":44,"./event":46,"debug":55,"json3":58}],48:[function(require,module,exports){
  2994. (function (global){
  2995. 'use strict';
  2996. var logObject = {};
  2997. ['log', 'debug', 'warn'].forEach(function (level) {
  2998. var levelExists;
  2999. try {
  3000. levelExists = global.console && global.console[level] && global.console[level].apply;
  3001. } catch(e) {
  3002. // do nothing
  3003. }
  3004. logObject[level] = levelExists ? function () {
  3005. return global.console[level].apply(global.console, arguments);
  3006. } : (level === 'log' ? function () {} : logObject.log);
  3007. });
  3008. module.exports = logObject;
  3009. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3010. },{}],49:[function(require,module,exports){
  3011. 'use strict';
  3012. module.exports = {
  3013. isObject: function(obj) {
  3014. var type = typeof obj;
  3015. return type === 'function' || type === 'object' && !!obj;
  3016. }
  3017. , extend: function(obj) {
  3018. if (!this.isObject(obj)) {
  3019. return obj;
  3020. }
  3021. var source, prop;
  3022. for (var i = 1, length = arguments.length; i < length; i++) {
  3023. source = arguments[i];
  3024. for (prop in source) {
  3025. if (Object.prototype.hasOwnProperty.call(source, prop)) {
  3026. obj[prop] = source[prop];
  3027. }
  3028. }
  3029. }
  3030. return obj;
  3031. }
  3032. };
  3033. },{}],50:[function(require,module,exports){
  3034. 'use strict';
  3035. /* global crypto:true */
  3036. var crypto = require('crypto');
  3037. // This string has length 32, a power of 2, so the modulus doesn't introduce a
  3038. // bias.
  3039. var _randomStringChars = 'abcdefghijklmnopqrstuvwxyz012345';
  3040. module.exports = {
  3041. string: function(length) {
  3042. var max = _randomStringChars.length;
  3043. var bytes = crypto.randomBytes(length);
  3044. var ret = [];
  3045. for (var i = 0; i < length; i++) {
  3046. ret.push(_randomStringChars.substr(bytes[i] % max, 1));
  3047. }
  3048. return ret.join('');
  3049. }
  3050. , number: function(max) {
  3051. return Math.floor(Math.random() * max);
  3052. }
  3053. , numberString: function(max) {
  3054. var t = ('' + (max - 1)).length;
  3055. var p = new Array(t + 1).join('0');
  3056. return (p + this.number(max)).slice(-t);
  3057. }
  3058. };
  3059. },{"crypto":43}],51:[function(require,module,exports){
  3060. (function (process){
  3061. 'use strict';
  3062. var debug = function() {};
  3063. if (process.env.NODE_ENV !== 'production') {
  3064. debug = require('debug')('sockjs-client:utils:transport');
  3065. }
  3066. module.exports = function(availableTransports) {
  3067. return {
  3068. filterToEnabled: function(transportsWhitelist, info) {
  3069. var transports = {
  3070. main: []
  3071. , facade: []
  3072. };
  3073. if (!transportsWhitelist) {
  3074. transportsWhitelist = [];
  3075. } else if (typeof transportsWhitelist === 'string') {
  3076. transportsWhitelist = [transportsWhitelist];
  3077. }
  3078. availableTransports.forEach(function(trans) {
  3079. if (!trans) {
  3080. return;
  3081. }
  3082. if (trans.transportName === 'websocket' && info.websocket === false) {
  3083. debug('disabled from server', 'websocket');
  3084. return;
  3085. }
  3086. if (transportsWhitelist.length &&
  3087. transportsWhitelist.indexOf(trans.transportName) === -1) {
  3088. debug('not in whitelist', trans.transportName);
  3089. return;
  3090. }
  3091. if (trans.enabled(info)) {
  3092. debug('enabled', trans.transportName);
  3093. transports.main.push(trans);
  3094. if (trans.facadeTransport) {
  3095. transports.facade.push(trans.facadeTransport);
  3096. }
  3097. } else {
  3098. debug('disabled', trans.transportName);
  3099. }
  3100. });
  3101. return transports;
  3102. }
  3103. };
  3104. };
  3105. }).call(this,{ env: {} })
  3106. },{"debug":55}],52:[function(require,module,exports){
  3107. (function (process){
  3108. 'use strict';
  3109. var URL = require('url-parse');
  3110. var debug = function() {};
  3111. if (process.env.NODE_ENV !== 'production') {
  3112. debug = require('debug')('sockjs-client:utils:url');
  3113. }
  3114. module.exports = {
  3115. getOrigin: function(url) {
  3116. if (!url) {
  3117. return null;
  3118. }
  3119. var p = new URL(url);
  3120. if (p.protocol === 'file:') {
  3121. return null;
  3122. }
  3123. var port = p.port;
  3124. if (!port) {
  3125. port = (p.protocol === 'https:') ? '443' : '80';
  3126. }
  3127. return p.protocol + '//' + p.hostname + ':' + port;
  3128. }
  3129. , isOriginEqual: function(a, b) {
  3130. var res = this.getOrigin(a) === this.getOrigin(b);
  3131. debug('same', a, b, res);
  3132. return res;
  3133. }
  3134. , isSchemeEqual: function(a, b) {
  3135. return (a.split(':')[0] === b.split(':')[0]);
  3136. }
  3137. , addPath: function (url, path) {
  3138. var qs = url.split('?');
  3139. return qs[0] + path + (qs[1] ? '?' + qs[1] : '');
  3140. }
  3141. , addQuery: function (url, q) {
  3142. return url + (url.indexOf('?') === -1 ? ('?' + q) : ('&' + q));
  3143. }
  3144. };
  3145. }).call(this,{ env: {} })
  3146. },{"debug":55,"url-parse":61}],53:[function(require,module,exports){
  3147. module.exports = '1.3.0';
  3148. },{}],54:[function(require,module,exports){
  3149. /**
  3150. * Helpers.
  3151. */
  3152. var s = 1000;
  3153. var m = s * 60;
  3154. var h = m * 60;
  3155. var d = h * 24;
  3156. var w = d * 7;
  3157. var y = d * 365.25;
  3158. /**
  3159. * Parse or format the given `val`.
  3160. *
  3161. * Options:
  3162. *
  3163. * - `long` verbose formatting [false]
  3164. *
  3165. * @param {String|Number} val
  3166. * @param {Object} [options]
  3167. * @throws {Error} throw an error if val is not a non-empty string or a number
  3168. * @return {String|Number}
  3169. * @api public
  3170. */
  3171. module.exports = function(val, options) {
  3172. options = options || {};
  3173. var type = typeof val;
  3174. if (type === 'string' && val.length > 0) {
  3175. return parse(val);
  3176. } else if (type === 'number' && isNaN(val) === false) {
  3177. return options.long ? fmtLong(val) : fmtShort(val);
  3178. }
  3179. throw new Error(
  3180. 'val is not a non-empty string or a valid number. val=' +
  3181. JSON.stringify(val)
  3182. );
  3183. };
  3184. /**
  3185. * Parse the given `str` and return milliseconds.
  3186. *
  3187. * @param {String} str
  3188. * @return {Number}
  3189. * @api private
  3190. */
  3191. function parse(str) {
  3192. str = String(str);
  3193. if (str.length > 100) {
  3194. return;
  3195. }
  3196. var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
  3197. str
  3198. );
  3199. if (!match) {
  3200. return;
  3201. }
  3202. var n = parseFloat(match[1]);
  3203. var type = (match[2] || 'ms').toLowerCase();
  3204. switch (type) {
  3205. case 'years':
  3206. case 'year':
  3207. case 'yrs':
  3208. case 'yr':
  3209. case 'y':
  3210. return n * y;
  3211. case 'weeks':
  3212. case 'week':
  3213. case 'w':
  3214. return n * w;
  3215. case 'days':
  3216. case 'day':
  3217. case 'd':
  3218. return n * d;
  3219. case 'hours':
  3220. case 'hour':
  3221. case 'hrs':
  3222. case 'hr':
  3223. case 'h':
  3224. return n * h;
  3225. case 'minutes':
  3226. case 'minute':
  3227. case 'mins':
  3228. case 'min':
  3229. case 'm':
  3230. return n * m;
  3231. case 'seconds':
  3232. case 'second':
  3233. case 'secs':
  3234. case 'sec':
  3235. case 's':
  3236. return n * s;
  3237. case 'milliseconds':
  3238. case 'millisecond':
  3239. case 'msecs':
  3240. case 'msec':
  3241. case 'ms':
  3242. return n;
  3243. default:
  3244. return undefined;
  3245. }
  3246. }
  3247. /**
  3248. * Short format for `ms`.
  3249. *
  3250. * @param {Number} ms
  3251. * @return {String}
  3252. * @api private
  3253. */
  3254. function fmtShort(ms) {
  3255. var msAbs = Math.abs(ms);
  3256. if (msAbs >= d) {
  3257. return Math.round(ms / d) + 'd';
  3258. }
  3259. if (msAbs >= h) {
  3260. return Math.round(ms / h) + 'h';
  3261. }
  3262. if (msAbs >= m) {
  3263. return Math.round(ms / m) + 'm';
  3264. }
  3265. if (msAbs >= s) {
  3266. return Math.round(ms / s) + 's';
  3267. }
  3268. return ms + 'ms';
  3269. }
  3270. /**
  3271. * Long format for `ms`.
  3272. *
  3273. * @param {Number} ms
  3274. * @return {String}
  3275. * @api private
  3276. */
  3277. function fmtLong(ms) {
  3278. var msAbs = Math.abs(ms);
  3279. if (msAbs >= d) {
  3280. return plural(ms, msAbs, d, 'day');
  3281. }
  3282. if (msAbs >= h) {
  3283. return plural(ms, msAbs, h, 'hour');
  3284. }
  3285. if (msAbs >= m) {
  3286. return plural(ms, msAbs, m, 'minute');
  3287. }
  3288. if (msAbs >= s) {
  3289. return plural(ms, msAbs, s, 'second');
  3290. }
  3291. return ms + ' ms';
  3292. }
  3293. /**
  3294. * Pluralization helper.
  3295. */
  3296. function plural(ms, msAbs, n, name) {
  3297. var isPlural = msAbs >= n * 1.5;
  3298. return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
  3299. }
  3300. },{}],55:[function(require,module,exports){
  3301. (function (process){
  3302. "use strict";
  3303. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  3304. /* eslint-env browser */
  3305. /**
  3306. * This is the web browser implementation of `debug()`.
  3307. */
  3308. exports.log = log;
  3309. exports.formatArgs = formatArgs;
  3310. exports.save = save;
  3311. exports.load = load;
  3312. exports.useColors = useColors;
  3313. exports.storage = localstorage();
  3314. /**
  3315. * Colors.
  3316. */
  3317. exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
  3318. /**
  3319. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  3320. * and the Firebug extension (any Firefox version) are known
  3321. * to support "%c" CSS customizations.
  3322. *
  3323. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  3324. */
  3325. // eslint-disable-next-line complexity
  3326. function useColors() {
  3327. // NB: In an Electron preload script, document will be defined but not fully
  3328. // initialized. Since we know we're in Chrome, we'll just detect this case
  3329. // explicitly
  3330. if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
  3331. return true;
  3332. } // Internet Explorer and Edge do not support colors.
  3333. if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
  3334. return false;
  3335. } // Is webkit? http://stackoverflow.com/a/16459606/376773
  3336. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  3337. return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
  3338. typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
  3339. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  3340. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
  3341. typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
  3342. }
  3343. /**
  3344. * Colorize log arguments if enabled.
  3345. *
  3346. * @api public
  3347. */
  3348. function formatArgs(args) {
  3349. args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
  3350. if (!this.useColors) {
  3351. return;
  3352. }
  3353. var c = 'color: ' + this.color;
  3354. args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
  3355. // arguments passed either before or after the %c, so we need to
  3356. // figure out the correct index to insert the CSS into
  3357. var index = 0;
  3358. var lastC = 0;
  3359. args[0].replace(/%[a-zA-Z%]/g, function (match) {
  3360. if (match === '%%') {
  3361. return;
  3362. }
  3363. index++;
  3364. if (match === '%c') {
  3365. // We only are interested in the *last* %c
  3366. // (the user may have provided their own)
  3367. lastC = index;
  3368. }
  3369. });
  3370. args.splice(lastC, 0, c);
  3371. }
  3372. /**
  3373. * Invokes `console.log()` when available.
  3374. * No-op when `console.log` is not a "function".
  3375. *
  3376. * @api public
  3377. */
  3378. function log() {
  3379. var _console;
  3380. // This hackery is required for IE8/9, where
  3381. // the `console.log` function doesn't have 'apply'
  3382. return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
  3383. }
  3384. /**
  3385. * Save `namespaces`.
  3386. *
  3387. * @param {String} namespaces
  3388. * @api private
  3389. */
  3390. function save(namespaces) {
  3391. try {
  3392. if (namespaces) {
  3393. exports.storage.setItem('debug', namespaces);
  3394. } else {
  3395. exports.storage.removeItem('debug');
  3396. }
  3397. } catch (error) {// Swallow
  3398. // XXX (@Qix-) should we be logging these?
  3399. }
  3400. }
  3401. /**
  3402. * Load `namespaces`.
  3403. *
  3404. * @return {String} returns the previously persisted debug modes
  3405. * @api private
  3406. */
  3407. function load() {
  3408. var r;
  3409. try {
  3410. r = exports.storage.getItem('debug');
  3411. } catch (error) {} // Swallow
  3412. // XXX (@Qix-) should we be logging these?
  3413. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  3414. if (!r && typeof process !== 'undefined' && 'env' in process) {
  3415. r = process.env.DEBUG;
  3416. }
  3417. return r;
  3418. }
  3419. /**
  3420. * Localstorage attempts to return the localstorage.
  3421. *
  3422. * This is necessary because safari throws
  3423. * when a user disables cookies/localstorage
  3424. * and you attempt to access it.
  3425. *
  3426. * @return {LocalStorage}
  3427. * @api private
  3428. */
  3429. function localstorage() {
  3430. try {
  3431. // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
  3432. // The Browser also has localStorage in the global context.
  3433. return localStorage;
  3434. } catch (error) {// Swallow
  3435. // XXX (@Qix-) should we be logging these?
  3436. }
  3437. }
  3438. module.exports = require('./common')(exports);
  3439. var formatters = module.exports.formatters;
  3440. /**
  3441. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  3442. */
  3443. formatters.j = function (v) {
  3444. try {
  3445. return JSON.stringify(v);
  3446. } catch (error) {
  3447. return '[UnexpectedJSONParseError]: ' + error.message;
  3448. }
  3449. };
  3450. }).call(this,{ env: {} })
  3451. },{"./common":56}],56:[function(require,module,exports){
  3452. "use strict";
  3453. /**
  3454. * This is the common logic for both the Node.js and web browser
  3455. * implementations of `debug()`.
  3456. */
  3457. function setup(env) {
  3458. createDebug.debug = createDebug;
  3459. createDebug.default = createDebug;
  3460. createDebug.coerce = coerce;
  3461. createDebug.disable = disable;
  3462. createDebug.enable = enable;
  3463. createDebug.enabled = enabled;
  3464. createDebug.humanize = require('ms');
  3465. Object.keys(env).forEach(function (key) {
  3466. createDebug[key] = env[key];
  3467. });
  3468. /**
  3469. * Active `debug` instances.
  3470. */
  3471. createDebug.instances = [];
  3472. /**
  3473. * The currently active debug mode names, and names to skip.
  3474. */
  3475. createDebug.names = [];
  3476. createDebug.skips = [];
  3477. /**
  3478. * Map of special "%n" handling functions, for the debug "format" argument.
  3479. *
  3480. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  3481. */
  3482. createDebug.formatters = {};
  3483. /**
  3484. * Selects a color for a debug namespace
  3485. * @param {String} namespace The namespace string for the for the debug instance to be colored
  3486. * @return {Number|String} An ANSI color code for the given namespace
  3487. * @api private
  3488. */
  3489. function selectColor(namespace) {
  3490. var hash = 0;
  3491. for (var i = 0; i < namespace.length; i++) {
  3492. hash = (hash << 5) - hash + namespace.charCodeAt(i);
  3493. hash |= 0; // Convert to 32bit integer
  3494. }
  3495. return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
  3496. }
  3497. createDebug.selectColor = selectColor;
  3498. /**
  3499. * Create a debugger with the given `namespace`.
  3500. *
  3501. * @param {String} namespace
  3502. * @return {Function}
  3503. * @api public
  3504. */
  3505. function createDebug(namespace) {
  3506. var prevTime;
  3507. function debug() {
  3508. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  3509. args[_key] = arguments[_key];
  3510. }
  3511. // Disabled?
  3512. if (!debug.enabled) {
  3513. return;
  3514. }
  3515. var self = debug; // Set `diff` timestamp
  3516. var curr = Number(new Date());
  3517. var ms = curr - (prevTime || curr);
  3518. self.diff = ms;
  3519. self.prev = prevTime;
  3520. self.curr = curr;
  3521. prevTime = curr;
  3522. args[0] = createDebug.coerce(args[0]);
  3523. if (typeof args[0] !== 'string') {
  3524. // Anything else let's inspect with %O
  3525. args.unshift('%O');
  3526. } // Apply any `formatters` transformations
  3527. var index = 0;
  3528. args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
  3529. // If we encounter an escaped % then don't increase the array index
  3530. if (match === '%%') {
  3531. return match;
  3532. }
  3533. index++;
  3534. var formatter = createDebug.formatters[format];
  3535. if (typeof formatter === 'function') {
  3536. var val = args[index];
  3537. match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
  3538. args.splice(index, 1);
  3539. index--;
  3540. }
  3541. return match;
  3542. }); // Apply env-specific formatting (colors, etc.)
  3543. createDebug.formatArgs.call(self, args);
  3544. var logFn = self.log || createDebug.log;
  3545. logFn.apply(self, args);
  3546. }
  3547. debug.namespace = namespace;
  3548. debug.enabled = createDebug.enabled(namespace);
  3549. debug.useColors = createDebug.useColors();
  3550. debug.color = selectColor(namespace);
  3551. debug.destroy = destroy;
  3552. debug.extend = extend; // Debug.formatArgs = formatArgs;
  3553. // debug.rawLog = rawLog;
  3554. // env-specific initialization logic for debug instances
  3555. if (typeof createDebug.init === 'function') {
  3556. createDebug.init(debug);
  3557. }
  3558. createDebug.instances.push(debug);
  3559. return debug;
  3560. }
  3561. function destroy() {
  3562. var index = createDebug.instances.indexOf(this);
  3563. if (index !== -1) {
  3564. createDebug.instances.splice(index, 1);
  3565. return true;
  3566. }
  3567. return false;
  3568. }
  3569. function extend(namespace, delimiter) {
  3570. return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
  3571. }
  3572. /**
  3573. * Enables a debug mode by namespaces. This can include modes
  3574. * separated by a colon and wildcards.
  3575. *
  3576. * @param {String} namespaces
  3577. * @api public
  3578. */
  3579. function enable(namespaces) {
  3580. createDebug.save(namespaces);
  3581. createDebug.names = [];
  3582. createDebug.skips = [];
  3583. var i;
  3584. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  3585. var len = split.length;
  3586. for (i = 0; i < len; i++) {
  3587. if (!split[i]) {
  3588. // ignore empty strings
  3589. continue;
  3590. }
  3591. namespaces = split[i].replace(/\*/g, '.*?');
  3592. if (namespaces[0] === '-') {
  3593. createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  3594. } else {
  3595. createDebug.names.push(new RegExp('^' + namespaces + '$'));
  3596. }
  3597. }
  3598. for (i = 0; i < createDebug.instances.length; i++) {
  3599. var instance = createDebug.instances[i];
  3600. instance.enabled = createDebug.enabled(instance.namespace);
  3601. }
  3602. }
  3603. /**
  3604. * Disable debug output.
  3605. *
  3606. * @api public
  3607. */
  3608. function disable() {
  3609. createDebug.enable('');
  3610. }
  3611. /**
  3612. * Returns true if the given mode name is enabled, false otherwise.
  3613. *
  3614. * @param {String} name
  3615. * @return {Boolean}
  3616. * @api public
  3617. */
  3618. function enabled(name) {
  3619. if (name[name.length - 1] === '*') {
  3620. return true;
  3621. }
  3622. var i;
  3623. var len;
  3624. for (i = 0, len = createDebug.skips.length; i < len; i++) {
  3625. if (createDebug.skips[i].test(name)) {
  3626. return false;
  3627. }
  3628. }
  3629. for (i = 0, len = createDebug.names.length; i < len; i++) {
  3630. if (createDebug.names[i].test(name)) {
  3631. return true;
  3632. }
  3633. }
  3634. return false;
  3635. }
  3636. /**
  3637. * Coerce `val`.
  3638. *
  3639. * @param {Mixed} val
  3640. * @return {Mixed}
  3641. * @api private
  3642. */
  3643. function coerce(val) {
  3644. if (val instanceof Error) {
  3645. return val.stack || val.message;
  3646. }
  3647. return val;
  3648. }
  3649. createDebug.enable(createDebug.load());
  3650. return createDebug;
  3651. }
  3652. module.exports = setup;
  3653. },{"ms":54}],57:[function(require,module,exports){
  3654. if (typeof Object.create === 'function') {
  3655. // implementation from standard node.js 'util' module
  3656. module.exports = function inherits(ctor, superCtor) {
  3657. ctor.super_ = superCtor
  3658. ctor.prototype = Object.create(superCtor.prototype, {
  3659. constructor: {
  3660. value: ctor,
  3661. enumerable: false,
  3662. writable: true,
  3663. configurable: true
  3664. }
  3665. });
  3666. };
  3667. } else {
  3668. // old school shim for old browsers
  3669. module.exports = function inherits(ctor, superCtor) {
  3670. ctor.super_ = superCtor
  3671. var TempCtor = function () {}
  3672. TempCtor.prototype = superCtor.prototype
  3673. ctor.prototype = new TempCtor()
  3674. ctor.prototype.constructor = ctor
  3675. }
  3676. }
  3677. },{}],58:[function(require,module,exports){
  3678. (function (global){
  3679. /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
  3680. ;(function () {
  3681. // Detect the `define` function exposed by asynchronous module loaders. The
  3682. // strict `define` check is necessary for compatibility with `r.js`.
  3683. var isLoader = typeof define === "function" && define.amd;
  3684. // A set of types used to distinguish objects from primitives.
  3685. var objectTypes = {
  3686. "function": true,
  3687. "object": true
  3688. };
  3689. // Detect the `exports` object exposed by CommonJS implementations.
  3690. var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
  3691. // Use the `global` object exposed by Node (including Browserify via
  3692. // `insert-module-globals`), Narwhal, and Ringo as the default context,
  3693. // and the `window` object in browsers. Rhino exports a `global` function
  3694. // instead.
  3695. var root = objectTypes[typeof window] && window || this,
  3696. freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
  3697. if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
  3698. root = freeGlobal;
  3699. }
  3700. // Public: Initializes JSON 3 using the given `context` object, attaching the
  3701. // `stringify` and `parse` functions to the specified `exports` object.
  3702. function runInContext(context, exports) {
  3703. context || (context = root["Object"]());
  3704. exports || (exports = root["Object"]());
  3705. // Native constructor aliases.
  3706. var Number = context["Number"] || root["Number"],
  3707. String = context["String"] || root["String"],
  3708. Object = context["Object"] || root["Object"],
  3709. Date = context["Date"] || root["Date"],
  3710. SyntaxError = context["SyntaxError"] || root["SyntaxError"],
  3711. TypeError = context["TypeError"] || root["TypeError"],
  3712. Math = context["Math"] || root["Math"],
  3713. nativeJSON = context["JSON"] || root["JSON"];
  3714. // Delegate to the native `stringify` and `parse` implementations.
  3715. if (typeof nativeJSON == "object" && nativeJSON) {
  3716. exports.stringify = nativeJSON.stringify;
  3717. exports.parse = nativeJSON.parse;
  3718. }
  3719. // Convenience aliases.
  3720. var objectProto = Object.prototype,
  3721. getClass = objectProto.toString,
  3722. isProperty, forEach, undef;
  3723. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  3724. var isExtended = new Date(-3509827334573292);
  3725. try {
  3726. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  3727. // results for certain dates in Opera >= 10.53.
  3728. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  3729. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  3730. // but clips the values returned by the date methods to the range of
  3731. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  3732. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  3733. } catch (exception) {}
  3734. // Internal: Determines whether the native `JSON.stringify` and `parse`
  3735. // implementations are spec-compliant. Based on work by Ken Snyder.
  3736. function has(name) {
  3737. if (has[name] !== undef) {
  3738. // Return cached feature test result.
  3739. return has[name];
  3740. }
  3741. var isSupported;
  3742. if (name == "bug-string-char-index") {
  3743. // IE <= 7 doesn't support accessing string characters using square
  3744. // bracket notation. IE 8 only supports this for primitives.
  3745. isSupported = "a"[0] != "a";
  3746. } else if (name == "json") {
  3747. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  3748. // supported.
  3749. isSupported = has("json-stringify") && has("json-parse");
  3750. } else {
  3751. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  3752. // Test `JSON.stringify`.
  3753. if (name == "json-stringify") {
  3754. var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  3755. if (stringifySupported) {
  3756. // A test function object with a custom `toJSON` method.
  3757. (value = function () {
  3758. return 1;
  3759. }).toJSON = value;
  3760. try {
  3761. stringifySupported =
  3762. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  3763. // primitives as object literals.
  3764. stringify(0) === "0" &&
  3765. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  3766. // literals.
  3767. stringify(new Number()) === "0" &&
  3768. stringify(new String()) == '""' &&
  3769. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  3770. // does not define a canonical JSON representation (this applies to
  3771. // objects with `toJSON` properties as well, *unless* they are nested
  3772. // within an object or array).
  3773. stringify(getClass) === undef &&
  3774. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  3775. // FF 3.1b3 pass this test.
  3776. stringify(undef) === undef &&
  3777. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  3778. // respectively, if the value is omitted entirely.
  3779. stringify() === undef &&
  3780. // FF 3.1b1, 2 throw an error if the given value is not a number,
  3781. // string, array, object, Boolean, or `null` literal. This applies to
  3782. // objects with custom `toJSON` methods as well, unless they are nested
  3783. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  3784. // methods entirely.
  3785. stringify(value) === "1" &&
  3786. stringify([value]) == "[1]" &&
  3787. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  3788. // `"[null]"`.
  3789. stringify([undef]) == "[null]" &&
  3790. // YUI 3.0.0b1 fails to serialize `null` literals.
  3791. stringify(null) == "null" &&
  3792. // FF 3.1b1, 2 halts serialization if an array contains a function:
  3793. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  3794. // elides non-JSON values from objects and arrays, unless they
  3795. // define custom `toJSON` methods.
  3796. stringify([undef, getClass, null]) == "[null,null,null]" &&
  3797. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  3798. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  3799. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  3800. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  3801. stringify(null, value) === "1" &&
  3802. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  3803. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  3804. // serialize extended years.
  3805. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  3806. // The milliseconds are optional in ES 5, but required in 5.1.
  3807. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  3808. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  3809. // four-digit years instead of six-digit years. Credits: @Yaffle.
  3810. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  3811. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  3812. // values less than 1000. Credits: @Yaffle.
  3813. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  3814. } catch (exception) {
  3815. stringifySupported = false;
  3816. }
  3817. }
  3818. isSupported = stringifySupported;
  3819. }
  3820. // Test `JSON.parse`.
  3821. if (name == "json-parse") {
  3822. var parse = exports.parse;
  3823. if (typeof parse == "function") {
  3824. try {
  3825. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  3826. // Conforming implementations should also coerce the initial argument to
  3827. // a string prior to parsing.
  3828. if (parse("0") === 0 && !parse(false)) {
  3829. // Simple parsing test.
  3830. value = parse(serialized);
  3831. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  3832. if (parseSupported) {
  3833. try {
  3834. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  3835. parseSupported = !parse('"\t"');
  3836. } catch (exception) {}
  3837. if (parseSupported) {
  3838. try {
  3839. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  3840. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  3841. // certain octal literals.
  3842. parseSupported = parse("01") !== 1;
  3843. } catch (exception) {}
  3844. }
  3845. if (parseSupported) {
  3846. try {
  3847. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  3848. // points. These environments, along with FF 3.1b1 and 2,
  3849. // also allow trailing commas in JSON objects and arrays.
  3850. parseSupported = parse("1.") !== 1;
  3851. } catch (exception) {}
  3852. }
  3853. }
  3854. }
  3855. } catch (exception) {
  3856. parseSupported = false;
  3857. }
  3858. }
  3859. isSupported = parseSupported;
  3860. }
  3861. }
  3862. return has[name] = !!isSupported;
  3863. }
  3864. if (!has("json")) {
  3865. // Common `[[Class]]` name aliases.
  3866. var functionClass = "[object Function]",
  3867. dateClass = "[object Date]",
  3868. numberClass = "[object Number]",
  3869. stringClass = "[object String]",
  3870. arrayClass = "[object Array]",
  3871. booleanClass = "[object Boolean]";
  3872. // Detect incomplete support for accessing string characters by index.
  3873. var charIndexBuggy = has("bug-string-char-index");
  3874. // Define additional utility methods if the `Date` methods are buggy.
  3875. if (!isExtended) {
  3876. var floor = Math.floor;
  3877. // A mapping between the months of the year and the number of days between
  3878. // January 1st and the first of the respective month.
  3879. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  3880. // Internal: Calculates the number of days between the Unix epoch and the
  3881. // first day of the given month.
  3882. var getDay = function (year, month) {
  3883. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  3884. };
  3885. }
  3886. // Internal: Determines if a property is a direct property of the given
  3887. // object. Delegates to the native `Object#hasOwnProperty` method.
  3888. if (!(isProperty = objectProto.hasOwnProperty)) {
  3889. isProperty = function (property) {
  3890. var members = {}, constructor;
  3891. if ((members.__proto__ = null, members.__proto__ = {
  3892. // The *proto* property cannot be set multiple times in recent
  3893. // versions of Firefox and SeaMonkey.
  3894. "toString": 1
  3895. }, members).toString != getClass) {
  3896. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  3897. // supports the mutable *proto* property.
  3898. isProperty = function (property) {
  3899. // Capture and break the object's prototype chain (see section 8.6.2
  3900. // of the ES 5.1 spec). The parenthesized expression prevents an
  3901. // unsafe transformation by the Closure Compiler.
  3902. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  3903. // Restore the original prototype chain.
  3904. this.__proto__ = original;
  3905. return result;
  3906. };
  3907. } else {
  3908. // Capture a reference to the top-level `Object` constructor.
  3909. constructor = members.constructor;
  3910. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  3911. // other environments.
  3912. isProperty = function (property) {
  3913. var parent = (this.constructor || constructor).prototype;
  3914. return property in this && !(property in parent && this[property] === parent[property]);
  3915. };
  3916. }
  3917. members = null;
  3918. return isProperty.call(this, property);
  3919. };
  3920. }
  3921. // Internal: Normalizes the `for...in` iteration algorithm across
  3922. // environments. Each enumerated key is yielded to a `callback` function.
  3923. forEach = function (object, callback) {
  3924. var size = 0, Properties, members, property;
  3925. // Tests for bugs in the current environment's `for...in` algorithm. The
  3926. // `valueOf` property inherits the non-enumerable flag from
  3927. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  3928. (Properties = function () {
  3929. this.valueOf = 0;
  3930. }).prototype.valueOf = 0;
  3931. // Iterate over a new instance of the `Properties` class.
  3932. members = new Properties();
  3933. for (property in members) {
  3934. // Ignore all properties inherited from `Object.prototype`.
  3935. if (isProperty.call(members, property)) {
  3936. size++;
  3937. }
  3938. }
  3939. Properties = members = null;
  3940. // Normalize the iteration algorithm.
  3941. if (!size) {
  3942. // A list of non-enumerable properties inherited from `Object.prototype`.
  3943. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  3944. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  3945. // properties.
  3946. forEach = function (object, callback) {
  3947. var isFunction = getClass.call(object) == functionClass, property, length;
  3948. var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
  3949. for (property in object) {
  3950. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  3951. // certain conditions; IE does not.
  3952. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  3953. callback(property);
  3954. }
  3955. }
  3956. // Manually invoke the callback for each non-enumerable property.
  3957. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  3958. };
  3959. } else if (size == 2) {
  3960. // Safari <= 2.0.4 enumerates shadowed properties twice.
  3961. forEach = function (object, callback) {
  3962. // Create a set of iterated properties.
  3963. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  3964. for (property in object) {
  3965. // Store each property name to prevent double enumeration. The
  3966. // `prototype` property of functions is not enumerated due to cross-
  3967. // environment inconsistencies.
  3968. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  3969. callback(property);
  3970. }
  3971. }
  3972. };
  3973. } else {
  3974. // No bugs detected; use the standard `for...in` algorithm.
  3975. forEach = function (object, callback) {
  3976. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  3977. for (property in object) {
  3978. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  3979. callback(property);
  3980. }
  3981. }
  3982. // Manually invoke the callback for the `constructor` property due to
  3983. // cross-environment inconsistencies.
  3984. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  3985. callback(property);
  3986. }
  3987. };
  3988. }
  3989. return forEach(object, callback);
  3990. };
  3991. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  3992. // `filter` argument may specify either a function that alters how object and
  3993. // array members are serialized, or an array of strings and numbers that
  3994. // indicates which properties should be serialized. The optional `width`
  3995. // argument may be either a string or number that specifies the indentation
  3996. // level of the output.
  3997. if (!has("json-stringify")) {
  3998. // Internal: A map of control characters and their escaped equivalents.
  3999. var Escapes = {
  4000. 92: "\\\\",
  4001. 34: '\\"',
  4002. 8: "\\b",
  4003. 12: "\\f",
  4004. 10: "\\n",
  4005. 13: "\\r",
  4006. 9: "\\t"
  4007. };
  4008. // Internal: Converts `value` into a zero-padded string such that its
  4009. // length is at least equal to `width`. The `width` must be <= 6.
  4010. var leadingZeroes = "000000";
  4011. var toPaddedString = function (width, value) {
  4012. // The `|| 0` expression is necessary to work around a bug in
  4013. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  4014. return (leadingZeroes + (value || 0)).slice(-width);
  4015. };
  4016. // Internal: Double-quotes a string `value`, replacing all ASCII control
  4017. // characters (characters with code unit values between 0 and 31) with
  4018. // their escaped equivalents. This is an implementation of the
  4019. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  4020. var unicodePrefix = "\\u00";
  4021. var quote = function (value) {
  4022. var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
  4023. var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
  4024. for (; index < length; index++) {
  4025. var charCode = value.charCodeAt(index);
  4026. // If the character is a control character, append its Unicode or
  4027. // shorthand escape sequence; otherwise, append the character as-is.
  4028. switch (charCode) {
  4029. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  4030. result += Escapes[charCode];
  4031. break;
  4032. default:
  4033. if (charCode < 32) {
  4034. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  4035. break;
  4036. }
  4037. result += useCharIndex ? symbols[index] : value.charAt(index);
  4038. }
  4039. }
  4040. return result + '"';
  4041. };
  4042. // Internal: Recursively serializes an object. Implements the
  4043. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  4044. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  4045. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  4046. try {
  4047. // Necessary for host object support.
  4048. value = object[property];
  4049. } catch (exception) {}
  4050. if (typeof value == "object" && value) {
  4051. className = getClass.call(value);
  4052. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  4053. if (value > -1 / 0 && value < 1 / 0) {
  4054. // Dates are serialized according to the `Date#toJSON` method
  4055. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  4056. // for the ISO 8601 date time string format.
  4057. if (getDay) {
  4058. // Manually compute the year, month, date, hours, minutes,
  4059. // seconds, and milliseconds if the `getUTC*` methods are
  4060. // buggy. Adapted from @Yaffle's `date-shim` project.
  4061. date = floor(value / 864e5);
  4062. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  4063. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  4064. date = 1 + date - getDay(year, month);
  4065. // The `time` value specifies the time within the day (see ES
  4066. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  4067. // to compute `A modulo B`, as the `%` operator does not
  4068. // correspond to the `modulo` operation for negative numbers.
  4069. time = (value % 864e5 + 864e5) % 864e5;
  4070. // The hours, minutes, seconds, and milliseconds are obtained by
  4071. // decomposing the time within the day. See section 15.9.1.10.
  4072. hours = floor(time / 36e5) % 24;
  4073. minutes = floor(time / 6e4) % 60;
  4074. seconds = floor(time / 1e3) % 60;
  4075. milliseconds = time % 1e3;
  4076. } else {
  4077. year = value.getUTCFullYear();
  4078. month = value.getUTCMonth();
  4079. date = value.getUTCDate();
  4080. hours = value.getUTCHours();
  4081. minutes = value.getUTCMinutes();
  4082. seconds = value.getUTCSeconds();
  4083. milliseconds = value.getUTCMilliseconds();
  4084. }
  4085. // Serialize extended years correctly.
  4086. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  4087. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  4088. // Months, dates, hours, minutes, and seconds should have two
  4089. // digits; milliseconds should have three.
  4090. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  4091. // Milliseconds are optional in ES 5.0, but required in 5.1.
  4092. "." + toPaddedString(3, milliseconds) + "Z";
  4093. } else {
  4094. value = null;
  4095. }
  4096. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  4097. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  4098. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  4099. // ignores all `toJSON` methods on these objects unless they are
  4100. // defined directly on an instance.
  4101. value = value.toJSON(property);
  4102. }
  4103. }
  4104. if (callback) {
  4105. // If a replacement function was provided, call it to obtain the value
  4106. // for serialization.
  4107. value = callback.call(object, property, value);
  4108. }
  4109. if (value === null) {
  4110. return "null";
  4111. }
  4112. className = getClass.call(value);
  4113. if (className == booleanClass) {
  4114. // Booleans are represented literally.
  4115. return "" + value;
  4116. } else if (className == numberClass) {
  4117. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  4118. // `"null"`.
  4119. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  4120. } else if (className == stringClass) {
  4121. // Strings are double-quoted and escaped.
  4122. return quote("" + value);
  4123. }
  4124. // Recursively serialize objects and arrays.
  4125. if (typeof value == "object") {
  4126. // Check for cyclic structures. This is a linear search; performance
  4127. // is inversely proportional to the number of unique nested objects.
  4128. for (length = stack.length; length--;) {
  4129. if (stack[length] === value) {
  4130. // Cyclic structures cannot be serialized by `JSON.stringify`.
  4131. throw TypeError();
  4132. }
  4133. }
  4134. // Add the object to the stack of traversed objects.
  4135. stack.push(value);
  4136. results = [];
  4137. // Save the current indentation level and indent one additional level.
  4138. prefix = indentation;
  4139. indentation += whitespace;
  4140. if (className == arrayClass) {
  4141. // Recursively serialize array elements.
  4142. for (index = 0, length = value.length; index < length; index++) {
  4143. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  4144. results.push(element === undef ? "null" : element);
  4145. }
  4146. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  4147. } else {
  4148. // Recursively serialize object members. Members are selected from
  4149. // either a user-specified list of property names, or the object
  4150. // itself.
  4151. forEach(properties || value, function (property) {
  4152. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  4153. if (element !== undef) {
  4154. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  4155. // is not the empty string, let `member` {quote(property) + ":"}
  4156. // be the concatenation of `member` and the `space` character."
  4157. // The "`space` character" refers to the literal space
  4158. // character, not the `space` {width} argument provided to
  4159. // `JSON.stringify`.
  4160. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  4161. }
  4162. });
  4163. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  4164. }
  4165. // Remove the object from the traversed object stack.
  4166. stack.pop();
  4167. return result;
  4168. }
  4169. };
  4170. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  4171. exports.stringify = function (source, filter, width) {
  4172. var whitespace, callback, properties, className;
  4173. if (objectTypes[typeof filter] && filter) {
  4174. if ((className = getClass.call(filter)) == functionClass) {
  4175. callback = filter;
  4176. } else if (className == arrayClass) {
  4177. // Convert the property names array into a makeshift set.
  4178. properties = {};
  4179. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  4180. }
  4181. }
  4182. if (width) {
  4183. if ((className = getClass.call(width)) == numberClass) {
  4184. // Convert the `width` to an integer and create a string containing
  4185. // `width` number of space characters.
  4186. if ((width -= width % 1) > 0) {
  4187. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  4188. }
  4189. } else if (className == stringClass) {
  4190. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  4191. }
  4192. }
  4193. // Opera <= 7.54u2 discards the values associated with empty string keys
  4194. // (`""`) only if they are used directly within an object member list
  4195. // (e.g., `!("" in { "": 1})`).
  4196. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  4197. };
  4198. }
  4199. // Public: Parses a JSON source string.
  4200. if (!has("json-parse")) {
  4201. var fromCharCode = String.fromCharCode;
  4202. // Internal: A map of escaped control characters and their unescaped
  4203. // equivalents.
  4204. var Unescapes = {
  4205. 92: "\\",
  4206. 34: '"',
  4207. 47: "/",
  4208. 98: "\b",
  4209. 116: "\t",
  4210. 110: "\n",
  4211. 102: "\f",
  4212. 114: "\r"
  4213. };
  4214. // Internal: Stores the parser state.
  4215. var Index, Source;
  4216. // Internal: Resets the parser state and throws a `SyntaxError`.
  4217. var abort = function () {
  4218. Index = Source = null;
  4219. throw SyntaxError();
  4220. };
  4221. // Internal: Returns the next token, or `"$"` if the parser has reached
  4222. // the end of the source string. A token may be a string, number, `null`
  4223. // literal, or Boolean literal.
  4224. var lex = function () {
  4225. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  4226. while (Index < length) {
  4227. charCode = source.charCodeAt(Index);
  4228. switch (charCode) {
  4229. case 9: case 10: case 13: case 32:
  4230. // Skip whitespace tokens, including tabs, carriage returns, line
  4231. // feeds, and space characters.
  4232. Index++;
  4233. break;
  4234. case 123: case 125: case 91: case 93: case 58: case 44:
  4235. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  4236. // the current position.
  4237. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  4238. Index++;
  4239. return value;
  4240. case 34:
  4241. // `"` delimits a JSON string; advance to the next character and
  4242. // begin parsing the string. String tokens are prefixed with the
  4243. // sentinel `@` character to distinguish them from punctuators and
  4244. // end-of-string tokens.
  4245. for (value = "@", Index++; Index < length;) {
  4246. charCode = source.charCodeAt(Index);
  4247. if (charCode < 32) {
  4248. // Unescaped ASCII control characters (those with a code unit
  4249. // less than the space character) are not permitted.
  4250. abort();
  4251. } else if (charCode == 92) {
  4252. // A reverse solidus (`\`) marks the beginning of an escaped
  4253. // control character (including `"`, `\`, and `/`) or Unicode
  4254. // escape sequence.
  4255. charCode = source.charCodeAt(++Index);
  4256. switch (charCode) {
  4257. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  4258. // Revive escaped control characters.
  4259. value += Unescapes[charCode];
  4260. Index++;
  4261. break;
  4262. case 117:
  4263. // `\u` marks the beginning of a Unicode escape sequence.
  4264. // Advance to the first character and validate the
  4265. // four-digit code point.
  4266. begin = ++Index;
  4267. for (position = Index + 4; Index < position; Index++) {
  4268. charCode = source.charCodeAt(Index);
  4269. // A valid sequence comprises four hexdigits (case-
  4270. // insensitive) that form a single hexadecimal value.
  4271. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  4272. // Invalid Unicode escape sequence.
  4273. abort();
  4274. }
  4275. }
  4276. // Revive the escaped character.
  4277. value += fromCharCode("0x" + source.slice(begin, Index));
  4278. break;
  4279. default:
  4280. // Invalid escape sequence.
  4281. abort();
  4282. }
  4283. } else {
  4284. if (charCode == 34) {
  4285. // An unescaped double-quote character marks the end of the
  4286. // string.
  4287. break;
  4288. }
  4289. charCode = source.charCodeAt(Index);
  4290. begin = Index;
  4291. // Optimize for the common case where a string is valid.
  4292. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  4293. charCode = source.charCodeAt(++Index);
  4294. }
  4295. // Append the string as-is.
  4296. value += source.slice(begin, Index);
  4297. }
  4298. }
  4299. if (source.charCodeAt(Index) == 34) {
  4300. // Advance to the next character and return the revived string.
  4301. Index++;
  4302. return value;
  4303. }
  4304. // Unterminated string.
  4305. abort();
  4306. default:
  4307. // Parse numbers and literals.
  4308. begin = Index;
  4309. // Advance past the negative sign, if one is specified.
  4310. if (charCode == 45) {
  4311. isSigned = true;
  4312. charCode = source.charCodeAt(++Index);
  4313. }
  4314. // Parse an integer or floating-point value.
  4315. if (charCode >= 48 && charCode <= 57) {
  4316. // Leading zeroes are interpreted as octal literals.
  4317. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  4318. // Illegal octal literal.
  4319. abort();
  4320. }
  4321. isSigned = false;
  4322. // Parse the integer component.
  4323. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  4324. // Floats cannot contain a leading decimal point; however, this
  4325. // case is already accounted for by the parser.
  4326. if (source.charCodeAt(Index) == 46) {
  4327. position = ++Index;
  4328. // Parse the decimal component.
  4329. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  4330. if (position == Index) {
  4331. // Illegal trailing decimal.
  4332. abort();
  4333. }
  4334. Index = position;
  4335. }
  4336. // Parse exponents. The `e` denoting the exponent is
  4337. // case-insensitive.
  4338. charCode = source.charCodeAt(Index);
  4339. if (charCode == 101 || charCode == 69) {
  4340. charCode = source.charCodeAt(++Index);
  4341. // Skip past the sign following the exponent, if one is
  4342. // specified.
  4343. if (charCode == 43 || charCode == 45) {
  4344. Index++;
  4345. }
  4346. // Parse the exponential component.
  4347. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  4348. if (position == Index) {
  4349. // Illegal empty exponent.
  4350. abort();
  4351. }
  4352. Index = position;
  4353. }
  4354. // Coerce the parsed value to a JavaScript number.
  4355. return +source.slice(begin, Index);
  4356. }
  4357. // A negative sign may only precede numbers.
  4358. if (isSigned) {
  4359. abort();
  4360. }
  4361. // `true`, `false`, and `null` literals.
  4362. if (source.slice(Index, Index + 4) == "true") {
  4363. Index += 4;
  4364. return true;
  4365. } else if (source.slice(Index, Index + 5) == "false") {
  4366. Index += 5;
  4367. return false;
  4368. } else if (source.slice(Index, Index + 4) == "null") {
  4369. Index += 4;
  4370. return null;
  4371. }
  4372. // Unrecognized token.
  4373. abort();
  4374. }
  4375. }
  4376. // Return the sentinel `$` character if the parser has reached the end
  4377. // of the source string.
  4378. return "$";
  4379. };
  4380. // Internal: Parses a JSON `value` token.
  4381. var get = function (value) {
  4382. var results, hasMembers;
  4383. if (value == "$") {
  4384. // Unexpected end of input.
  4385. abort();
  4386. }
  4387. if (typeof value == "string") {
  4388. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  4389. // Remove the sentinel `@` character.
  4390. return value.slice(1);
  4391. }
  4392. // Parse object and array literals.
  4393. if (value == "[") {
  4394. // Parses a JSON array, returning a new JavaScript array.
  4395. results = [];
  4396. for (;; hasMembers || (hasMembers = true)) {
  4397. value = lex();
  4398. // A closing square bracket marks the end of the array literal.
  4399. if (value == "]") {
  4400. break;
  4401. }
  4402. // If the array literal contains elements, the current token
  4403. // should be a comma separating the previous element from the
  4404. // next.
  4405. if (hasMembers) {
  4406. if (value == ",") {
  4407. value = lex();
  4408. if (value == "]") {
  4409. // Unexpected trailing `,` in array literal.
  4410. abort();
  4411. }
  4412. } else {
  4413. // A `,` must separate each array element.
  4414. abort();
  4415. }
  4416. }
  4417. // Elisions and leading commas are not permitted.
  4418. if (value == ",") {
  4419. abort();
  4420. }
  4421. results.push(get(value));
  4422. }
  4423. return results;
  4424. } else if (value == "{") {
  4425. // Parses a JSON object, returning a new JavaScript object.
  4426. results = {};
  4427. for (;; hasMembers || (hasMembers = true)) {
  4428. value = lex();
  4429. // A closing curly brace marks the end of the object literal.
  4430. if (value == "}") {
  4431. break;
  4432. }
  4433. // If the object literal contains members, the current token
  4434. // should be a comma separator.
  4435. if (hasMembers) {
  4436. if (value == ",") {
  4437. value = lex();
  4438. if (value == "}") {
  4439. // Unexpected trailing `,` in object literal.
  4440. abort();
  4441. }
  4442. } else {
  4443. // A `,` must separate each object member.
  4444. abort();
  4445. }
  4446. }
  4447. // Leading commas are not permitted, object property names must be
  4448. // double-quoted strings, and a `:` must separate each property
  4449. // name and value.
  4450. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  4451. abort();
  4452. }
  4453. results[value.slice(1)] = get(lex());
  4454. }
  4455. return results;
  4456. }
  4457. // Unexpected token encountered.
  4458. abort();
  4459. }
  4460. return value;
  4461. };
  4462. // Internal: Updates a traversed object member.
  4463. var update = function (source, property, callback) {
  4464. var element = walk(source, property, callback);
  4465. if (element === undef) {
  4466. delete source[property];
  4467. } else {
  4468. source[property] = element;
  4469. }
  4470. };
  4471. // Internal: Recursively traverses a parsed JSON object, invoking the
  4472. // `callback` function for each value. This is an implementation of the
  4473. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  4474. var walk = function (source, property, callback) {
  4475. var value = source[property], length;
  4476. if (typeof value == "object" && value) {
  4477. // `forEach` can't be used to traverse an array in Opera <= 8.54
  4478. // because its `Object#hasOwnProperty` implementation returns `false`
  4479. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  4480. if (getClass.call(value) == arrayClass) {
  4481. for (length = value.length; length--;) {
  4482. update(value, length, callback);
  4483. }
  4484. } else {
  4485. forEach(value, function (property) {
  4486. update(value, property, callback);
  4487. });
  4488. }
  4489. }
  4490. return callback.call(source, property, value);
  4491. };
  4492. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  4493. exports.parse = function (source, callback) {
  4494. var result, value;
  4495. Index = 0;
  4496. Source = "" + source;
  4497. result = get(lex());
  4498. // If a JSON string contains multiple tokens, it is invalid.
  4499. if (lex() != "$") {
  4500. abort();
  4501. }
  4502. // Reset the parser state.
  4503. Index = Source = null;
  4504. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  4505. };
  4506. }
  4507. }
  4508. exports["runInContext"] = runInContext;
  4509. return exports;
  4510. }
  4511. if (freeExports && !isLoader) {
  4512. // Export for CommonJS environments.
  4513. runInContext(root, freeExports);
  4514. } else {
  4515. // Export for web browsers and JavaScript engines.
  4516. var nativeJSON = root.JSON,
  4517. previousJSON = root["JSON3"],
  4518. isRestored = false;
  4519. var JSON3 = runInContext(root, (root["JSON3"] = {
  4520. // Public: Restores the original value of the global `JSON` object and
  4521. // returns a reference to the `JSON3` object.
  4522. "noConflict": function () {
  4523. if (!isRestored) {
  4524. isRestored = true;
  4525. root.JSON = nativeJSON;
  4526. root["JSON3"] = previousJSON;
  4527. nativeJSON = previousJSON = null;
  4528. }
  4529. return JSON3;
  4530. }
  4531. }));
  4532. root.JSON = {
  4533. "parse": JSON3.parse,
  4534. "stringify": JSON3.stringify
  4535. };
  4536. }
  4537. // Export for asynchronous module loaders.
  4538. if (isLoader) {
  4539. define(function () {
  4540. return JSON3;
  4541. });
  4542. }
  4543. }).call(this);
  4544. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4545. },{}],59:[function(require,module,exports){
  4546. 'use strict';
  4547. var has = Object.prototype.hasOwnProperty;
  4548. /**
  4549. * Decode a URI encoded string.
  4550. *
  4551. * @param {String} input The URI encoded string.
  4552. * @returns {String} The decoded string.
  4553. * @api private
  4554. */
  4555. function decode(input) {
  4556. return decodeURIComponent(input.replace(/\+/g, ' '));
  4557. }
  4558. /**
  4559. * Simple query string parser.
  4560. *
  4561. * @param {String} query The query string that needs to be parsed.
  4562. * @returns {Object}
  4563. * @api public
  4564. */
  4565. function querystring(query) {
  4566. var parser = /([^=?&]+)=?([^&]*)/g
  4567. , result = {}
  4568. , part;
  4569. while (part = parser.exec(query)) {
  4570. var key = decode(part[1])
  4571. , value = decode(part[2]);
  4572. //
  4573. // Prevent overriding of existing properties. This ensures that build-in
  4574. // methods like `toString` or __proto__ are not overriden by malicious
  4575. // querystrings.
  4576. //
  4577. if (key in result) continue;
  4578. result[key] = value;
  4579. }
  4580. return result;
  4581. }
  4582. /**
  4583. * Transform a query string to an object.
  4584. *
  4585. * @param {Object} obj Object that should be transformed.
  4586. * @param {String} prefix Optional prefix.
  4587. * @returns {String}
  4588. * @api public
  4589. */
  4590. function querystringify(obj, prefix) {
  4591. prefix = prefix || '';
  4592. var pairs = [];
  4593. //
  4594. // Optionally prefix with a '?' if needed
  4595. //
  4596. if ('string' !== typeof prefix) prefix = '?';
  4597. for (var key in obj) {
  4598. if (has.call(obj, key)) {
  4599. pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key]));
  4600. }
  4601. }
  4602. return pairs.length ? prefix + pairs.join('&') : '';
  4603. }
  4604. //
  4605. // Expose the module.
  4606. //
  4607. exports.stringify = querystringify;
  4608. exports.parse = querystring;
  4609. },{}],60:[function(require,module,exports){
  4610. 'use strict';
  4611. /**
  4612. * Check if we're required to add a port number.
  4613. *
  4614. * @see https://url.spec.whatwg.org/#default-port
  4615. * @param {Number|String} port Port number we need to check
  4616. * @param {String} protocol Protocol we need to check against.
  4617. * @returns {Boolean} Is it a default port for the given protocol
  4618. * @api private
  4619. */
  4620. module.exports = function required(port, protocol) {
  4621. protocol = protocol.split(':')[0];
  4622. port = +port;
  4623. if (!port) return false;
  4624. switch (protocol) {
  4625. case 'http':
  4626. case 'ws':
  4627. return port !== 80;
  4628. case 'https':
  4629. case 'wss':
  4630. return port !== 443;
  4631. case 'ftp':
  4632. return port !== 21;
  4633. case 'gopher':
  4634. return port !== 70;
  4635. case 'file':
  4636. return false;
  4637. }
  4638. return port !== 0;
  4639. };
  4640. },{}],61:[function(require,module,exports){
  4641. (function (global){
  4642. 'use strict';
  4643. var required = require('requires-port')
  4644. , qs = require('querystringify')
  4645. , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i
  4646. , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//;
  4647. /**
  4648. * These are the parse rules for the URL parser, it informs the parser
  4649. * about:
  4650. *
  4651. * 0. The char it Needs to parse, if it's a string it should be done using
  4652. * indexOf, RegExp using exec and NaN means set as current value.
  4653. * 1. The property we should set when parsing this value.
  4654. * 2. Indication if it's backwards or forward parsing, when set as number it's
  4655. * the value of extra chars that should be split off.
  4656. * 3. Inherit from location if non existing in the parser.
  4657. * 4. `toLowerCase` the resulting value.
  4658. */
  4659. var rules = [
  4660. ['#', 'hash'], // Extract from the back.
  4661. ['?', 'query'], // Extract from the back.
  4662. function sanitize(address) { // Sanitize what is left of the address
  4663. return address.replace('\\', '/');
  4664. },
  4665. ['/', 'pathname'], // Extract from the back.
  4666. ['@', 'auth', 1], // Extract from the front.
  4667. [NaN, 'host', undefined, 1, 1], // Set left over value.
  4668. [/:(\d+)$/, 'port', undefined, 1], // RegExp the back.
  4669. [NaN, 'hostname', undefined, 1, 1] // Set left over.
  4670. ];
  4671. /**
  4672. * These properties should not be copied or inherited from. This is only needed
  4673. * for all non blob URL's as a blob URL does not include a hash, only the
  4674. * origin.
  4675. *
  4676. * @type {Object}
  4677. * @private
  4678. */
  4679. var ignore = { hash: 1, query: 1 };
  4680. /**
  4681. * The location object differs when your code is loaded through a normal page,
  4682. * Worker or through a worker using a blob. And with the blobble begins the
  4683. * trouble as the location object will contain the URL of the blob, not the
  4684. * location of the page where our code is loaded in. The actual origin is
  4685. * encoded in the `pathname` so we can thankfully generate a good "default"
  4686. * location from it so we can generate proper relative URL's again.
  4687. *
  4688. * @param {Object|String} loc Optional default location object.
  4689. * @returns {Object} lolcation object.
  4690. * @public
  4691. */
  4692. function lolcation(loc) {
  4693. var location = global && global.location || {};
  4694. loc = loc || location;
  4695. var finaldestination = {}
  4696. , type = typeof loc
  4697. , key;
  4698. if ('blob:' === loc.protocol) {
  4699. finaldestination = new Url(unescape(loc.pathname), {});
  4700. } else if ('string' === type) {
  4701. finaldestination = new Url(loc, {});
  4702. for (key in ignore) delete finaldestination[key];
  4703. } else if ('object' === type) {
  4704. for (key in loc) {
  4705. if (key in ignore) continue;
  4706. finaldestination[key] = loc[key];
  4707. }
  4708. if (finaldestination.slashes === undefined) {
  4709. finaldestination.slashes = slashes.test(loc.href);
  4710. }
  4711. }
  4712. return finaldestination;
  4713. }
  4714. /**
  4715. * @typedef ProtocolExtract
  4716. * @type Object
  4717. * @property {String} protocol Protocol matched in the URL, in lowercase.
  4718. * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
  4719. * @property {String} rest Rest of the URL that is not part of the protocol.
  4720. */
  4721. /**
  4722. * Extract protocol information from a URL with/without double slash ("//").
  4723. *
  4724. * @param {String} address URL we want to extract from.
  4725. * @return {ProtocolExtract} Extracted information.
  4726. * @private
  4727. */
  4728. function extractProtocol(address) {
  4729. var match = protocolre.exec(address);
  4730. return {
  4731. protocol: match[1] ? match[1].toLowerCase() : '',
  4732. slashes: !!match[2],
  4733. rest: match[3]
  4734. };
  4735. }
  4736. /**
  4737. * Resolve a relative URL pathname against a base URL pathname.
  4738. *
  4739. * @param {String} relative Pathname of the relative URL.
  4740. * @param {String} base Pathname of the base URL.
  4741. * @return {String} Resolved pathname.
  4742. * @private
  4743. */
  4744. function resolve(relative, base) {
  4745. var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
  4746. , i = path.length
  4747. , last = path[i - 1]
  4748. , unshift = false
  4749. , up = 0;
  4750. while (i--) {
  4751. if (path[i] === '.') {
  4752. path.splice(i, 1);
  4753. } else if (path[i] === '..') {
  4754. path.splice(i, 1);
  4755. up++;
  4756. } else if (up) {
  4757. if (i === 0) unshift = true;
  4758. path.splice(i, 1);
  4759. up--;
  4760. }
  4761. }
  4762. if (unshift) path.unshift('');
  4763. if (last === '.' || last === '..') path.push('');
  4764. return path.join('/');
  4765. }
  4766. /**
  4767. * The actual URL instance. Instead of returning an object we've opted-in to
  4768. * create an actual constructor as it's much more memory efficient and
  4769. * faster and it pleases my OCD.
  4770. *
  4771. * It is worth noting that we should not use `URL` as class name to prevent
  4772. * clashes with the global URL instance that got introduced in browsers.
  4773. *
  4774. * @constructor
  4775. * @param {String} address URL we want to parse.
  4776. * @param {Object|String} location Location defaults for relative paths.
  4777. * @param {Boolean|Function} parser Parser for the query string.
  4778. * @private
  4779. */
  4780. function Url(address, location, parser) {
  4781. if (!(this instanceof Url)) {
  4782. return new Url(address, location, parser);
  4783. }
  4784. var relative, extracted, parse, instruction, index, key
  4785. , instructions = rules.slice()
  4786. , type = typeof location
  4787. , url = this
  4788. , i = 0;
  4789. //
  4790. // The following if statements allows this module two have compatibility with
  4791. // 2 different API:
  4792. //
  4793. // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  4794. // where the boolean indicates that the query string should also be parsed.
  4795. //
  4796. // 2. The `URL` interface of the browser which accepts a URL, object as
  4797. // arguments. The supplied object will be used as default values / fall-back
  4798. // for relative paths.
  4799. //
  4800. if ('object' !== type && 'string' !== type) {
  4801. parser = location;
  4802. location = null;
  4803. }
  4804. if (parser && 'function' !== typeof parser) parser = qs.parse;
  4805. location = lolcation(location);
  4806. //
  4807. // Extract protocol information before running the instructions.
  4808. //
  4809. extracted = extractProtocol(address || '');
  4810. relative = !extracted.protocol && !extracted.slashes;
  4811. url.slashes = extracted.slashes || relative && location.slashes;
  4812. url.protocol = extracted.protocol || location.protocol || '';
  4813. address = extracted.rest;
  4814. //
  4815. // When the authority component is absent the URL starts with a path
  4816. // component.
  4817. //
  4818. if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname'];
  4819. for (; i < instructions.length; i++) {
  4820. instruction = instructions[i];
  4821. if (typeof instruction === 'function') {
  4822. address = instruction(address);
  4823. continue;
  4824. }
  4825. parse = instruction[0];
  4826. key = instruction[1];
  4827. if (parse !== parse) {
  4828. url[key] = address;
  4829. } else if ('string' === typeof parse) {
  4830. if (~(index = address.indexOf(parse))) {
  4831. if ('number' === typeof instruction[2]) {
  4832. url[key] = address.slice(0, index);
  4833. address = address.slice(index + instruction[2]);
  4834. } else {
  4835. url[key] = address.slice(index);
  4836. address = address.slice(0, index);
  4837. }
  4838. }
  4839. } else if ((index = parse.exec(address))) {
  4840. url[key] = index[1];
  4841. address = address.slice(0, index.index);
  4842. }
  4843. url[key] = url[key] || (
  4844. relative && instruction[3] ? location[key] || '' : ''
  4845. );
  4846. //
  4847. // Hostname, host and protocol should be lowercased so they can be used to
  4848. // create a proper `origin`.
  4849. //
  4850. if (instruction[4]) url[key] = url[key].toLowerCase();
  4851. }
  4852. //
  4853. // Also parse the supplied query string in to an object. If we're supplied
  4854. // with a custom parser as function use that instead of the default build-in
  4855. // parser.
  4856. //
  4857. if (parser) url.query = parser(url.query);
  4858. //
  4859. // If the URL is relative, resolve the pathname against the base URL.
  4860. //
  4861. if (
  4862. relative
  4863. && location.slashes
  4864. && url.pathname.charAt(0) !== '/'
  4865. && (url.pathname !== '' || location.pathname !== '')
  4866. ) {
  4867. url.pathname = resolve(url.pathname, location.pathname);
  4868. }
  4869. //
  4870. // We should not add port numbers if they are already the default port number
  4871. // for a given protocol. As the host also contains the port number we're going
  4872. // override it with the hostname which contains no port number.
  4873. //
  4874. if (!required(url.port, url.protocol)) {
  4875. url.host = url.hostname;
  4876. url.port = '';
  4877. }
  4878. //
  4879. // Parse down the `auth` for the username and password.
  4880. //
  4881. url.username = url.password = '';
  4882. if (url.auth) {
  4883. instruction = url.auth.split(':');
  4884. url.username = instruction[0] || '';
  4885. url.password = instruction[1] || '';
  4886. }
  4887. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  4888. ? url.protocol +'//'+ url.host
  4889. : 'null';
  4890. //
  4891. // The href is just the compiled result.
  4892. //
  4893. url.href = url.toString();
  4894. }
  4895. /**
  4896. * This is convenience method for changing properties in the URL instance to
  4897. * insure that they all propagate correctly.
  4898. *
  4899. * @param {String} part Property we need to adjust.
  4900. * @param {Mixed} value The newly assigned value.
  4901. * @param {Boolean|Function} fn When setting the query, it will be the function
  4902. * used to parse the query.
  4903. * When setting the protocol, double slash will be
  4904. * removed from the final url if it is true.
  4905. * @returns {URL} URL instance for chaining.
  4906. * @public
  4907. */
  4908. function set(part, value, fn) {
  4909. var url = this;
  4910. switch (part) {
  4911. case 'query':
  4912. if ('string' === typeof value && value.length) {
  4913. value = (fn || qs.parse)(value);
  4914. }
  4915. url[part] = value;
  4916. break;
  4917. case 'port':
  4918. url[part] = value;
  4919. if (!required(value, url.protocol)) {
  4920. url.host = url.hostname;
  4921. url[part] = '';
  4922. } else if (value) {
  4923. url.host = url.hostname +':'+ value;
  4924. }
  4925. break;
  4926. case 'hostname':
  4927. url[part] = value;
  4928. if (url.port) value += ':'+ url.port;
  4929. url.host = value;
  4930. break;
  4931. case 'host':
  4932. url[part] = value;
  4933. if (/:\d+$/.test(value)) {
  4934. value = value.split(':');
  4935. url.port = value.pop();
  4936. url.hostname = value.join(':');
  4937. } else {
  4938. url.hostname = value;
  4939. url.port = '';
  4940. }
  4941. break;
  4942. case 'protocol':
  4943. url.protocol = value.toLowerCase();
  4944. url.slashes = !fn;
  4945. break;
  4946. case 'pathname':
  4947. case 'hash':
  4948. if (value) {
  4949. var char = part === 'pathname' ? '/' : '#';
  4950. url[part] = value.charAt(0) !== char ? char + value : value;
  4951. } else {
  4952. url[part] = value;
  4953. }
  4954. break;
  4955. default:
  4956. url[part] = value;
  4957. }
  4958. for (var i = 0; i < rules.length; i++) {
  4959. var ins = rules[i];
  4960. if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
  4961. }
  4962. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  4963. ? url.protocol +'//'+ url.host
  4964. : 'null';
  4965. url.href = url.toString();
  4966. return url;
  4967. }
  4968. /**
  4969. * Transform the properties back in to a valid and full URL string.
  4970. *
  4971. * @param {Function} stringify Optional query stringify function.
  4972. * @returns {String} Compiled version of the URL.
  4973. * @public
  4974. */
  4975. function toString(stringify) {
  4976. if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
  4977. var query
  4978. , url = this
  4979. , protocol = url.protocol;
  4980. if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';
  4981. var result = protocol + (url.slashes ? '//' : '');
  4982. if (url.username) {
  4983. result += url.username;
  4984. if (url.password) result += ':'+ url.password;
  4985. result += '@';
  4986. }
  4987. result += url.host + url.pathname;
  4988. query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  4989. if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
  4990. if (url.hash) result += url.hash;
  4991. return result;
  4992. }
  4993. Url.prototype = { set: set, toString: toString };
  4994. //
  4995. // Expose the URL parser and some additional properties that might be useful for
  4996. // others or testing.
  4997. //
  4998. Url.extractProtocol = extractProtocol;
  4999. Url.location = lolcation;
  5000. Url.qs = qs;
  5001. module.exports = Url;
  5002. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5003. },{"querystringify":59,"requires-port":60}]},{},[1])(1)
  5004. });
  5005. //# sourceMappingURL=sockjs.js.map