sockjs.js 177 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752
  1. /* sockjs-client v1.1.5 | 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":56}],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":56}],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":56}],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":57}],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":54,"json3":57}],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":54,"events":3,"inherits":56,"json3":57}],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":56,"json3":57}],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":54,"events":3,"inherits":56,"json3":57}],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":54,"events":3,"inherits":56}],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":54,"inherits":56,"json3":57,"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":54,"events":3,"inherits":56}],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":56}],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":56}],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":54,"events":3,"inherits":56,"json3":57}],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":56}],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":54,"inherits":56}],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":54,"events":3,"inherits":56}],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":56}],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":54,"events":3,"inherits":56}],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":54,"inherits":56}],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":54,"events":3,"eventsource":18,"inherits":56}],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":54,"events":3,"inherits":56}],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":54,"events":3,"inherits":56}],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":54,"events":3,"inherits":56}],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":54}],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":54,"events":3,"inherits":56}],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":56}],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":56}],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":56}],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":54,"events":3,"inherits":56}],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":56}],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":56}],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":56}],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":56}],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":57}],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":54,"json3":57}],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":54}],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":54,"url-parse":61}],53:[function(require,module,exports){
  3147. module.exports = '1.1.5';
  3148. },{}],54:[function(require,module,exports){
  3149. (function (process){
  3150. /**
  3151. * This is the web browser implementation of `debug()`.
  3152. *
  3153. * Expose `debug()` as the module.
  3154. */
  3155. exports = module.exports = require('./debug');
  3156. exports.log = log;
  3157. exports.formatArgs = formatArgs;
  3158. exports.save = save;
  3159. exports.load = load;
  3160. exports.useColors = useColors;
  3161. exports.storage = 'undefined' != typeof chrome
  3162. && 'undefined' != typeof chrome.storage
  3163. ? chrome.storage.local
  3164. : localstorage();
  3165. /**
  3166. * Colors.
  3167. */
  3168. exports.colors = [
  3169. 'lightseagreen',
  3170. 'forestgreen',
  3171. 'goldenrod',
  3172. 'dodgerblue',
  3173. 'darkorchid',
  3174. 'crimson'
  3175. ];
  3176. /**
  3177. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  3178. * and the Firebug extension (any Firefox version) are known
  3179. * to support "%c" CSS customizations.
  3180. *
  3181. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  3182. */
  3183. function useColors() {
  3184. // NB: In an Electron preload script, document will be defined but not fully
  3185. // initialized. Since we know we're in Chrome, we'll just detect this case
  3186. // explicitly
  3187. if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
  3188. return true;
  3189. }
  3190. // is webkit? http://stackoverflow.com/a/16459606/376773
  3191. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  3192. return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
  3193. // is firebug? http://stackoverflow.com/a/398120/376773
  3194. (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
  3195. // is firefox >= v31?
  3196. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  3197. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
  3198. // double check webkit in userAgent just in case we are in a worker
  3199. (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
  3200. }
  3201. /**
  3202. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  3203. */
  3204. exports.formatters.j = function(v) {
  3205. try {
  3206. return JSON.stringify(v);
  3207. } catch (err) {
  3208. return '[UnexpectedJSONParseError]: ' + err.message;
  3209. }
  3210. };
  3211. /**
  3212. * Colorize log arguments if enabled.
  3213. *
  3214. * @api public
  3215. */
  3216. function formatArgs(args) {
  3217. var useColors = this.useColors;
  3218. args[0] = (useColors ? '%c' : '')
  3219. + this.namespace
  3220. + (useColors ? ' %c' : ' ')
  3221. + args[0]
  3222. + (useColors ? '%c ' : ' ')
  3223. + '+' + exports.humanize(this.diff);
  3224. if (!useColors) return;
  3225. var c = 'color: ' + this.color;
  3226. args.splice(1, 0, c, 'color: inherit')
  3227. // the final "%c" is somewhat tricky, because there could be other
  3228. // arguments passed either before or after the %c, so we need to
  3229. // figure out the correct index to insert the CSS into
  3230. var index = 0;
  3231. var lastC = 0;
  3232. args[0].replace(/%[a-zA-Z%]/g, function(match) {
  3233. if ('%%' === match) return;
  3234. index++;
  3235. if ('%c' === match) {
  3236. // we only are interested in the *last* %c
  3237. // (the user may have provided their own)
  3238. lastC = index;
  3239. }
  3240. });
  3241. args.splice(lastC, 0, c);
  3242. }
  3243. /**
  3244. * Invokes `console.log()` when available.
  3245. * No-op when `console.log` is not a "function".
  3246. *
  3247. * @api public
  3248. */
  3249. function log() {
  3250. // this hackery is required for IE8/9, where
  3251. // the `console.log` function doesn't have 'apply'
  3252. return 'object' === typeof console
  3253. && console.log
  3254. && Function.prototype.apply.call(console.log, console, arguments);
  3255. }
  3256. /**
  3257. * Save `namespaces`.
  3258. *
  3259. * @param {String} namespaces
  3260. * @api private
  3261. */
  3262. function save(namespaces) {
  3263. try {
  3264. if (null == namespaces) {
  3265. exports.storage.removeItem('debug');
  3266. } else {
  3267. exports.storage.debug = namespaces;
  3268. }
  3269. } catch(e) {}
  3270. }
  3271. /**
  3272. * Load `namespaces`.
  3273. *
  3274. * @return {String} returns the previously persisted debug modes
  3275. * @api private
  3276. */
  3277. function load() {
  3278. var r;
  3279. try {
  3280. r = exports.storage.debug;
  3281. } catch(e) {}
  3282. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  3283. if (!r && typeof process !== 'undefined' && 'env' in process) {
  3284. r = process.env.DEBUG;
  3285. }
  3286. return r;
  3287. }
  3288. /**
  3289. * Enable namespaces listed in `localStorage.debug` initially.
  3290. */
  3291. exports.enable(load());
  3292. /**
  3293. * Localstorage attempts to return the localstorage.
  3294. *
  3295. * This is necessary because safari throws
  3296. * when a user disables cookies/localstorage
  3297. * and you attempt to access it.
  3298. *
  3299. * @return {LocalStorage}
  3300. * @api private
  3301. */
  3302. function localstorage() {
  3303. try {
  3304. return window.localStorage;
  3305. } catch (e) {}
  3306. }
  3307. }).call(this,{ env: {} })
  3308. },{"./debug":55}],55:[function(require,module,exports){
  3309. /**
  3310. * This is the common logic for both the Node.js and web browser
  3311. * implementations of `debug()`.
  3312. *
  3313. * Expose `debug()` as the module.
  3314. */
  3315. exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
  3316. exports.coerce = coerce;
  3317. exports.disable = disable;
  3318. exports.enable = enable;
  3319. exports.enabled = enabled;
  3320. exports.humanize = require('ms');
  3321. /**
  3322. * The currently active debug mode names, and names to skip.
  3323. */
  3324. exports.names = [];
  3325. exports.skips = [];
  3326. /**
  3327. * Map of special "%n" handling functions, for the debug "format" argument.
  3328. *
  3329. * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
  3330. */
  3331. exports.formatters = {};
  3332. /**
  3333. * Previous log timestamp.
  3334. */
  3335. var prevTime;
  3336. /**
  3337. * Select a color.
  3338. * @param {String} namespace
  3339. * @return {Number}
  3340. * @api private
  3341. */
  3342. function selectColor(namespace) {
  3343. var hash = 0, i;
  3344. for (i in namespace) {
  3345. hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
  3346. hash |= 0; // Convert to 32bit integer
  3347. }
  3348. return exports.colors[Math.abs(hash) % exports.colors.length];
  3349. }
  3350. /**
  3351. * Create a debugger with the given `namespace`.
  3352. *
  3353. * @param {String} namespace
  3354. * @return {Function}
  3355. * @api public
  3356. */
  3357. function createDebug(namespace) {
  3358. function debug() {
  3359. // disabled?
  3360. if (!debug.enabled) return;
  3361. var self = debug;
  3362. // set `diff` timestamp
  3363. var curr = +new Date();
  3364. var ms = curr - (prevTime || curr);
  3365. self.diff = ms;
  3366. self.prev = prevTime;
  3367. self.curr = curr;
  3368. prevTime = curr;
  3369. // turn the `arguments` into a proper Array
  3370. var args = new Array(arguments.length);
  3371. for (var i = 0; i < args.length; i++) {
  3372. args[i] = arguments[i];
  3373. }
  3374. args[0] = exports.coerce(args[0]);
  3375. if ('string' !== typeof args[0]) {
  3376. // anything else let's inspect with %O
  3377. args.unshift('%O');
  3378. }
  3379. // apply any `formatters` transformations
  3380. var index = 0;
  3381. args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
  3382. // if we encounter an escaped % then don't increase the array index
  3383. if (match === '%%') return match;
  3384. index++;
  3385. var formatter = exports.formatters[format];
  3386. if ('function' === typeof formatter) {
  3387. var val = args[index];
  3388. match = formatter.call(self, val);
  3389. // now we need to remove `args[index]` since it's inlined in the `format`
  3390. args.splice(index, 1);
  3391. index--;
  3392. }
  3393. return match;
  3394. });
  3395. // apply env-specific formatting (colors, etc.)
  3396. exports.formatArgs.call(self, args);
  3397. var logFn = debug.log || exports.log || console.log.bind(console);
  3398. logFn.apply(self, args);
  3399. }
  3400. debug.namespace = namespace;
  3401. debug.enabled = exports.enabled(namespace);
  3402. debug.useColors = exports.useColors();
  3403. debug.color = selectColor(namespace);
  3404. // env-specific initialization logic for debug instances
  3405. if ('function' === typeof exports.init) {
  3406. exports.init(debug);
  3407. }
  3408. return debug;
  3409. }
  3410. /**
  3411. * Enables a debug mode by namespaces. This can include modes
  3412. * separated by a colon and wildcards.
  3413. *
  3414. * @param {String} namespaces
  3415. * @api public
  3416. */
  3417. function enable(namespaces) {
  3418. exports.save(namespaces);
  3419. exports.names = [];
  3420. exports.skips = [];
  3421. var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  3422. var len = split.length;
  3423. for (var i = 0; i < len; i++) {
  3424. if (!split[i]) continue; // ignore empty strings
  3425. namespaces = split[i].replace(/\*/g, '.*?');
  3426. if (namespaces[0] === '-') {
  3427. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  3428. } else {
  3429. exports.names.push(new RegExp('^' + namespaces + '$'));
  3430. }
  3431. }
  3432. }
  3433. /**
  3434. * Disable debug output.
  3435. *
  3436. * @api public
  3437. */
  3438. function disable() {
  3439. exports.enable('');
  3440. }
  3441. /**
  3442. * Returns true if the given mode name is enabled, false otherwise.
  3443. *
  3444. * @param {String} name
  3445. * @return {Boolean}
  3446. * @api public
  3447. */
  3448. function enabled(name) {
  3449. var i, len;
  3450. for (i = 0, len = exports.skips.length; i < len; i++) {
  3451. if (exports.skips[i].test(name)) {
  3452. return false;
  3453. }
  3454. }
  3455. for (i = 0, len = exports.names.length; i < len; i++) {
  3456. if (exports.names[i].test(name)) {
  3457. return true;
  3458. }
  3459. }
  3460. return false;
  3461. }
  3462. /**
  3463. * Coerce `val`.
  3464. *
  3465. * @param {Mixed} val
  3466. * @return {Mixed}
  3467. * @api private
  3468. */
  3469. function coerce(val) {
  3470. if (val instanceof Error) return val.stack || val.message;
  3471. return val;
  3472. }
  3473. },{"ms":58}],56:[function(require,module,exports){
  3474. if (typeof Object.create === 'function') {
  3475. // implementation from standard node.js 'util' module
  3476. module.exports = function inherits(ctor, superCtor) {
  3477. ctor.super_ = superCtor
  3478. ctor.prototype = Object.create(superCtor.prototype, {
  3479. constructor: {
  3480. value: ctor,
  3481. enumerable: false,
  3482. writable: true,
  3483. configurable: true
  3484. }
  3485. });
  3486. };
  3487. } else {
  3488. // old school shim for old browsers
  3489. module.exports = function inherits(ctor, superCtor) {
  3490. ctor.super_ = superCtor
  3491. var TempCtor = function () {}
  3492. TempCtor.prototype = superCtor.prototype
  3493. ctor.prototype = new TempCtor()
  3494. ctor.prototype.constructor = ctor
  3495. }
  3496. }
  3497. },{}],57:[function(require,module,exports){
  3498. (function (global){
  3499. /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
  3500. ;(function () {
  3501. // Detect the `define` function exposed by asynchronous module loaders. The
  3502. // strict `define` check is necessary for compatibility with `r.js`.
  3503. var isLoader = typeof define === "function" && define.amd;
  3504. // A set of types used to distinguish objects from primitives.
  3505. var objectTypes = {
  3506. "function": true,
  3507. "object": true
  3508. };
  3509. // Detect the `exports` object exposed by CommonJS implementations.
  3510. var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
  3511. // Use the `global` object exposed by Node (including Browserify via
  3512. // `insert-module-globals`), Narwhal, and Ringo as the default context,
  3513. // and the `window` object in browsers. Rhino exports a `global` function
  3514. // instead.
  3515. var root = objectTypes[typeof window] && window || this,
  3516. freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
  3517. if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
  3518. root = freeGlobal;
  3519. }
  3520. // Public: Initializes JSON 3 using the given `context` object, attaching the
  3521. // `stringify` and `parse` functions to the specified `exports` object.
  3522. function runInContext(context, exports) {
  3523. context || (context = root["Object"]());
  3524. exports || (exports = root["Object"]());
  3525. // Native constructor aliases.
  3526. var Number = context["Number"] || root["Number"],
  3527. String = context["String"] || root["String"],
  3528. Object = context["Object"] || root["Object"],
  3529. Date = context["Date"] || root["Date"],
  3530. SyntaxError = context["SyntaxError"] || root["SyntaxError"],
  3531. TypeError = context["TypeError"] || root["TypeError"],
  3532. Math = context["Math"] || root["Math"],
  3533. nativeJSON = context["JSON"] || root["JSON"];
  3534. // Delegate to the native `stringify` and `parse` implementations.
  3535. if (typeof nativeJSON == "object" && nativeJSON) {
  3536. exports.stringify = nativeJSON.stringify;
  3537. exports.parse = nativeJSON.parse;
  3538. }
  3539. // Convenience aliases.
  3540. var objectProto = Object.prototype,
  3541. getClass = objectProto.toString,
  3542. isProperty, forEach, undef;
  3543. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  3544. var isExtended = new Date(-3509827334573292);
  3545. try {
  3546. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  3547. // results for certain dates in Opera >= 10.53.
  3548. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  3549. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  3550. // but clips the values returned by the date methods to the range of
  3551. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  3552. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  3553. } catch (exception) {}
  3554. // Internal: Determines whether the native `JSON.stringify` and `parse`
  3555. // implementations are spec-compliant. Based on work by Ken Snyder.
  3556. function has(name) {
  3557. if (has[name] !== undef) {
  3558. // Return cached feature test result.
  3559. return has[name];
  3560. }
  3561. var isSupported;
  3562. if (name == "bug-string-char-index") {
  3563. // IE <= 7 doesn't support accessing string characters using square
  3564. // bracket notation. IE 8 only supports this for primitives.
  3565. isSupported = "a"[0] != "a";
  3566. } else if (name == "json") {
  3567. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  3568. // supported.
  3569. isSupported = has("json-stringify") && has("json-parse");
  3570. } else {
  3571. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  3572. // Test `JSON.stringify`.
  3573. if (name == "json-stringify") {
  3574. var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  3575. if (stringifySupported) {
  3576. // A test function object with a custom `toJSON` method.
  3577. (value = function () {
  3578. return 1;
  3579. }).toJSON = value;
  3580. try {
  3581. stringifySupported =
  3582. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  3583. // primitives as object literals.
  3584. stringify(0) === "0" &&
  3585. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  3586. // literals.
  3587. stringify(new Number()) === "0" &&
  3588. stringify(new String()) == '""' &&
  3589. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  3590. // does not define a canonical JSON representation (this applies to
  3591. // objects with `toJSON` properties as well, *unless* they are nested
  3592. // within an object or array).
  3593. stringify(getClass) === undef &&
  3594. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  3595. // FF 3.1b3 pass this test.
  3596. stringify(undef) === undef &&
  3597. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  3598. // respectively, if the value is omitted entirely.
  3599. stringify() === undef &&
  3600. // FF 3.1b1, 2 throw an error if the given value is not a number,
  3601. // string, array, object, Boolean, or `null` literal. This applies to
  3602. // objects with custom `toJSON` methods as well, unless they are nested
  3603. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  3604. // methods entirely.
  3605. stringify(value) === "1" &&
  3606. stringify([value]) == "[1]" &&
  3607. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  3608. // `"[null]"`.
  3609. stringify([undef]) == "[null]" &&
  3610. // YUI 3.0.0b1 fails to serialize `null` literals.
  3611. stringify(null) == "null" &&
  3612. // FF 3.1b1, 2 halts serialization if an array contains a function:
  3613. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  3614. // elides non-JSON values from objects and arrays, unless they
  3615. // define custom `toJSON` methods.
  3616. stringify([undef, getClass, null]) == "[null,null,null]" &&
  3617. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  3618. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  3619. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  3620. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  3621. stringify(null, value) === "1" &&
  3622. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  3623. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  3624. // serialize extended years.
  3625. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  3626. // The milliseconds are optional in ES 5, but required in 5.1.
  3627. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  3628. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  3629. // four-digit years instead of six-digit years. Credits: @Yaffle.
  3630. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  3631. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  3632. // values less than 1000. Credits: @Yaffle.
  3633. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  3634. } catch (exception) {
  3635. stringifySupported = false;
  3636. }
  3637. }
  3638. isSupported = stringifySupported;
  3639. }
  3640. // Test `JSON.parse`.
  3641. if (name == "json-parse") {
  3642. var parse = exports.parse;
  3643. if (typeof parse == "function") {
  3644. try {
  3645. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  3646. // Conforming implementations should also coerce the initial argument to
  3647. // a string prior to parsing.
  3648. if (parse("0") === 0 && !parse(false)) {
  3649. // Simple parsing test.
  3650. value = parse(serialized);
  3651. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  3652. if (parseSupported) {
  3653. try {
  3654. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  3655. parseSupported = !parse('"\t"');
  3656. } catch (exception) {}
  3657. if (parseSupported) {
  3658. try {
  3659. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  3660. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  3661. // certain octal literals.
  3662. parseSupported = parse("01") !== 1;
  3663. } catch (exception) {}
  3664. }
  3665. if (parseSupported) {
  3666. try {
  3667. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  3668. // points. These environments, along with FF 3.1b1 and 2,
  3669. // also allow trailing commas in JSON objects and arrays.
  3670. parseSupported = parse("1.") !== 1;
  3671. } catch (exception) {}
  3672. }
  3673. }
  3674. }
  3675. } catch (exception) {
  3676. parseSupported = false;
  3677. }
  3678. }
  3679. isSupported = parseSupported;
  3680. }
  3681. }
  3682. return has[name] = !!isSupported;
  3683. }
  3684. if (!has("json")) {
  3685. // Common `[[Class]]` name aliases.
  3686. var functionClass = "[object Function]",
  3687. dateClass = "[object Date]",
  3688. numberClass = "[object Number]",
  3689. stringClass = "[object String]",
  3690. arrayClass = "[object Array]",
  3691. booleanClass = "[object Boolean]";
  3692. // Detect incomplete support for accessing string characters by index.
  3693. var charIndexBuggy = has("bug-string-char-index");
  3694. // Define additional utility methods if the `Date` methods are buggy.
  3695. if (!isExtended) {
  3696. var floor = Math.floor;
  3697. // A mapping between the months of the year and the number of days between
  3698. // January 1st and the first of the respective month.
  3699. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  3700. // Internal: Calculates the number of days between the Unix epoch and the
  3701. // first day of the given month.
  3702. var getDay = function (year, month) {
  3703. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  3704. };
  3705. }
  3706. // Internal: Determines if a property is a direct property of the given
  3707. // object. Delegates to the native `Object#hasOwnProperty` method.
  3708. if (!(isProperty = objectProto.hasOwnProperty)) {
  3709. isProperty = function (property) {
  3710. var members = {}, constructor;
  3711. if ((members.__proto__ = null, members.__proto__ = {
  3712. // The *proto* property cannot be set multiple times in recent
  3713. // versions of Firefox and SeaMonkey.
  3714. "toString": 1
  3715. }, members).toString != getClass) {
  3716. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  3717. // supports the mutable *proto* property.
  3718. isProperty = function (property) {
  3719. // Capture and break the object's prototype chain (see section 8.6.2
  3720. // of the ES 5.1 spec). The parenthesized expression prevents an
  3721. // unsafe transformation by the Closure Compiler.
  3722. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  3723. // Restore the original prototype chain.
  3724. this.__proto__ = original;
  3725. return result;
  3726. };
  3727. } else {
  3728. // Capture a reference to the top-level `Object` constructor.
  3729. constructor = members.constructor;
  3730. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  3731. // other environments.
  3732. isProperty = function (property) {
  3733. var parent = (this.constructor || constructor).prototype;
  3734. return property in this && !(property in parent && this[property] === parent[property]);
  3735. };
  3736. }
  3737. members = null;
  3738. return isProperty.call(this, property);
  3739. };
  3740. }
  3741. // Internal: Normalizes the `for...in` iteration algorithm across
  3742. // environments. Each enumerated key is yielded to a `callback` function.
  3743. forEach = function (object, callback) {
  3744. var size = 0, Properties, members, property;
  3745. // Tests for bugs in the current environment's `for...in` algorithm. The
  3746. // `valueOf` property inherits the non-enumerable flag from
  3747. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  3748. (Properties = function () {
  3749. this.valueOf = 0;
  3750. }).prototype.valueOf = 0;
  3751. // Iterate over a new instance of the `Properties` class.
  3752. members = new Properties();
  3753. for (property in members) {
  3754. // Ignore all properties inherited from `Object.prototype`.
  3755. if (isProperty.call(members, property)) {
  3756. size++;
  3757. }
  3758. }
  3759. Properties = members = null;
  3760. // Normalize the iteration algorithm.
  3761. if (!size) {
  3762. // A list of non-enumerable properties inherited from `Object.prototype`.
  3763. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  3764. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  3765. // properties.
  3766. forEach = function (object, callback) {
  3767. var isFunction = getClass.call(object) == functionClass, property, length;
  3768. var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
  3769. for (property in object) {
  3770. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  3771. // certain conditions; IE does not.
  3772. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  3773. callback(property);
  3774. }
  3775. }
  3776. // Manually invoke the callback for each non-enumerable property.
  3777. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  3778. };
  3779. } else if (size == 2) {
  3780. // Safari <= 2.0.4 enumerates shadowed properties twice.
  3781. forEach = function (object, callback) {
  3782. // Create a set of iterated properties.
  3783. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  3784. for (property in object) {
  3785. // Store each property name to prevent double enumeration. The
  3786. // `prototype` property of functions is not enumerated due to cross-
  3787. // environment inconsistencies.
  3788. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  3789. callback(property);
  3790. }
  3791. }
  3792. };
  3793. } else {
  3794. // No bugs detected; use the standard `for...in` algorithm.
  3795. forEach = function (object, callback) {
  3796. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  3797. for (property in object) {
  3798. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  3799. callback(property);
  3800. }
  3801. }
  3802. // Manually invoke the callback for the `constructor` property due to
  3803. // cross-environment inconsistencies.
  3804. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  3805. callback(property);
  3806. }
  3807. };
  3808. }
  3809. return forEach(object, callback);
  3810. };
  3811. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  3812. // `filter` argument may specify either a function that alters how object and
  3813. // array members are serialized, or an array of strings and numbers that
  3814. // indicates which properties should be serialized. The optional `width`
  3815. // argument may be either a string or number that specifies the indentation
  3816. // level of the output.
  3817. if (!has("json-stringify")) {
  3818. // Internal: A map of control characters and their escaped equivalents.
  3819. var Escapes = {
  3820. 92: "\\\\",
  3821. 34: '\\"',
  3822. 8: "\\b",
  3823. 12: "\\f",
  3824. 10: "\\n",
  3825. 13: "\\r",
  3826. 9: "\\t"
  3827. };
  3828. // Internal: Converts `value` into a zero-padded string such that its
  3829. // length is at least equal to `width`. The `width` must be <= 6.
  3830. var leadingZeroes = "000000";
  3831. var toPaddedString = function (width, value) {
  3832. // The `|| 0` expression is necessary to work around a bug in
  3833. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  3834. return (leadingZeroes + (value || 0)).slice(-width);
  3835. };
  3836. // Internal: Double-quotes a string `value`, replacing all ASCII control
  3837. // characters (characters with code unit values between 0 and 31) with
  3838. // their escaped equivalents. This is an implementation of the
  3839. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  3840. var unicodePrefix = "\\u00";
  3841. var quote = function (value) {
  3842. var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
  3843. var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
  3844. for (; index < length; index++) {
  3845. var charCode = value.charCodeAt(index);
  3846. // If the character is a control character, append its Unicode or
  3847. // shorthand escape sequence; otherwise, append the character as-is.
  3848. switch (charCode) {
  3849. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  3850. result += Escapes[charCode];
  3851. break;
  3852. default:
  3853. if (charCode < 32) {
  3854. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  3855. break;
  3856. }
  3857. result += useCharIndex ? symbols[index] : value.charAt(index);
  3858. }
  3859. }
  3860. return result + '"';
  3861. };
  3862. // Internal: Recursively serializes an object. Implements the
  3863. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  3864. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  3865. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  3866. try {
  3867. // Necessary for host object support.
  3868. value = object[property];
  3869. } catch (exception) {}
  3870. if (typeof value == "object" && value) {
  3871. className = getClass.call(value);
  3872. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  3873. if (value > -1 / 0 && value < 1 / 0) {
  3874. // Dates are serialized according to the `Date#toJSON` method
  3875. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  3876. // for the ISO 8601 date time string format.
  3877. if (getDay) {
  3878. // Manually compute the year, month, date, hours, minutes,
  3879. // seconds, and milliseconds if the `getUTC*` methods are
  3880. // buggy. Adapted from @Yaffle's `date-shim` project.
  3881. date = floor(value / 864e5);
  3882. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  3883. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  3884. date = 1 + date - getDay(year, month);
  3885. // The `time` value specifies the time within the day (see ES
  3886. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  3887. // to compute `A modulo B`, as the `%` operator does not
  3888. // correspond to the `modulo` operation for negative numbers.
  3889. time = (value % 864e5 + 864e5) % 864e5;
  3890. // The hours, minutes, seconds, and milliseconds are obtained by
  3891. // decomposing the time within the day. See section 15.9.1.10.
  3892. hours = floor(time / 36e5) % 24;
  3893. minutes = floor(time / 6e4) % 60;
  3894. seconds = floor(time / 1e3) % 60;
  3895. milliseconds = time % 1e3;
  3896. } else {
  3897. year = value.getUTCFullYear();
  3898. month = value.getUTCMonth();
  3899. date = value.getUTCDate();
  3900. hours = value.getUTCHours();
  3901. minutes = value.getUTCMinutes();
  3902. seconds = value.getUTCSeconds();
  3903. milliseconds = value.getUTCMilliseconds();
  3904. }
  3905. // Serialize extended years correctly.
  3906. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  3907. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  3908. // Months, dates, hours, minutes, and seconds should have two
  3909. // digits; milliseconds should have three.
  3910. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  3911. // Milliseconds are optional in ES 5.0, but required in 5.1.
  3912. "." + toPaddedString(3, milliseconds) + "Z";
  3913. } else {
  3914. value = null;
  3915. }
  3916. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  3917. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  3918. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  3919. // ignores all `toJSON` methods on these objects unless they are
  3920. // defined directly on an instance.
  3921. value = value.toJSON(property);
  3922. }
  3923. }
  3924. if (callback) {
  3925. // If a replacement function was provided, call it to obtain the value
  3926. // for serialization.
  3927. value = callback.call(object, property, value);
  3928. }
  3929. if (value === null) {
  3930. return "null";
  3931. }
  3932. className = getClass.call(value);
  3933. if (className == booleanClass) {
  3934. // Booleans are represented literally.
  3935. return "" + value;
  3936. } else if (className == numberClass) {
  3937. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  3938. // `"null"`.
  3939. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  3940. } else if (className == stringClass) {
  3941. // Strings are double-quoted and escaped.
  3942. return quote("" + value);
  3943. }
  3944. // Recursively serialize objects and arrays.
  3945. if (typeof value == "object") {
  3946. // Check for cyclic structures. This is a linear search; performance
  3947. // is inversely proportional to the number of unique nested objects.
  3948. for (length = stack.length; length--;) {
  3949. if (stack[length] === value) {
  3950. // Cyclic structures cannot be serialized by `JSON.stringify`.
  3951. throw TypeError();
  3952. }
  3953. }
  3954. // Add the object to the stack of traversed objects.
  3955. stack.push(value);
  3956. results = [];
  3957. // Save the current indentation level and indent one additional level.
  3958. prefix = indentation;
  3959. indentation += whitespace;
  3960. if (className == arrayClass) {
  3961. // Recursively serialize array elements.
  3962. for (index = 0, length = value.length; index < length; index++) {
  3963. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  3964. results.push(element === undef ? "null" : element);
  3965. }
  3966. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  3967. } else {
  3968. // Recursively serialize object members. Members are selected from
  3969. // either a user-specified list of property names, or the object
  3970. // itself.
  3971. forEach(properties || value, function (property) {
  3972. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  3973. if (element !== undef) {
  3974. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  3975. // is not the empty string, let `member` {quote(property) + ":"}
  3976. // be the concatenation of `member` and the `space` character."
  3977. // The "`space` character" refers to the literal space
  3978. // character, not the `space` {width} argument provided to
  3979. // `JSON.stringify`.
  3980. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  3981. }
  3982. });
  3983. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  3984. }
  3985. // Remove the object from the traversed object stack.
  3986. stack.pop();
  3987. return result;
  3988. }
  3989. };
  3990. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  3991. exports.stringify = function (source, filter, width) {
  3992. var whitespace, callback, properties, className;
  3993. if (objectTypes[typeof filter] && filter) {
  3994. if ((className = getClass.call(filter)) == functionClass) {
  3995. callback = filter;
  3996. } else if (className == arrayClass) {
  3997. // Convert the property names array into a makeshift set.
  3998. properties = {};
  3999. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  4000. }
  4001. }
  4002. if (width) {
  4003. if ((className = getClass.call(width)) == numberClass) {
  4004. // Convert the `width` to an integer and create a string containing
  4005. // `width` number of space characters.
  4006. if ((width -= width % 1) > 0) {
  4007. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  4008. }
  4009. } else if (className == stringClass) {
  4010. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  4011. }
  4012. }
  4013. // Opera <= 7.54u2 discards the values associated with empty string keys
  4014. // (`""`) only if they are used directly within an object member list
  4015. // (e.g., `!("" in { "": 1})`).
  4016. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  4017. };
  4018. }
  4019. // Public: Parses a JSON source string.
  4020. if (!has("json-parse")) {
  4021. var fromCharCode = String.fromCharCode;
  4022. // Internal: A map of escaped control characters and their unescaped
  4023. // equivalents.
  4024. var Unescapes = {
  4025. 92: "\\",
  4026. 34: '"',
  4027. 47: "/",
  4028. 98: "\b",
  4029. 116: "\t",
  4030. 110: "\n",
  4031. 102: "\f",
  4032. 114: "\r"
  4033. };
  4034. // Internal: Stores the parser state.
  4035. var Index, Source;
  4036. // Internal: Resets the parser state and throws a `SyntaxError`.
  4037. var abort = function () {
  4038. Index = Source = null;
  4039. throw SyntaxError();
  4040. };
  4041. // Internal: Returns the next token, or `"$"` if the parser has reached
  4042. // the end of the source string. A token may be a string, number, `null`
  4043. // literal, or Boolean literal.
  4044. var lex = function () {
  4045. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  4046. while (Index < length) {
  4047. charCode = source.charCodeAt(Index);
  4048. switch (charCode) {
  4049. case 9: case 10: case 13: case 32:
  4050. // Skip whitespace tokens, including tabs, carriage returns, line
  4051. // feeds, and space characters.
  4052. Index++;
  4053. break;
  4054. case 123: case 125: case 91: case 93: case 58: case 44:
  4055. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  4056. // the current position.
  4057. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  4058. Index++;
  4059. return value;
  4060. case 34:
  4061. // `"` delimits a JSON string; advance to the next character and
  4062. // begin parsing the string. String tokens are prefixed with the
  4063. // sentinel `@` character to distinguish them from punctuators and
  4064. // end-of-string tokens.
  4065. for (value = "@", Index++; Index < length;) {
  4066. charCode = source.charCodeAt(Index);
  4067. if (charCode < 32) {
  4068. // Unescaped ASCII control characters (those with a code unit
  4069. // less than the space character) are not permitted.
  4070. abort();
  4071. } else if (charCode == 92) {
  4072. // A reverse solidus (`\`) marks the beginning of an escaped
  4073. // control character (including `"`, `\`, and `/`) or Unicode
  4074. // escape sequence.
  4075. charCode = source.charCodeAt(++Index);
  4076. switch (charCode) {
  4077. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  4078. // Revive escaped control characters.
  4079. value += Unescapes[charCode];
  4080. Index++;
  4081. break;
  4082. case 117:
  4083. // `\u` marks the beginning of a Unicode escape sequence.
  4084. // Advance to the first character and validate the
  4085. // four-digit code point.
  4086. begin = ++Index;
  4087. for (position = Index + 4; Index < position; Index++) {
  4088. charCode = source.charCodeAt(Index);
  4089. // A valid sequence comprises four hexdigits (case-
  4090. // insensitive) that form a single hexadecimal value.
  4091. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  4092. // Invalid Unicode escape sequence.
  4093. abort();
  4094. }
  4095. }
  4096. // Revive the escaped character.
  4097. value += fromCharCode("0x" + source.slice(begin, Index));
  4098. break;
  4099. default:
  4100. // Invalid escape sequence.
  4101. abort();
  4102. }
  4103. } else {
  4104. if (charCode == 34) {
  4105. // An unescaped double-quote character marks the end of the
  4106. // string.
  4107. break;
  4108. }
  4109. charCode = source.charCodeAt(Index);
  4110. begin = Index;
  4111. // Optimize for the common case where a string is valid.
  4112. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  4113. charCode = source.charCodeAt(++Index);
  4114. }
  4115. // Append the string as-is.
  4116. value += source.slice(begin, Index);
  4117. }
  4118. }
  4119. if (source.charCodeAt(Index) == 34) {
  4120. // Advance to the next character and return the revived string.
  4121. Index++;
  4122. return value;
  4123. }
  4124. // Unterminated string.
  4125. abort();
  4126. default:
  4127. // Parse numbers and literals.
  4128. begin = Index;
  4129. // Advance past the negative sign, if one is specified.
  4130. if (charCode == 45) {
  4131. isSigned = true;
  4132. charCode = source.charCodeAt(++Index);
  4133. }
  4134. // Parse an integer or floating-point value.
  4135. if (charCode >= 48 && charCode <= 57) {
  4136. // Leading zeroes are interpreted as octal literals.
  4137. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  4138. // Illegal octal literal.
  4139. abort();
  4140. }
  4141. isSigned = false;
  4142. // Parse the integer component.
  4143. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  4144. // Floats cannot contain a leading decimal point; however, this
  4145. // case is already accounted for by the parser.
  4146. if (source.charCodeAt(Index) == 46) {
  4147. position = ++Index;
  4148. // Parse the decimal component.
  4149. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  4150. if (position == Index) {
  4151. // Illegal trailing decimal.
  4152. abort();
  4153. }
  4154. Index = position;
  4155. }
  4156. // Parse exponents. The `e` denoting the exponent is
  4157. // case-insensitive.
  4158. charCode = source.charCodeAt(Index);
  4159. if (charCode == 101 || charCode == 69) {
  4160. charCode = source.charCodeAt(++Index);
  4161. // Skip past the sign following the exponent, if one is
  4162. // specified.
  4163. if (charCode == 43 || charCode == 45) {
  4164. Index++;
  4165. }
  4166. // Parse the exponential component.
  4167. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  4168. if (position == Index) {
  4169. // Illegal empty exponent.
  4170. abort();
  4171. }
  4172. Index = position;
  4173. }
  4174. // Coerce the parsed value to a JavaScript number.
  4175. return +source.slice(begin, Index);
  4176. }
  4177. // A negative sign may only precede numbers.
  4178. if (isSigned) {
  4179. abort();
  4180. }
  4181. // `true`, `false`, and `null` literals.
  4182. if (source.slice(Index, Index + 4) == "true") {
  4183. Index += 4;
  4184. return true;
  4185. } else if (source.slice(Index, Index + 5) == "false") {
  4186. Index += 5;
  4187. return false;
  4188. } else if (source.slice(Index, Index + 4) == "null") {
  4189. Index += 4;
  4190. return null;
  4191. }
  4192. // Unrecognized token.
  4193. abort();
  4194. }
  4195. }
  4196. // Return the sentinel `$` character if the parser has reached the end
  4197. // of the source string.
  4198. return "$";
  4199. };
  4200. // Internal: Parses a JSON `value` token.
  4201. var get = function (value) {
  4202. var results, hasMembers;
  4203. if (value == "$") {
  4204. // Unexpected end of input.
  4205. abort();
  4206. }
  4207. if (typeof value == "string") {
  4208. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  4209. // Remove the sentinel `@` character.
  4210. return value.slice(1);
  4211. }
  4212. // Parse object and array literals.
  4213. if (value == "[") {
  4214. // Parses a JSON array, returning a new JavaScript array.
  4215. results = [];
  4216. for (;; hasMembers || (hasMembers = true)) {
  4217. value = lex();
  4218. // A closing square bracket marks the end of the array literal.
  4219. if (value == "]") {
  4220. break;
  4221. }
  4222. // If the array literal contains elements, the current token
  4223. // should be a comma separating the previous element from the
  4224. // next.
  4225. if (hasMembers) {
  4226. if (value == ",") {
  4227. value = lex();
  4228. if (value == "]") {
  4229. // Unexpected trailing `,` in array literal.
  4230. abort();
  4231. }
  4232. } else {
  4233. // A `,` must separate each array element.
  4234. abort();
  4235. }
  4236. }
  4237. // Elisions and leading commas are not permitted.
  4238. if (value == ",") {
  4239. abort();
  4240. }
  4241. results.push(get(value));
  4242. }
  4243. return results;
  4244. } else if (value == "{") {
  4245. // Parses a JSON object, returning a new JavaScript object.
  4246. results = {};
  4247. for (;; hasMembers || (hasMembers = true)) {
  4248. value = lex();
  4249. // A closing curly brace marks the end of the object literal.
  4250. if (value == "}") {
  4251. break;
  4252. }
  4253. // If the object literal contains members, the current token
  4254. // should be a comma separator.
  4255. if (hasMembers) {
  4256. if (value == ",") {
  4257. value = lex();
  4258. if (value == "}") {
  4259. // Unexpected trailing `,` in object literal.
  4260. abort();
  4261. }
  4262. } else {
  4263. // A `,` must separate each object member.
  4264. abort();
  4265. }
  4266. }
  4267. // Leading commas are not permitted, object property names must be
  4268. // double-quoted strings, and a `:` must separate each property
  4269. // name and value.
  4270. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  4271. abort();
  4272. }
  4273. results[value.slice(1)] = get(lex());
  4274. }
  4275. return results;
  4276. }
  4277. // Unexpected token encountered.
  4278. abort();
  4279. }
  4280. return value;
  4281. };
  4282. // Internal: Updates a traversed object member.
  4283. var update = function (source, property, callback) {
  4284. var element = walk(source, property, callback);
  4285. if (element === undef) {
  4286. delete source[property];
  4287. } else {
  4288. source[property] = element;
  4289. }
  4290. };
  4291. // Internal: Recursively traverses a parsed JSON object, invoking the
  4292. // `callback` function for each value. This is an implementation of the
  4293. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  4294. var walk = function (source, property, callback) {
  4295. var value = source[property], length;
  4296. if (typeof value == "object" && value) {
  4297. // `forEach` can't be used to traverse an array in Opera <= 8.54
  4298. // because its `Object#hasOwnProperty` implementation returns `false`
  4299. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  4300. if (getClass.call(value) == arrayClass) {
  4301. for (length = value.length; length--;) {
  4302. update(value, length, callback);
  4303. }
  4304. } else {
  4305. forEach(value, function (property) {
  4306. update(value, property, callback);
  4307. });
  4308. }
  4309. }
  4310. return callback.call(source, property, value);
  4311. };
  4312. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  4313. exports.parse = function (source, callback) {
  4314. var result, value;
  4315. Index = 0;
  4316. Source = "" + source;
  4317. result = get(lex());
  4318. // If a JSON string contains multiple tokens, it is invalid.
  4319. if (lex() != "$") {
  4320. abort();
  4321. }
  4322. // Reset the parser state.
  4323. Index = Source = null;
  4324. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  4325. };
  4326. }
  4327. }
  4328. exports["runInContext"] = runInContext;
  4329. return exports;
  4330. }
  4331. if (freeExports && !isLoader) {
  4332. // Export for CommonJS environments.
  4333. runInContext(root, freeExports);
  4334. } else {
  4335. // Export for web browsers and JavaScript engines.
  4336. var nativeJSON = root.JSON,
  4337. previousJSON = root["JSON3"],
  4338. isRestored = false;
  4339. var JSON3 = runInContext(root, (root["JSON3"] = {
  4340. // Public: Restores the original value of the global `JSON` object and
  4341. // returns a reference to the `JSON3` object.
  4342. "noConflict": function () {
  4343. if (!isRestored) {
  4344. isRestored = true;
  4345. root.JSON = nativeJSON;
  4346. root["JSON3"] = previousJSON;
  4347. nativeJSON = previousJSON = null;
  4348. }
  4349. return JSON3;
  4350. }
  4351. }));
  4352. root.JSON = {
  4353. "parse": JSON3.parse,
  4354. "stringify": JSON3.stringify
  4355. };
  4356. }
  4357. // Export for asynchronous module loaders.
  4358. if (isLoader) {
  4359. define(function () {
  4360. return JSON3;
  4361. });
  4362. }
  4363. }).call(this);
  4364. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4365. },{}],58:[function(require,module,exports){
  4366. /**
  4367. * Helpers.
  4368. */
  4369. var s = 1000;
  4370. var m = s * 60;
  4371. var h = m * 60;
  4372. var d = h * 24;
  4373. var y = d * 365.25;
  4374. /**
  4375. * Parse or format the given `val`.
  4376. *
  4377. * Options:
  4378. *
  4379. * - `long` verbose formatting [false]
  4380. *
  4381. * @param {String|Number} val
  4382. * @param {Object} [options]
  4383. * @throws {Error} throw an error if val is not a non-empty string or a number
  4384. * @return {String|Number}
  4385. * @api public
  4386. */
  4387. module.exports = function(val, options) {
  4388. options = options || {};
  4389. var type = typeof val;
  4390. if (type === 'string' && val.length > 0) {
  4391. return parse(val);
  4392. } else if (type === 'number' && isNaN(val) === false) {
  4393. return options.long ? fmtLong(val) : fmtShort(val);
  4394. }
  4395. throw new Error(
  4396. 'val is not a non-empty string or a valid number. val=' +
  4397. JSON.stringify(val)
  4398. );
  4399. };
  4400. /**
  4401. * Parse the given `str` and return milliseconds.
  4402. *
  4403. * @param {String} str
  4404. * @return {Number}
  4405. * @api private
  4406. */
  4407. function parse(str) {
  4408. str = String(str);
  4409. if (str.length > 100) {
  4410. return;
  4411. }
  4412. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
  4413. str
  4414. );
  4415. if (!match) {
  4416. return;
  4417. }
  4418. var n = parseFloat(match[1]);
  4419. var type = (match[2] || 'ms').toLowerCase();
  4420. switch (type) {
  4421. case 'years':
  4422. case 'year':
  4423. case 'yrs':
  4424. case 'yr':
  4425. case 'y':
  4426. return n * y;
  4427. case 'days':
  4428. case 'day':
  4429. case 'd':
  4430. return n * d;
  4431. case 'hours':
  4432. case 'hour':
  4433. case 'hrs':
  4434. case 'hr':
  4435. case 'h':
  4436. return n * h;
  4437. case 'minutes':
  4438. case 'minute':
  4439. case 'mins':
  4440. case 'min':
  4441. case 'm':
  4442. return n * m;
  4443. case 'seconds':
  4444. case 'second':
  4445. case 'secs':
  4446. case 'sec':
  4447. case 's':
  4448. return n * s;
  4449. case 'milliseconds':
  4450. case 'millisecond':
  4451. case 'msecs':
  4452. case 'msec':
  4453. case 'ms':
  4454. return n;
  4455. default:
  4456. return undefined;
  4457. }
  4458. }
  4459. /**
  4460. * Short format for `ms`.
  4461. *
  4462. * @param {Number} ms
  4463. * @return {String}
  4464. * @api private
  4465. */
  4466. function fmtShort(ms) {
  4467. if (ms >= d) {
  4468. return Math.round(ms / d) + 'd';
  4469. }
  4470. if (ms >= h) {
  4471. return Math.round(ms / h) + 'h';
  4472. }
  4473. if (ms >= m) {
  4474. return Math.round(ms / m) + 'm';
  4475. }
  4476. if (ms >= s) {
  4477. return Math.round(ms / s) + 's';
  4478. }
  4479. return ms + 'ms';
  4480. }
  4481. /**
  4482. * Long format for `ms`.
  4483. *
  4484. * @param {Number} ms
  4485. * @return {String}
  4486. * @api private
  4487. */
  4488. function fmtLong(ms) {
  4489. return plural(ms, d, 'day') ||
  4490. plural(ms, h, 'hour') ||
  4491. plural(ms, m, 'minute') ||
  4492. plural(ms, s, 'second') ||
  4493. ms + ' ms';
  4494. }
  4495. /**
  4496. * Pluralization helper.
  4497. */
  4498. function plural(ms, n, name) {
  4499. if (ms < n) {
  4500. return;
  4501. }
  4502. if (ms < n * 1.5) {
  4503. return Math.floor(ms / n) + ' ' + name;
  4504. }
  4505. return Math.ceil(ms / n) + ' ' + name + 's';
  4506. }
  4507. },{}],59:[function(require,module,exports){
  4508. 'use strict';
  4509. var has = Object.prototype.hasOwnProperty;
  4510. /**
  4511. * Decode a URI encoded string.
  4512. *
  4513. * @param {String} input The URI encoded string.
  4514. * @returns {String} The decoded string.
  4515. * @api private
  4516. */
  4517. function decode(input) {
  4518. return decodeURIComponent(input.replace(/\+/g, ' '));
  4519. }
  4520. /**
  4521. * Simple query string parser.
  4522. *
  4523. * @param {String} query The query string that needs to be parsed.
  4524. * @returns {Object}
  4525. * @api public
  4526. */
  4527. function querystring(query) {
  4528. var parser = /([^=?&]+)=?([^&]*)/g
  4529. , result = {}
  4530. , part;
  4531. while (part = parser.exec(query)) {
  4532. var key = decode(part[1])
  4533. , value = decode(part[2]);
  4534. //
  4535. // Prevent overriding of existing properties. This ensures that build-in
  4536. // methods like `toString` or __proto__ are not overriden by malicious
  4537. // querystrings.
  4538. //
  4539. if (key in result) continue;
  4540. result[key] = value;
  4541. }
  4542. return result;
  4543. }
  4544. /**
  4545. * Transform a query string to an object.
  4546. *
  4547. * @param {Object} obj Object that should be transformed.
  4548. * @param {String} prefix Optional prefix.
  4549. * @returns {String}
  4550. * @api public
  4551. */
  4552. function querystringify(obj, prefix) {
  4553. prefix = prefix || '';
  4554. var pairs = [];
  4555. //
  4556. // Optionally prefix with a '?' if needed
  4557. //
  4558. if ('string' !== typeof prefix) prefix = '?';
  4559. for (var key in obj) {
  4560. if (has.call(obj, key)) {
  4561. pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key]));
  4562. }
  4563. }
  4564. return pairs.length ? prefix + pairs.join('&') : '';
  4565. }
  4566. //
  4567. // Expose the module.
  4568. //
  4569. exports.stringify = querystringify;
  4570. exports.parse = querystring;
  4571. },{}],60:[function(require,module,exports){
  4572. 'use strict';
  4573. /**
  4574. * Check if we're required to add a port number.
  4575. *
  4576. * @see https://url.spec.whatwg.org/#default-port
  4577. * @param {Number|String} port Port number we need to check
  4578. * @param {String} protocol Protocol we need to check against.
  4579. * @returns {Boolean} Is it a default port for the given protocol
  4580. * @api private
  4581. */
  4582. module.exports = function required(port, protocol) {
  4583. protocol = protocol.split(':')[0];
  4584. port = +port;
  4585. if (!port) return false;
  4586. switch (protocol) {
  4587. case 'http':
  4588. case 'ws':
  4589. return port !== 80;
  4590. case 'https':
  4591. case 'wss':
  4592. return port !== 443;
  4593. case 'ftp':
  4594. return port !== 21;
  4595. case 'gopher':
  4596. return port !== 70;
  4597. case 'file':
  4598. return false;
  4599. }
  4600. return port !== 0;
  4601. };
  4602. },{}],61:[function(require,module,exports){
  4603. (function (global){
  4604. 'use strict';
  4605. var required = require('requires-port')
  4606. , qs = require('querystringify')
  4607. , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i
  4608. , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//;
  4609. /**
  4610. * These are the parse rules for the URL parser, it informs the parser
  4611. * about:
  4612. *
  4613. * 0. The char it Needs to parse, if it's a string it should be done using
  4614. * indexOf, RegExp using exec and NaN means set as current value.
  4615. * 1. The property we should set when parsing this value.
  4616. * 2. Indication if it's backwards or forward parsing, when set as number it's
  4617. * the value of extra chars that should be split off.
  4618. * 3. Inherit from location if non existing in the parser.
  4619. * 4. `toLowerCase` the resulting value.
  4620. */
  4621. var rules = [
  4622. ['#', 'hash'], // Extract from the back.
  4623. ['?', 'query'], // Extract from the back.
  4624. ['/', 'pathname'], // Extract from the back.
  4625. ['@', 'auth', 1], // Extract from the front.
  4626. [NaN, 'host', undefined, 1, 1], // Set left over value.
  4627. [/:(\d+)$/, 'port', undefined, 1], // RegExp the back.
  4628. [NaN, 'hostname', undefined, 1, 1] // Set left over.
  4629. ];
  4630. /**
  4631. * These properties should not be copied or inherited from. This is only needed
  4632. * for all non blob URL's as a blob URL does not include a hash, only the
  4633. * origin.
  4634. *
  4635. * @type {Object}
  4636. * @private
  4637. */
  4638. var ignore = { hash: 1, query: 1 };
  4639. /**
  4640. * The location object differs when your code is loaded through a normal page,
  4641. * Worker or through a worker using a blob. And with the blobble begins the
  4642. * trouble as the location object will contain the URL of the blob, not the
  4643. * location of the page where our code is loaded in. The actual origin is
  4644. * encoded in the `pathname` so we can thankfully generate a good "default"
  4645. * location from it so we can generate proper relative URL's again.
  4646. *
  4647. * @param {Object|String} loc Optional default location object.
  4648. * @returns {Object} lolcation object.
  4649. * @api public
  4650. */
  4651. function lolcation(loc) {
  4652. loc = loc || global.location || {};
  4653. var finaldestination = {}
  4654. , type = typeof loc
  4655. , key;
  4656. if ('blob:' === loc.protocol) {
  4657. finaldestination = new URL(unescape(loc.pathname), {});
  4658. } else if ('string' === type) {
  4659. finaldestination = new URL(loc, {});
  4660. for (key in ignore) delete finaldestination[key];
  4661. } else if ('object' === type) {
  4662. for (key in loc) {
  4663. if (key in ignore) continue;
  4664. finaldestination[key] = loc[key];
  4665. }
  4666. if (finaldestination.slashes === undefined) {
  4667. finaldestination.slashes = slashes.test(loc.href);
  4668. }
  4669. }
  4670. return finaldestination;
  4671. }
  4672. /**
  4673. * @typedef ProtocolExtract
  4674. * @type Object
  4675. * @property {String} protocol Protocol matched in the URL, in lowercase.
  4676. * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
  4677. * @property {String} rest Rest of the URL that is not part of the protocol.
  4678. */
  4679. /**
  4680. * Extract protocol information from a URL with/without double slash ("//").
  4681. *
  4682. * @param {String} address URL we want to extract from.
  4683. * @return {ProtocolExtract} Extracted information.
  4684. * @api private
  4685. */
  4686. function extractProtocol(address) {
  4687. var match = protocolre.exec(address);
  4688. return {
  4689. protocol: match[1] ? match[1].toLowerCase() : '',
  4690. slashes: !!match[2],
  4691. rest: match[3]
  4692. };
  4693. }
  4694. /**
  4695. * Resolve a relative URL pathname against a base URL pathname.
  4696. *
  4697. * @param {String} relative Pathname of the relative URL.
  4698. * @param {String} base Pathname of the base URL.
  4699. * @return {String} Resolved pathname.
  4700. * @api private
  4701. */
  4702. function resolve(relative, base) {
  4703. var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
  4704. , i = path.length
  4705. , last = path[i - 1]
  4706. , unshift = false
  4707. , up = 0;
  4708. while (i--) {
  4709. if (path[i] === '.') {
  4710. path.splice(i, 1);
  4711. } else if (path[i] === '..') {
  4712. path.splice(i, 1);
  4713. up++;
  4714. } else if (up) {
  4715. if (i === 0) unshift = true;
  4716. path.splice(i, 1);
  4717. up--;
  4718. }
  4719. }
  4720. if (unshift) path.unshift('');
  4721. if (last === '.' || last === '..') path.push('');
  4722. return path.join('/');
  4723. }
  4724. /**
  4725. * The actual URL instance. Instead of returning an object we've opted-in to
  4726. * create an actual constructor as it's much more memory efficient and
  4727. * faster and it pleases my OCD.
  4728. *
  4729. * @constructor
  4730. * @param {String} address URL we want to parse.
  4731. * @param {Object|String} location Location defaults for relative paths.
  4732. * @param {Boolean|Function} parser Parser for the query string.
  4733. * @api public
  4734. */
  4735. function URL(address, location, parser) {
  4736. if (!(this instanceof URL)) {
  4737. return new URL(address, location, parser);
  4738. }
  4739. var relative, extracted, parse, instruction, index, key
  4740. , instructions = rules.slice()
  4741. , type = typeof location
  4742. , url = this
  4743. , i = 0;
  4744. //
  4745. // The following if statements allows this module two have compatibility with
  4746. // 2 different API:
  4747. //
  4748. // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  4749. // where the boolean indicates that the query string should also be parsed.
  4750. //
  4751. // 2. The `URL` interface of the browser which accepts a URL, object as
  4752. // arguments. The supplied object will be used as default values / fall-back
  4753. // for relative paths.
  4754. //
  4755. if ('object' !== type && 'string' !== type) {
  4756. parser = location;
  4757. location = null;
  4758. }
  4759. if (parser && 'function' !== typeof parser) parser = qs.parse;
  4760. location = lolcation(location);
  4761. //
  4762. // Extract protocol information before running the instructions.
  4763. //
  4764. extracted = extractProtocol(address || '');
  4765. relative = !extracted.protocol && !extracted.slashes;
  4766. url.slashes = extracted.slashes || relative && location.slashes;
  4767. url.protocol = extracted.protocol || location.protocol || '';
  4768. address = extracted.rest;
  4769. //
  4770. // When the authority component is absent the URL starts with a path
  4771. // component.
  4772. //
  4773. if (!extracted.slashes) instructions[2] = [/(.*)/, 'pathname'];
  4774. for (; i < instructions.length; i++) {
  4775. instruction = instructions[i];
  4776. parse = instruction[0];
  4777. key = instruction[1];
  4778. if (parse !== parse) {
  4779. url[key] = address;
  4780. } else if ('string' === typeof parse) {
  4781. if (~(index = address.indexOf(parse))) {
  4782. if ('number' === typeof instruction[2]) {
  4783. url[key] = address.slice(0, index);
  4784. address = address.slice(index + instruction[2]);
  4785. } else {
  4786. url[key] = address.slice(index);
  4787. address = address.slice(0, index);
  4788. }
  4789. }
  4790. } else if ((index = parse.exec(address))) {
  4791. url[key] = index[1];
  4792. address = address.slice(0, index.index);
  4793. }
  4794. url[key] = url[key] || (
  4795. relative && instruction[3] ? location[key] || '' : ''
  4796. );
  4797. //
  4798. // Hostname, host and protocol should be lowercased so they can be used to
  4799. // create a proper `origin`.
  4800. //
  4801. if (instruction[4]) url[key] = url[key].toLowerCase();
  4802. }
  4803. //
  4804. // Also parse the supplied query string in to an object. If we're supplied
  4805. // with a custom parser as function use that instead of the default build-in
  4806. // parser.
  4807. //
  4808. if (parser) url.query = parser(url.query);
  4809. //
  4810. // If the URL is relative, resolve the pathname against the base URL.
  4811. //
  4812. if (
  4813. relative
  4814. && location.slashes
  4815. && url.pathname.charAt(0) !== '/'
  4816. && (url.pathname !== '' || location.pathname !== '')
  4817. ) {
  4818. url.pathname = resolve(url.pathname, location.pathname);
  4819. }
  4820. //
  4821. // We should not add port numbers if they are already the default port number
  4822. // for a given protocol. As the host also contains the port number we're going
  4823. // override it with the hostname which contains no port number.
  4824. //
  4825. if (!required(url.port, url.protocol)) {
  4826. url.host = url.hostname;
  4827. url.port = '';
  4828. }
  4829. //
  4830. // Parse down the `auth` for the username and password.
  4831. //
  4832. url.username = url.password = '';
  4833. if (url.auth) {
  4834. instruction = url.auth.split(':');
  4835. url.username = instruction[0] || '';
  4836. url.password = instruction[1] || '';
  4837. }
  4838. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  4839. ? url.protocol +'//'+ url.host
  4840. : 'null';
  4841. //
  4842. // The href is just the compiled result.
  4843. //
  4844. url.href = url.toString();
  4845. }
  4846. /**
  4847. * This is convenience method for changing properties in the URL instance to
  4848. * insure that they all propagate correctly.
  4849. *
  4850. * @param {String} part Property we need to adjust.
  4851. * @param {Mixed} value The newly assigned value.
  4852. * @param {Boolean|Function} fn When setting the query, it will be the function
  4853. * used to parse the query.
  4854. * When setting the protocol, double slash will be
  4855. * removed from the final url if it is true.
  4856. * @returns {URL}
  4857. * @api public
  4858. */
  4859. function set(part, value, fn) {
  4860. var url = this;
  4861. switch (part) {
  4862. case 'query':
  4863. if ('string' === typeof value && value.length) {
  4864. value = (fn || qs.parse)(value);
  4865. }
  4866. url[part] = value;
  4867. break;
  4868. case 'port':
  4869. url[part] = value;
  4870. if (!required(value, url.protocol)) {
  4871. url.host = url.hostname;
  4872. url[part] = '';
  4873. } else if (value) {
  4874. url.host = url.hostname +':'+ value;
  4875. }
  4876. break;
  4877. case 'hostname':
  4878. url[part] = value;
  4879. if (url.port) value += ':'+ url.port;
  4880. url.host = value;
  4881. break;
  4882. case 'host':
  4883. url[part] = value;
  4884. if (/:\d+$/.test(value)) {
  4885. value = value.split(':');
  4886. url.port = value.pop();
  4887. url.hostname = value.join(':');
  4888. } else {
  4889. url.hostname = value;
  4890. url.port = '';
  4891. }
  4892. break;
  4893. case 'protocol':
  4894. url.protocol = value.toLowerCase();
  4895. url.slashes = !fn;
  4896. break;
  4897. case 'pathname':
  4898. case 'hash':
  4899. if (value) {
  4900. var char = part === 'pathname' ? '/' : '#';
  4901. url[part] = value.charAt(0) !== char ? char + value : value;
  4902. } else {
  4903. url[part] = value;
  4904. }
  4905. break;
  4906. default:
  4907. url[part] = value;
  4908. }
  4909. for (var i = 0; i < rules.length; i++) {
  4910. var ins = rules[i];
  4911. if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
  4912. }
  4913. url.origin = url.protocol && url.host && url.protocol !== 'file:'
  4914. ? url.protocol +'//'+ url.host
  4915. : 'null';
  4916. url.href = url.toString();
  4917. return url;
  4918. }
  4919. /**
  4920. * Transform the properties back in to a valid and full URL string.
  4921. *
  4922. * @param {Function} stringify Optional query stringify function.
  4923. * @returns {String}
  4924. * @api public
  4925. */
  4926. function toString(stringify) {
  4927. if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
  4928. var query
  4929. , url = this
  4930. , protocol = url.protocol;
  4931. if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';
  4932. var result = protocol + (url.slashes ? '//' : '');
  4933. if (url.username) {
  4934. result += url.username;
  4935. if (url.password) result += ':'+ url.password;
  4936. result += '@';
  4937. }
  4938. result += url.host + url.pathname;
  4939. query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  4940. if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
  4941. if (url.hash) result += url.hash;
  4942. return result;
  4943. }
  4944. URL.prototype = { set: set, toString: toString };
  4945. //
  4946. // Expose the URL parser and some additional properties that might be useful for
  4947. // others or testing.
  4948. //
  4949. URL.extractProtocol = extractProtocol;
  4950. URL.location = lolcation;
  4951. URL.qs = qs;
  4952. module.exports = URL;
  4953. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  4954. },{"querystringify":59,"requires-port":60}]},{},[1])(1)
  4955. });
  4956. //# sourceMappingURL=sockjs.js.map