engine.io.js 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.eio=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  2. module.exports = _dereq_('./lib/');
  3. },{"./lib/":2}],2:[function(_dereq_,module,exports){
  4. module.exports = _dereq_('./socket');
  5. /**
  6. * Exports parser
  7. *
  8. * @api public
  9. *
  10. */
  11. module.exports.parser = _dereq_('engine.io-parser');
  12. },{"./socket":3,"engine.io-parser":20}],3:[function(_dereq_,module,exports){
  13. (function (global){
  14. /**
  15. * Module dependencies.
  16. */
  17. var transports = _dereq_('./transports');
  18. var Emitter = _dereq_('component-emitter');
  19. var debug = _dereq_('debug')('engine.io-client:socket');
  20. var index = _dereq_('indexof');
  21. var parser = _dereq_('engine.io-parser');
  22. var parseuri = _dereq_('parseuri');
  23. var parsejson = _dereq_('parsejson');
  24. var parseqs = _dereq_('parseqs');
  25. /**
  26. * Module exports.
  27. */
  28. module.exports = Socket;
  29. /**
  30. * Noop function.
  31. *
  32. * @api private
  33. */
  34. function noop(){}
  35. /**
  36. * Socket constructor.
  37. *
  38. * @param {String|Object} uri or options
  39. * @param {Object} options
  40. * @api public
  41. */
  42. function Socket(uri, opts){
  43. if (!(this instanceof Socket)) return new Socket(uri, opts);
  44. opts = opts || {};
  45. if (uri && 'object' == typeof uri) {
  46. opts = uri;
  47. uri = null;
  48. }
  49. if (uri) {
  50. uri = parseuri(uri);
  51. opts.hostname = uri.host;
  52. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  53. opts.port = uri.port;
  54. if (uri.query) opts.query = uri.query;
  55. } else if (opts.host) {
  56. opts.hostname = parseuri(opts.host).host;
  57. }
  58. this.secure = null != opts.secure ? opts.secure :
  59. (global.location && 'https:' == location.protocol);
  60. if (opts.hostname && !opts.port) {
  61. // if no port is specified manually, use the protocol default
  62. opts.port = this.secure ? '443' : '80';
  63. }
  64. this.agent = opts.agent || false;
  65. this.hostname = opts.hostname ||
  66. (global.location ? location.hostname : 'localhost');
  67. this.port = opts.port || (global.location && location.port ?
  68. location.port :
  69. (this.secure ? 443 : 80));
  70. this.query = opts.query || {};
  71. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  72. this.upgrade = false !== opts.upgrade;
  73. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  74. this.forceJSONP = !!opts.forceJSONP;
  75. this.jsonp = false !== opts.jsonp;
  76. this.forceBase64 = !!opts.forceBase64;
  77. this.enablesXDR = !!opts.enablesXDR;
  78. this.timestampParam = opts.timestampParam || 't';
  79. this.timestampRequests = opts.timestampRequests;
  80. this.transports = opts.transports || ['polling', 'websocket'];
  81. this.readyState = '';
  82. this.writeBuffer = [];
  83. this.policyPort = opts.policyPort || 843;
  84. this.rememberUpgrade = opts.rememberUpgrade || false;
  85. this.binaryType = null;
  86. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  87. this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
  88. if (true === this.perMessageDeflate) this.perMessageDeflate = {};
  89. if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
  90. this.perMessageDeflate.threshold = 1024;
  91. }
  92. // SSL options for Node.js client
  93. this.pfx = opts.pfx || null;
  94. this.key = opts.key || null;
  95. this.passphrase = opts.passphrase || null;
  96. this.cert = opts.cert || null;
  97. this.ca = opts.ca || null;
  98. this.ciphers = opts.ciphers || null;
  99. this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized;
  100. // other options for Node.js client
  101. var freeGlobal = typeof global == 'object' && global;
  102. if (freeGlobal.global === freeGlobal) {
  103. if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
  104. this.extraHeaders = opts.extraHeaders;
  105. }
  106. }
  107. this.open();
  108. }
  109. Socket.priorWebsocketSuccess = false;
  110. /**
  111. * Mix in `Emitter`.
  112. */
  113. Emitter(Socket.prototype);
  114. /**
  115. * Protocol version.
  116. *
  117. * @api public
  118. */
  119. Socket.protocol = parser.protocol; // this is an int
  120. /**
  121. * Expose deps for legacy compatibility
  122. * and standalone browser access.
  123. */
  124. Socket.Socket = Socket;
  125. Socket.Transport = _dereq_('./transport');
  126. Socket.transports = _dereq_('./transports');
  127. Socket.parser = _dereq_('engine.io-parser');
  128. /**
  129. * Creates transport of the given type.
  130. *
  131. * @param {String} transport name
  132. * @return {Transport}
  133. * @api private
  134. */
  135. Socket.prototype.createTransport = function (name) {
  136. debug('creating transport "%s"', name);
  137. var query = clone(this.query);
  138. // append engine.io protocol identifier
  139. query.EIO = parser.protocol;
  140. // transport name
  141. query.transport = name;
  142. // session id if we already have one
  143. if (this.id) query.sid = this.id;
  144. var transport = new transports[name]({
  145. agent: this.agent,
  146. hostname: this.hostname,
  147. port: this.port,
  148. secure: this.secure,
  149. path: this.path,
  150. query: query,
  151. forceJSONP: this.forceJSONP,
  152. jsonp: this.jsonp,
  153. forceBase64: this.forceBase64,
  154. enablesXDR: this.enablesXDR,
  155. timestampRequests: this.timestampRequests,
  156. timestampParam: this.timestampParam,
  157. policyPort: this.policyPort,
  158. socket: this,
  159. pfx: this.pfx,
  160. key: this.key,
  161. passphrase: this.passphrase,
  162. cert: this.cert,
  163. ca: this.ca,
  164. ciphers: this.ciphers,
  165. rejectUnauthorized: this.rejectUnauthorized,
  166. perMessageDeflate: this.perMessageDeflate,
  167. extraHeaders: this.extraHeaders
  168. });
  169. return transport;
  170. };
  171. function clone (obj) {
  172. var o = {};
  173. for (var i in obj) {
  174. if (obj.hasOwnProperty(i)) {
  175. o[i] = obj[i];
  176. }
  177. }
  178. return o;
  179. }
  180. /**
  181. * Initializes transport to use and starts probe.
  182. *
  183. * @api private
  184. */
  185. Socket.prototype.open = function () {
  186. var transport;
  187. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  188. transport = 'websocket';
  189. } else if (0 === this.transports.length) {
  190. // Emit error on next tick so it can be listened to
  191. var self = this;
  192. setTimeout(function() {
  193. self.emit('error', 'No transports available');
  194. }, 0);
  195. return;
  196. } else {
  197. transport = this.transports[0];
  198. }
  199. this.readyState = 'opening';
  200. // Retry with the next transport if the transport is disabled (jsonp: false)
  201. try {
  202. transport = this.createTransport(transport);
  203. } catch (e) {
  204. this.transports.shift();
  205. this.open();
  206. return;
  207. }
  208. transport.open();
  209. this.setTransport(transport);
  210. };
  211. /**
  212. * Sets the current transport. Disables the existing one (if any).
  213. *
  214. * @api private
  215. */
  216. Socket.prototype.setTransport = function(transport){
  217. debug('setting transport %s', transport.name);
  218. var self = this;
  219. if (this.transport) {
  220. debug('clearing existing transport %s', this.transport.name);
  221. this.transport.removeAllListeners();
  222. }
  223. // set up transport
  224. this.transport = transport;
  225. // set up transport listeners
  226. transport
  227. .on('drain', function(){
  228. self.onDrain();
  229. })
  230. .on('packet', function(packet){
  231. self.onPacket(packet);
  232. })
  233. .on('error', function(e){
  234. self.onError(e);
  235. })
  236. .on('close', function(){
  237. self.onClose('transport close');
  238. });
  239. };
  240. /**
  241. * Probes a transport.
  242. *
  243. * @param {String} transport name
  244. * @api private
  245. */
  246. Socket.prototype.probe = function (name) {
  247. debug('probing transport "%s"', name);
  248. var transport = this.createTransport(name, { probe: 1 })
  249. , failed = false
  250. , self = this;
  251. Socket.priorWebsocketSuccess = false;
  252. function onTransportOpen(){
  253. if (self.onlyBinaryUpgrades) {
  254. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  255. failed = failed || upgradeLosesBinary;
  256. }
  257. if (failed) return;
  258. debug('probe transport "%s" opened', name);
  259. transport.send([{ type: 'ping', data: 'probe' }]);
  260. transport.once('packet', function (msg) {
  261. if (failed) return;
  262. if ('pong' == msg.type && 'probe' == msg.data) {
  263. debug('probe transport "%s" pong', name);
  264. self.upgrading = true;
  265. self.emit('upgrading', transport);
  266. if (!transport) return;
  267. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  268. debug('pausing current transport "%s"', self.transport.name);
  269. self.transport.pause(function () {
  270. if (failed) return;
  271. if ('closed' == self.readyState) return;
  272. debug('changing transport and sending upgrade packet');
  273. cleanup();
  274. self.setTransport(transport);
  275. transport.send([{ type: 'upgrade' }]);
  276. self.emit('upgrade', transport);
  277. transport = null;
  278. self.upgrading = false;
  279. self.flush();
  280. });
  281. } else {
  282. debug('probe transport "%s" failed', name);
  283. var err = new Error('probe error');
  284. err.transport = transport.name;
  285. self.emit('upgradeError', err);
  286. }
  287. });
  288. }
  289. function freezeTransport() {
  290. if (failed) return;
  291. // Any callback called by transport should be ignored since now
  292. failed = true;
  293. cleanup();
  294. transport.close();
  295. transport = null;
  296. }
  297. //Handle any error that happens while probing
  298. function onerror(err) {
  299. var error = new Error('probe error: ' + err);
  300. error.transport = transport.name;
  301. freezeTransport();
  302. debug('probe transport "%s" failed because of error: %s', name, err);
  303. self.emit('upgradeError', error);
  304. }
  305. function onTransportClose(){
  306. onerror("transport closed");
  307. }
  308. //When the socket is closed while we're probing
  309. function onclose(){
  310. onerror("socket closed");
  311. }
  312. //When the socket is upgraded while we're probing
  313. function onupgrade(to){
  314. if (transport && to.name != transport.name) {
  315. debug('"%s" works - aborting "%s"', to.name, transport.name);
  316. freezeTransport();
  317. }
  318. }
  319. //Remove all listeners on the transport and on self
  320. function cleanup(){
  321. transport.removeListener('open', onTransportOpen);
  322. transport.removeListener('error', onerror);
  323. transport.removeListener('close', onTransportClose);
  324. self.removeListener('close', onclose);
  325. self.removeListener('upgrading', onupgrade);
  326. }
  327. transport.once('open', onTransportOpen);
  328. transport.once('error', onerror);
  329. transport.once('close', onTransportClose);
  330. this.once('close', onclose);
  331. this.once('upgrading', onupgrade);
  332. transport.open();
  333. };
  334. /**
  335. * Called when connection is deemed open.
  336. *
  337. * @api public
  338. */
  339. Socket.prototype.onOpen = function () {
  340. debug('socket open');
  341. this.readyState = 'open';
  342. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  343. this.emit('open');
  344. this.flush();
  345. // we check for `readyState` in case an `open`
  346. // listener already closed the socket
  347. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  348. debug('starting upgrade probes');
  349. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  350. this.probe(this.upgrades[i]);
  351. }
  352. }
  353. };
  354. /**
  355. * Handles a packet.
  356. *
  357. * @api private
  358. */
  359. Socket.prototype.onPacket = function (packet) {
  360. if ('opening' == this.readyState || 'open' == this.readyState) {
  361. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  362. this.emit('packet', packet);
  363. // Socket is live - any packet counts
  364. this.emit('heartbeat');
  365. switch (packet.type) {
  366. case 'open':
  367. this.onHandshake(parsejson(packet.data));
  368. break;
  369. case 'pong':
  370. this.setPing();
  371. this.emit('pong');
  372. break;
  373. case 'error':
  374. var err = new Error('server error');
  375. err.code = packet.data;
  376. this.onError(err);
  377. break;
  378. case 'message':
  379. this.emit('data', packet.data);
  380. this.emit('message', packet.data);
  381. break;
  382. }
  383. } else {
  384. debug('packet received with socket readyState "%s"', this.readyState);
  385. }
  386. };
  387. /**
  388. * Called upon handshake completion.
  389. *
  390. * @param {Object} handshake obj
  391. * @api private
  392. */
  393. Socket.prototype.onHandshake = function (data) {
  394. this.emit('handshake', data);
  395. this.id = data.sid;
  396. this.transport.query.sid = data.sid;
  397. this.upgrades = this.filterUpgrades(data.upgrades);
  398. this.pingInterval = data.pingInterval;
  399. this.pingTimeout = data.pingTimeout;
  400. this.onOpen();
  401. // In case open handler closes socket
  402. if ('closed' == this.readyState) return;
  403. this.setPing();
  404. // Prolong liveness of socket on heartbeat
  405. this.removeListener('heartbeat', this.onHeartbeat);
  406. this.on('heartbeat', this.onHeartbeat);
  407. };
  408. /**
  409. * Resets ping timeout.
  410. *
  411. * @api private
  412. */
  413. Socket.prototype.onHeartbeat = function (timeout) {
  414. clearTimeout(this.pingTimeoutTimer);
  415. var self = this;
  416. self.pingTimeoutTimer = setTimeout(function () {
  417. if ('closed' == self.readyState) return;
  418. self.onClose('ping timeout');
  419. }, timeout || (self.pingInterval + self.pingTimeout));
  420. };
  421. /**
  422. * Pings server every `this.pingInterval` and expects response
  423. * within `this.pingTimeout` or closes connection.
  424. *
  425. * @api private
  426. */
  427. Socket.prototype.setPing = function () {
  428. var self = this;
  429. clearTimeout(self.pingIntervalTimer);
  430. self.pingIntervalTimer = setTimeout(function () {
  431. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  432. self.ping();
  433. self.onHeartbeat(self.pingTimeout);
  434. }, self.pingInterval);
  435. };
  436. /**
  437. * Sends a ping packet.
  438. *
  439. * @api private
  440. */
  441. Socket.prototype.ping = function () {
  442. var self = this;
  443. this.sendPacket('ping', function(){
  444. self.emit('ping');
  445. });
  446. };
  447. /**
  448. * Called on `drain` event
  449. *
  450. * @api private
  451. */
  452. Socket.prototype.onDrain = function() {
  453. this.writeBuffer.splice(0, this.prevBufferLen);
  454. // setting prevBufferLen = 0 is very important
  455. // for example, when upgrading, upgrade packet is sent over,
  456. // and a nonzero prevBufferLen could cause problems on `drain`
  457. this.prevBufferLen = 0;
  458. if (0 === this.writeBuffer.length) {
  459. this.emit('drain');
  460. } else {
  461. this.flush();
  462. }
  463. };
  464. /**
  465. * Flush write buffers.
  466. *
  467. * @api private
  468. */
  469. Socket.prototype.flush = function () {
  470. if ('closed' != this.readyState && this.transport.writable &&
  471. !this.upgrading && this.writeBuffer.length) {
  472. debug('flushing %d packets in socket', this.writeBuffer.length);
  473. this.transport.send(this.writeBuffer);
  474. // keep track of current length of writeBuffer
  475. // splice writeBuffer and callbackBuffer on `drain`
  476. this.prevBufferLen = this.writeBuffer.length;
  477. this.emit('flush');
  478. }
  479. };
  480. /**
  481. * Sends a message.
  482. *
  483. * @param {String} message.
  484. * @param {Function} callback function.
  485. * @param {Object} options.
  486. * @return {Socket} for chaining.
  487. * @api public
  488. */
  489. Socket.prototype.write =
  490. Socket.prototype.send = function (msg, options, fn) {
  491. this.sendPacket('message', msg, options, fn);
  492. return this;
  493. };
  494. /**
  495. * Sends a packet.
  496. *
  497. * @param {String} packet type.
  498. * @param {String} data.
  499. * @param {Object} options.
  500. * @param {Function} callback function.
  501. * @api private
  502. */
  503. Socket.prototype.sendPacket = function (type, data, options, fn) {
  504. if('function' == typeof data) {
  505. fn = data;
  506. data = undefined;
  507. }
  508. if ('function' == typeof options) {
  509. fn = options;
  510. options = null;
  511. }
  512. if ('closing' == this.readyState || 'closed' == this.readyState) {
  513. return;
  514. }
  515. options = options || {};
  516. options.compress = false !== options.compress;
  517. var packet = {
  518. type: type,
  519. data: data,
  520. options: options
  521. };
  522. this.emit('packetCreate', packet);
  523. this.writeBuffer.push(packet);
  524. if (fn) this.once('flush', fn);
  525. this.flush();
  526. };
  527. /**
  528. * Closes the connection.
  529. *
  530. * @api private
  531. */
  532. Socket.prototype.close = function () {
  533. if ('opening' == this.readyState || 'open' == this.readyState) {
  534. this.readyState = 'closing';
  535. var self = this;
  536. if (this.writeBuffer.length) {
  537. this.once('drain', function() {
  538. if (this.upgrading) {
  539. waitForUpgrade();
  540. } else {
  541. close();
  542. }
  543. });
  544. } else if (this.upgrading) {
  545. waitForUpgrade();
  546. } else {
  547. close();
  548. }
  549. }
  550. function close() {
  551. self.onClose('forced close');
  552. debug('socket closing - telling transport to close');
  553. self.transport.close();
  554. }
  555. function cleanupAndClose() {
  556. self.removeListener('upgrade', cleanupAndClose);
  557. self.removeListener('upgradeError', cleanupAndClose);
  558. close();
  559. }
  560. function waitForUpgrade() {
  561. // wait for upgrade to finish since we can't send packets while pausing a transport
  562. self.once('upgrade', cleanupAndClose);
  563. self.once('upgradeError', cleanupAndClose);
  564. }
  565. return this;
  566. };
  567. /**
  568. * Called upon transport error
  569. *
  570. * @api private
  571. */
  572. Socket.prototype.onError = function (err) {
  573. debug('socket error %j', err);
  574. Socket.priorWebsocketSuccess = false;
  575. this.emit('error', err);
  576. this.onClose('transport error', err);
  577. };
  578. /**
  579. * Called upon transport close.
  580. *
  581. * @api private
  582. */
  583. Socket.prototype.onClose = function (reason, desc) {
  584. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  585. debug('socket close with reason: "%s"', reason);
  586. var self = this;
  587. // clear timers
  588. clearTimeout(this.pingIntervalTimer);
  589. clearTimeout(this.pingTimeoutTimer);
  590. // stop event from firing again for transport
  591. this.transport.removeAllListeners('close');
  592. // ensure transport won't stay open
  593. this.transport.close();
  594. // ignore further transport communication
  595. this.transport.removeAllListeners();
  596. // set ready state
  597. this.readyState = 'closed';
  598. // clear session id
  599. this.id = null;
  600. // emit close event
  601. this.emit('close', reason, desc);
  602. // clean buffers after, so users can still
  603. // grab the buffers on `close` event
  604. self.writeBuffer = [];
  605. self.prevBufferLen = 0;
  606. }
  607. };
  608. /**
  609. * Filters upgrades, returning only those matching client transports.
  610. *
  611. * @param {Array} server upgrades
  612. * @api private
  613. *
  614. */
  615. Socket.prototype.filterUpgrades = function (upgrades) {
  616. var filteredUpgrades = [];
  617. for (var i = 0, j = upgrades.length; i<j; i++) {
  618. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  619. }
  620. return filteredUpgrades;
  621. };
  622. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {})
  623. },{"./transport":4,"./transports":5,"component-emitter":16,"debug":18,"engine.io-parser":20,"indexof":24,"parsejson":27,"parseqs":28,"parseuri":29}],4:[function(_dereq_,module,exports){
  624. /**
  625. * Module dependencies.
  626. */
  627. var parser = _dereq_('engine.io-parser');
  628. var Emitter = _dereq_('component-emitter');
  629. /**
  630. * Module exports.
  631. */
  632. module.exports = Transport;
  633. /**
  634. * Transport abstract constructor.
  635. *
  636. * @param {Object} options.
  637. * @api private
  638. */
  639. function Transport (opts) {
  640. this.path = opts.path;
  641. this.hostname = opts.hostname;
  642. this.port = opts.port;
  643. this.secure = opts.secure;
  644. this.query = opts.query;
  645. this.timestampParam = opts.timestampParam;
  646. this.timestampRequests = opts.timestampRequests;
  647. this.readyState = '';
  648. this.agent = opts.agent || false;
  649. this.socket = opts.socket;
  650. this.enablesXDR = opts.enablesXDR;
  651. // SSL options for Node.js client
  652. this.pfx = opts.pfx;
  653. this.key = opts.key;
  654. this.passphrase = opts.passphrase;
  655. this.cert = opts.cert;
  656. this.ca = opts.ca;
  657. this.ciphers = opts.ciphers;
  658. this.rejectUnauthorized = opts.rejectUnauthorized;
  659. // other options for Node.js client
  660. this.extraHeaders = opts.extraHeaders;
  661. }
  662. /**
  663. * Mix in `Emitter`.
  664. */
  665. Emitter(Transport.prototype);
  666. /**
  667. * Emits an error.
  668. *
  669. * @param {String} str
  670. * @return {Transport} for chaining
  671. * @api public
  672. */
  673. Transport.prototype.onError = function (msg, desc) {
  674. var err = new Error(msg);
  675. err.type = 'TransportError';
  676. err.description = desc;
  677. this.emit('error', err);
  678. return this;
  679. };
  680. /**
  681. * Opens the transport.
  682. *
  683. * @api public
  684. */
  685. Transport.prototype.open = function () {
  686. if ('closed' == this.readyState || '' == this.readyState) {
  687. this.readyState = 'opening';
  688. this.doOpen();
  689. }
  690. return this;
  691. };
  692. /**
  693. * Closes the transport.
  694. *
  695. * @api private
  696. */
  697. Transport.prototype.close = function () {
  698. if ('opening' == this.readyState || 'open' == this.readyState) {
  699. this.doClose();
  700. this.onClose();
  701. }
  702. return this;
  703. };
  704. /**
  705. * Sends multiple packets.
  706. *
  707. * @param {Array} packets
  708. * @api private
  709. */
  710. Transport.prototype.send = function(packets){
  711. if ('open' == this.readyState) {
  712. this.write(packets);
  713. } else {
  714. throw new Error('Transport not open');
  715. }
  716. };
  717. /**
  718. * Called upon open
  719. *
  720. * @api private
  721. */
  722. Transport.prototype.onOpen = function () {
  723. this.readyState = 'open';
  724. this.writable = true;
  725. this.emit('open');
  726. };
  727. /**
  728. * Called with data.
  729. *
  730. * @param {String} data
  731. * @api private
  732. */
  733. Transport.prototype.onData = function(data){
  734. var packet = parser.decodePacket(data, this.socket.binaryType);
  735. this.onPacket(packet);
  736. };
  737. /**
  738. * Called with a decoded packet.
  739. */
  740. Transport.prototype.onPacket = function (packet) {
  741. this.emit('packet', packet);
  742. };
  743. /**
  744. * Called upon close.
  745. *
  746. * @api private
  747. */
  748. Transport.prototype.onClose = function () {
  749. this.readyState = 'closed';
  750. this.emit('close');
  751. };
  752. },{"component-emitter":16,"engine.io-parser":20}],5:[function(_dereq_,module,exports){
  753. (function (global){
  754. /**
  755. * Module dependencies
  756. */
  757. var XMLHttpRequest = _dereq_('xmlhttprequest-ssl');
  758. var XHR = _dereq_('./polling-xhr');
  759. var JSONP = _dereq_('./polling-jsonp');
  760. var websocket = _dereq_('./websocket');
  761. /**
  762. * Export transports.
  763. */
  764. exports.polling = polling;
  765. exports.websocket = websocket;
  766. /**
  767. * Polling transport polymorphic constructor.
  768. * Decides on xhr vs jsonp based on feature detection.
  769. *
  770. * @api private
  771. */
  772. function polling(opts){
  773. var xhr;
  774. var xd = false;
  775. var xs = false;
  776. var jsonp = false !== opts.jsonp;
  777. if (global.location) {
  778. var isSSL = 'https:' == location.protocol;
  779. var port = location.port;
  780. // some user agents have empty `location.port`
  781. if (!port) {
  782. port = isSSL ? 443 : 80;
  783. }
  784. xd = opts.hostname != location.hostname || port != opts.port;
  785. xs = opts.secure != isSSL;
  786. }
  787. opts.xdomain = xd;
  788. opts.xscheme = xs;
  789. xhr = new XMLHttpRequest(opts);
  790. if ('open' in xhr && !opts.forceJSONP) {
  791. return new XHR(opts);
  792. } else {
  793. if (!jsonp) throw new Error('JSONP disabled');
  794. return new JSONP(opts);
  795. }
  796. }
  797. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {})
  798. },{"./polling-jsonp":6,"./polling-xhr":7,"./websocket":9,"xmlhttprequest-ssl":10}],6:[function(_dereq_,module,exports){
  799. (function (global){
  800. /**
  801. * Module requirements.
  802. */
  803. var Polling = _dereq_('./polling');
  804. var inherit = _dereq_('component-inherit');
  805. /**
  806. * Module exports.
  807. */
  808. module.exports = JSONPPolling;
  809. /**
  810. * Cached regular expressions.
  811. */
  812. var rNewline = /\n/g;
  813. var rEscapedNewline = /\\n/g;
  814. /**
  815. * Global JSONP callbacks.
  816. */
  817. var callbacks;
  818. /**
  819. * Callbacks count.
  820. */
  821. var index = 0;
  822. /**
  823. * Noop.
  824. */
  825. function empty () { }
  826. /**
  827. * JSONP Polling constructor.
  828. *
  829. * @param {Object} opts.
  830. * @api public
  831. */
  832. function JSONPPolling (opts) {
  833. Polling.call(this, opts);
  834. this.query = this.query || {};
  835. // define global callbacks array if not present
  836. // we do this here (lazily) to avoid unneeded global pollution
  837. if (!callbacks) {
  838. // we need to consider multiple engines in the same page
  839. if (!global.___eio) global.___eio = [];
  840. callbacks = global.___eio;
  841. }
  842. // callback identifier
  843. this.index = callbacks.length;
  844. // add callback to jsonp global
  845. var self = this;
  846. callbacks.push(function (msg) {
  847. self.onData(msg);
  848. });
  849. // append to query string
  850. this.query.j = this.index;
  851. // prevent spurious errors from being emitted when the window is unloaded
  852. if (global.document && global.addEventListener) {
  853. global.addEventListener('beforeunload', function () {
  854. if (self.script) self.script.onerror = empty;
  855. }, false);
  856. }
  857. }
  858. /**
  859. * Inherits from Polling.
  860. */
  861. inherit(JSONPPolling, Polling);
  862. /*
  863. * JSONP only supports binary as base64 encoded strings
  864. */
  865. JSONPPolling.prototype.supportsBinary = false;
  866. /**
  867. * Closes the socket.
  868. *
  869. * @api private
  870. */
  871. JSONPPolling.prototype.doClose = function () {
  872. if (this.script) {
  873. this.script.parentNode.removeChild(this.script);
  874. this.script = null;
  875. }
  876. if (this.form) {
  877. this.form.parentNode.removeChild(this.form);
  878. this.form = null;
  879. this.iframe = null;
  880. }
  881. Polling.prototype.doClose.call(this);
  882. };
  883. /**
  884. * Starts a poll cycle.
  885. *
  886. * @api private
  887. */
  888. JSONPPolling.prototype.doPoll = function () {
  889. var self = this;
  890. var script = document.createElement('script');
  891. if (this.script) {
  892. this.script.parentNode.removeChild(this.script);
  893. this.script = null;
  894. }
  895. script.async = true;
  896. script.src = this.uri();
  897. script.onerror = function(e){
  898. self.onError('jsonp poll error',e);
  899. };
  900. var insertAt = document.getElementsByTagName('script')[0];
  901. if (insertAt) {
  902. insertAt.parentNode.insertBefore(script, insertAt);
  903. }
  904. else {
  905. (document.head || document.body).appendChild(script);
  906. }
  907. this.script = script;
  908. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  909. if (isUAgecko) {
  910. setTimeout(function () {
  911. var iframe = document.createElement('iframe');
  912. document.body.appendChild(iframe);
  913. document.body.removeChild(iframe);
  914. }, 100);
  915. }
  916. };
  917. /**
  918. * Writes with a hidden iframe.
  919. *
  920. * @param {String} data to send
  921. * @param {Function} called upon flush.
  922. * @api private
  923. */
  924. JSONPPolling.prototype.doWrite = function (data, fn) {
  925. var self = this;
  926. if (!this.form) {
  927. var form = document.createElement('form');
  928. var area = document.createElement('textarea');
  929. var id = this.iframeId = 'eio_iframe_' + this.index;
  930. var iframe;
  931. form.className = 'socketio';
  932. form.style.position = 'absolute';
  933. form.style.top = '-1000px';
  934. form.style.left = '-1000px';
  935. form.target = id;
  936. form.method = 'POST';
  937. form.setAttribute('accept-charset', 'utf-8');
  938. area.name = 'd';
  939. form.appendChild(area);
  940. document.body.appendChild(form);
  941. this.form = form;
  942. this.area = area;
  943. }
  944. this.form.action = this.uri();
  945. function complete () {
  946. initIframe();
  947. fn();
  948. }
  949. function initIframe () {
  950. if (self.iframe) {
  951. try {
  952. self.form.removeChild(self.iframe);
  953. } catch (e) {
  954. self.onError('jsonp polling iframe removal error', e);
  955. }
  956. }
  957. try {
  958. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  959. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  960. iframe = document.createElement(html);
  961. } catch (e) {
  962. iframe = document.createElement('iframe');
  963. iframe.name = self.iframeId;
  964. iframe.src = 'javascript:0';
  965. }
  966. iframe.id = self.iframeId;
  967. self.form.appendChild(iframe);
  968. self.iframe = iframe;
  969. }
  970. initIframe();
  971. // escape \n to prevent it from being converted into \r\n by some UAs
  972. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  973. data = data.replace(rEscapedNewline, '\\\n');
  974. this.area.value = data.replace(rNewline, '\\n');
  975. try {
  976. this.form.submit();
  977. } catch(e) {}
  978. if (this.iframe.attachEvent) {
  979. this.iframe.onreadystatechange = function(){
  980. if (self.iframe.readyState == 'complete') {
  981. complete();
  982. }
  983. };
  984. } else {
  985. this.iframe.onload = complete;
  986. }
  987. };
  988. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {})
  989. },{"./polling":8,"component-inherit":17}],7:[function(_dereq_,module,exports){
  990. (function (global){
  991. /**
  992. * Module requirements.
  993. */
  994. var XMLHttpRequest = _dereq_('xmlhttprequest-ssl');
  995. var Polling = _dereq_('./polling');
  996. var Emitter = _dereq_('component-emitter');
  997. var inherit = _dereq_('component-inherit');
  998. var debug = _dereq_('debug')('engine.io-client:polling-xhr');
  999. /**
  1000. * Module exports.
  1001. */
  1002. module.exports = XHR;
  1003. module.exports.Request = Request;
  1004. /**
  1005. * Empty function
  1006. */
  1007. function empty(){}
  1008. /**
  1009. * XHR Polling constructor.
  1010. *
  1011. * @param {Object} opts
  1012. * @api public
  1013. */
  1014. function XHR(opts){
  1015. Polling.call(this, opts);
  1016. if (global.location) {
  1017. var isSSL = 'https:' == location.protocol;
  1018. var port = location.port;
  1019. // some user agents have empty `location.port`
  1020. if (!port) {
  1021. port = isSSL ? 443 : 80;
  1022. }
  1023. this.xd = opts.hostname != global.location.hostname ||
  1024. port != opts.port;
  1025. this.xs = opts.secure != isSSL;
  1026. } else {
  1027. this.extraHeaders = opts.extraHeaders;
  1028. }
  1029. }
  1030. /**
  1031. * Inherits from Polling.
  1032. */
  1033. inherit(XHR, Polling);
  1034. /**
  1035. * XHR supports binary
  1036. */
  1037. XHR.prototype.supportsBinary = true;
  1038. /**
  1039. * Creates a request.
  1040. *
  1041. * @param {String} method
  1042. * @api private
  1043. */
  1044. XHR.prototype.request = function(opts){
  1045. opts = opts || {};
  1046. opts.uri = this.uri();
  1047. opts.xd = this.xd;
  1048. opts.xs = this.xs;
  1049. opts.agent = this.agent || false;
  1050. opts.supportsBinary = this.supportsBinary;
  1051. opts.enablesXDR = this.enablesXDR;
  1052. // SSL options for Node.js client
  1053. opts.pfx = this.pfx;
  1054. opts.key = this.key;
  1055. opts.passphrase = this.passphrase;
  1056. opts.cert = this.cert;
  1057. opts.ca = this.ca;
  1058. opts.ciphers = this.ciphers;
  1059. opts.rejectUnauthorized = this.rejectUnauthorized;
  1060. // other options for Node.js client
  1061. opts.extraHeaders = this.extraHeaders;
  1062. return new Request(opts);
  1063. };
  1064. /**
  1065. * Sends data.
  1066. *
  1067. * @param {String} data to send.
  1068. * @param {Function} called upon flush.
  1069. * @api private
  1070. */
  1071. XHR.prototype.doWrite = function(data, fn){
  1072. var isBinary = typeof data !== 'string' && data !== undefined;
  1073. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  1074. var self = this;
  1075. req.on('success', fn);
  1076. req.on('error', function(err){
  1077. self.onError('xhr post error', err);
  1078. });
  1079. this.sendXhr = req;
  1080. };
  1081. /**
  1082. * Starts a poll cycle.
  1083. *
  1084. * @api private
  1085. */
  1086. XHR.prototype.doPoll = function(){
  1087. debug('xhr poll');
  1088. var req = this.request();
  1089. var self = this;
  1090. req.on('data', function(data){
  1091. self.onData(data);
  1092. });
  1093. req.on('error', function(err){
  1094. self.onError('xhr poll error', err);
  1095. });
  1096. this.pollXhr = req;
  1097. };
  1098. /**
  1099. * Request constructor
  1100. *
  1101. * @param {Object} options
  1102. * @api public
  1103. */
  1104. function Request(opts){
  1105. this.method = opts.method || 'GET';
  1106. this.uri = opts.uri;
  1107. this.xd = !!opts.xd;
  1108. this.xs = !!opts.xs;
  1109. this.async = false !== opts.async;
  1110. this.data = undefined != opts.data ? opts.data : null;
  1111. this.agent = opts.agent;
  1112. this.isBinary = opts.isBinary;
  1113. this.supportsBinary = opts.supportsBinary;
  1114. this.enablesXDR = opts.enablesXDR;
  1115. // SSL options for Node.js client
  1116. this.pfx = opts.pfx;
  1117. this.key = opts.key;
  1118. this.passphrase = opts.passphrase;
  1119. this.cert = opts.cert;
  1120. this.ca = opts.ca;
  1121. this.ciphers = opts.ciphers;
  1122. this.rejectUnauthorized = opts.rejectUnauthorized;
  1123. // other options for Node.js client
  1124. this.extraHeaders = opts.extraHeaders;
  1125. this.create();
  1126. }
  1127. /**
  1128. * Mix in `Emitter`.
  1129. */
  1130. Emitter(Request.prototype);
  1131. /**
  1132. * Creates the XHR object and sends the request.
  1133. *
  1134. * @api private
  1135. */
  1136. Request.prototype.create = function(){
  1137. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  1138. // SSL options for Node.js client
  1139. opts.pfx = this.pfx;
  1140. opts.key = this.key;
  1141. opts.passphrase = this.passphrase;
  1142. opts.cert = this.cert;
  1143. opts.ca = this.ca;
  1144. opts.ciphers = this.ciphers;
  1145. opts.rejectUnauthorized = this.rejectUnauthorized;
  1146. var xhr = this.xhr = new XMLHttpRequest(opts);
  1147. var self = this;
  1148. try {
  1149. debug('xhr open %s: %s', this.method, this.uri);
  1150. xhr.open(this.method, this.uri, this.async);
  1151. try {
  1152. if (this.extraHeaders) {
  1153. xhr.setDisableHeaderCheck(true);
  1154. for (var i in this.extraHeaders) {
  1155. if (this.extraHeaders.hasOwnProperty(i)) {
  1156. xhr.setRequestHeader(i, this.extraHeaders[i]);
  1157. }
  1158. }
  1159. }
  1160. } catch (e) {}
  1161. if (this.supportsBinary) {
  1162. // This has to be done after open because Firefox is stupid
  1163. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  1164. xhr.responseType = 'arraybuffer';
  1165. }
  1166. if ('POST' == this.method) {
  1167. try {
  1168. if (this.isBinary) {
  1169. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  1170. } else {
  1171. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  1172. }
  1173. } catch (e) {}
  1174. }
  1175. // ie6 check
  1176. if ('withCredentials' in xhr) {
  1177. xhr.withCredentials = true;
  1178. }
  1179. if (this.hasXDR()) {
  1180. xhr.onload = function(){
  1181. self.onLoad();
  1182. };
  1183. xhr.onerror = function(){
  1184. self.onError(xhr.responseText);
  1185. };
  1186. } else {
  1187. xhr.onreadystatechange = function(){
  1188. if (4 != xhr.readyState) return;
  1189. if (200 == xhr.status || 1223 == xhr.status) {
  1190. self.onLoad();
  1191. } else {
  1192. // make sure the `error` event handler that's user-set
  1193. // does not throw in the same tick and gets caught here
  1194. setTimeout(function(){
  1195. self.onError(xhr.status);
  1196. }, 0);
  1197. }
  1198. };
  1199. }
  1200. debug('xhr data %s', this.data);
  1201. xhr.send(this.data);
  1202. } catch (e) {
  1203. // Need to defer since .create() is called directly fhrom the constructor
  1204. // and thus the 'error' event can only be only bound *after* this exception
  1205. // occurs. Therefore, also, we cannot throw here at all.
  1206. setTimeout(function() {
  1207. self.onError(e);
  1208. }, 0);
  1209. return;
  1210. }
  1211. if (global.document) {
  1212. this.index = Request.requestsCount++;
  1213. Request.requests[this.index] = this;
  1214. }
  1215. };
  1216. /**
  1217. * Called upon successful response.
  1218. *
  1219. * @api private
  1220. */
  1221. Request.prototype.onSuccess = function(){
  1222. this.emit('success');
  1223. this.cleanup();
  1224. };
  1225. /**
  1226. * Called if we have data.
  1227. *
  1228. * @api private
  1229. */
  1230. Request.prototype.onData = function(data){
  1231. this.emit('data', data);
  1232. this.onSuccess();
  1233. };
  1234. /**
  1235. * Called upon error.
  1236. *
  1237. * @api private
  1238. */
  1239. Request.prototype.onError = function(err){
  1240. this.emit('error', err);
  1241. this.cleanup(true);
  1242. };
  1243. /**
  1244. * Cleans up house.
  1245. *
  1246. * @api private
  1247. */
  1248. Request.prototype.cleanup = function(fromError){
  1249. if ('undefined' == typeof this.xhr || null === this.xhr) {
  1250. return;
  1251. }
  1252. // xmlhttprequest
  1253. if (this.hasXDR()) {
  1254. this.xhr.onload = this.xhr.onerror = empty;
  1255. } else {
  1256. this.xhr.onreadystatechange = empty;
  1257. }
  1258. if (fromError) {
  1259. try {
  1260. this.xhr.abort();
  1261. } catch(e) {}
  1262. }
  1263. if (global.document) {
  1264. delete Request.requests[this.index];
  1265. }
  1266. this.xhr = null;
  1267. };
  1268. /**
  1269. * Called upon load.
  1270. *
  1271. * @api private
  1272. */
  1273. Request.prototype.onLoad = function(){
  1274. var data;
  1275. try {
  1276. var contentType;
  1277. try {
  1278. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  1279. } catch (e) {}
  1280. if (contentType === 'application/octet-stream') {
  1281. data = this.xhr.response;
  1282. } else {
  1283. if (!this.supportsBinary) {
  1284. data = this.xhr.responseText;
  1285. } else {
  1286. try {
  1287. data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response));
  1288. } catch (e) {
  1289. var ui8Arr = new Uint8Array(this.xhr.response);
  1290. var dataArray = [];
  1291. for (var idx = 0, length = ui8Arr.length; idx < length; idx++) {
  1292. dataArray.push(ui8Arr[idx]);
  1293. }
  1294. data = String.fromCharCode.apply(null, dataArray);
  1295. }
  1296. }
  1297. }
  1298. } catch (e) {
  1299. this.onError(e);
  1300. }
  1301. if (null != data) {
  1302. this.onData(data);
  1303. }
  1304. };
  1305. /**
  1306. * Check if it has XDomainRequest.
  1307. *
  1308. * @api private
  1309. */
  1310. Request.prototype.hasXDR = function(){
  1311. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  1312. };
  1313. /**
  1314. * Aborts the request.
  1315. *
  1316. * @api public
  1317. */
  1318. Request.prototype.abort = function(){
  1319. this.cleanup();
  1320. };
  1321. /**
  1322. * Aborts pending requests when unloading the window. This is needed to prevent
  1323. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  1324. * emitted.
  1325. */
  1326. if (global.document) {
  1327. Request.requestsCount = 0;
  1328. Request.requests = {};
  1329. if (global.attachEvent) {
  1330. global.attachEvent('onunload', unloadHandler);
  1331. } else if (global.addEventListener) {
  1332. global.addEventListener('beforeunload', unloadHandler, false);
  1333. }
  1334. }
  1335. function unloadHandler() {
  1336. for (var i in Request.requests) {
  1337. if (Request.requests.hasOwnProperty(i)) {
  1338. Request.requests[i].abort();
  1339. }
  1340. }
  1341. }
  1342. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {})
  1343. },{"./polling":8,"component-emitter":16,"component-inherit":17,"debug":18,"xmlhttprequest-ssl":10}],8:[function(_dereq_,module,exports){
  1344. /**
  1345. * Module dependencies.
  1346. */
  1347. var Transport = _dereq_('../transport');
  1348. var parseqs = _dereq_('parseqs');
  1349. var parser = _dereq_('engine.io-parser');
  1350. var inherit = _dereq_('component-inherit');
  1351. var yeast = _dereq_('yeast');
  1352. var debug = _dereq_('debug')('engine.io-client:polling');
  1353. /**
  1354. * Module exports.
  1355. */
  1356. module.exports = Polling;
  1357. /**
  1358. * Is XHR2 supported?
  1359. */
  1360. var hasXHR2 = (function() {
  1361. var XMLHttpRequest = _dereq_('xmlhttprequest-ssl');
  1362. var xhr = new XMLHttpRequest({ xdomain: false });
  1363. return null != xhr.responseType;
  1364. })();
  1365. /**
  1366. * Polling interface.
  1367. *
  1368. * @param {Object} opts
  1369. * @api private
  1370. */
  1371. function Polling(opts){
  1372. var forceBase64 = (opts && opts.forceBase64);
  1373. if (!hasXHR2 || forceBase64) {
  1374. this.supportsBinary = false;
  1375. }
  1376. Transport.call(this, opts);
  1377. }
  1378. /**
  1379. * Inherits from Transport.
  1380. */
  1381. inherit(Polling, Transport);
  1382. /**
  1383. * Transport name.
  1384. */
  1385. Polling.prototype.name = 'polling';
  1386. /**
  1387. * Opens the socket (triggers polling). We write a PING message to determine
  1388. * when the transport is open.
  1389. *
  1390. * @api private
  1391. */
  1392. Polling.prototype.doOpen = function(){
  1393. this.poll();
  1394. };
  1395. /**
  1396. * Pauses polling.
  1397. *
  1398. * @param {Function} callback upon buffers are flushed and transport is paused
  1399. * @api private
  1400. */
  1401. Polling.prototype.pause = function(onPause){
  1402. var pending = 0;
  1403. var self = this;
  1404. this.readyState = 'pausing';
  1405. function pause(){
  1406. debug('paused');
  1407. self.readyState = 'paused';
  1408. onPause();
  1409. }
  1410. if (this.polling || !this.writable) {
  1411. var total = 0;
  1412. if (this.polling) {
  1413. debug('we are currently polling - waiting to pause');
  1414. total++;
  1415. this.once('pollComplete', function(){
  1416. debug('pre-pause polling complete');
  1417. --total || pause();
  1418. });
  1419. }
  1420. if (!this.writable) {
  1421. debug('we are currently writing - waiting to pause');
  1422. total++;
  1423. this.once('drain', function(){
  1424. debug('pre-pause writing complete');
  1425. --total || pause();
  1426. });
  1427. }
  1428. } else {
  1429. pause();
  1430. }
  1431. };
  1432. /**
  1433. * Starts polling cycle.
  1434. *
  1435. * @api public
  1436. */
  1437. Polling.prototype.poll = function(){
  1438. debug('polling');
  1439. this.polling = true;
  1440. this.doPoll();
  1441. this.emit('poll');
  1442. };
  1443. /**
  1444. * Overloads onData to detect payloads.
  1445. *
  1446. * @api private
  1447. */
  1448. Polling.prototype.onData = function(data){
  1449. var self = this;
  1450. debug('polling got data %s', data);
  1451. var callback = function(packet, index, total) {
  1452. // if its the first message we consider the transport open
  1453. if ('opening' == self.readyState) {
  1454. self.onOpen();
  1455. }
  1456. // if its a close packet, we close the ongoing requests
  1457. if ('close' == packet.type) {
  1458. self.onClose();
  1459. return false;
  1460. }
  1461. // otherwise bypass onData and handle the message
  1462. self.onPacket(packet);
  1463. };
  1464. // decode payload
  1465. parser.decodePayload(data, this.socket.binaryType, callback);
  1466. // if an event did not trigger closing
  1467. if ('closed' != this.readyState) {
  1468. // if we got data we're not polling
  1469. this.polling = false;
  1470. this.emit('pollComplete');
  1471. if ('open' == this.readyState) {
  1472. this.poll();
  1473. } else {
  1474. debug('ignoring poll - transport state "%s"', this.readyState);
  1475. }
  1476. }
  1477. };
  1478. /**
  1479. * For polling, send a close packet.
  1480. *
  1481. * @api private
  1482. */
  1483. Polling.prototype.doClose = function(){
  1484. var self = this;
  1485. function close(){
  1486. debug('writing close packet');
  1487. self.write([{ type: 'close' }]);
  1488. }
  1489. if ('open' == this.readyState) {
  1490. debug('transport open - closing');
  1491. close();
  1492. } else {
  1493. // in case we're trying to close while
  1494. // handshaking is in progress (GH-164)
  1495. debug('transport not open - deferring close');
  1496. this.once('open', close);
  1497. }
  1498. };
  1499. /**
  1500. * Writes a packets payload.
  1501. *
  1502. * @param {Array} data packets
  1503. * @param {Function} drain callback
  1504. * @api private
  1505. */
  1506. Polling.prototype.write = function(packets){
  1507. var self = this;
  1508. this.writable = false;
  1509. var callbackfn = function() {
  1510. self.writable = true;
  1511. self.emit('drain');
  1512. };
  1513. var self = this;
  1514. parser.encodePayload(packets, this.supportsBinary, function(data) {
  1515. self.doWrite(data, callbackfn);
  1516. });
  1517. };
  1518. /**
  1519. * Generates uri for connection.
  1520. *
  1521. * @api private
  1522. */
  1523. Polling.prototype.uri = function(){
  1524. var query = this.query || {};
  1525. var schema = this.secure ? 'https' : 'http';
  1526. var port = '';
  1527. // cache busting is forced
  1528. if (false !== this.timestampRequests) {
  1529. query[this.timestampParam] = yeast();
  1530. }
  1531. if (!this.supportsBinary && !query.sid) {
  1532. query.b64 = 1;
  1533. }
  1534. query = parseqs.encode(query);
  1535. // avoid port if default for schema
  1536. if (this.port && (('https' == schema && this.port != 443) ||
  1537. ('http' == schema && this.port != 80))) {
  1538. port = ':' + this.port;
  1539. }
  1540. // prepend ? to query
  1541. if (query.length) {
  1542. query = '?' + query;
  1543. }
  1544. var ipv6 = this.hostname.indexOf(':') !== -1;
  1545. return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
  1546. };
  1547. },{"../transport":4,"component-inherit":17,"debug":18,"engine.io-parser":20,"parseqs":28,"xmlhttprequest-ssl":10,"yeast":31}],9:[function(_dereq_,module,exports){
  1548. (function (global){
  1549. /**
  1550. * Module dependencies.
  1551. */
  1552. var Transport = _dereq_('../transport');
  1553. var parser = _dereq_('engine.io-parser');
  1554. var parseqs = _dereq_('parseqs');
  1555. var inherit = _dereq_('component-inherit');
  1556. var yeast = _dereq_('yeast');
  1557. var debug = _dereq_('debug')('engine.io-client:websocket');
  1558. var BrowserWebSocket = global.WebSocket || global.MozWebSocket;
  1559. /**
  1560. * Get either the `WebSocket` or `MozWebSocket` globals
  1561. * in the browser or try to resolve WebSocket-compatible
  1562. * interface exposed by `ws` for Node-like environment.
  1563. */
  1564. var WebSocket = BrowserWebSocket;
  1565. if (!WebSocket && typeof window === 'undefined') {
  1566. try {
  1567. WebSocket = _dereq_('ws');
  1568. } catch (e) { }
  1569. }
  1570. /**
  1571. * Module exports.
  1572. */
  1573. module.exports = WS;
  1574. /**
  1575. * WebSocket transport constructor.
  1576. *
  1577. * @api {Object} connection options
  1578. * @api public
  1579. */
  1580. function WS(opts){
  1581. var forceBase64 = (opts && opts.forceBase64);
  1582. if (forceBase64) {
  1583. this.supportsBinary = false;
  1584. }
  1585. this.perMessageDeflate = opts.perMessageDeflate;
  1586. Transport.call(this, opts);
  1587. }
  1588. /**
  1589. * Inherits from Transport.
  1590. */
  1591. inherit(WS, Transport);
  1592. /**
  1593. * Transport name.
  1594. *
  1595. * @api public
  1596. */
  1597. WS.prototype.name = 'websocket';
  1598. /*
  1599. * WebSockets support binary
  1600. */
  1601. WS.prototype.supportsBinary = true;
  1602. /**
  1603. * Opens socket.
  1604. *
  1605. * @api private
  1606. */
  1607. WS.prototype.doOpen = function(){
  1608. if (!this.check()) {
  1609. // let probe timeout
  1610. return;
  1611. }
  1612. var self = this;
  1613. var uri = this.uri();
  1614. var protocols = void(0);
  1615. var opts = {
  1616. agent: this.agent,
  1617. perMessageDeflate: this.perMessageDeflate
  1618. };
  1619. // SSL options for Node.js client
  1620. opts.pfx = this.pfx;
  1621. opts.key = this.key;
  1622. opts.passphrase = this.passphrase;
  1623. opts.cert = this.cert;
  1624. opts.ca = this.ca;
  1625. opts.ciphers = this.ciphers;
  1626. opts.rejectUnauthorized = this.rejectUnauthorized;
  1627. if (this.extraHeaders) {
  1628. opts.headers = this.extraHeaders;
  1629. }
  1630. this.ws = BrowserWebSocket ? new WebSocket(uri) : new WebSocket(uri, protocols, opts);
  1631. if (this.ws.binaryType === undefined) {
  1632. this.supportsBinary = false;
  1633. }
  1634. if (this.ws.supports && this.ws.supports.binary) {
  1635. this.supportsBinary = true;
  1636. this.ws.binaryType = 'buffer';
  1637. } else {
  1638. this.ws.binaryType = 'arraybuffer';
  1639. }
  1640. this.addEventListeners();
  1641. };
  1642. /**
  1643. * Adds event listeners to the socket
  1644. *
  1645. * @api private
  1646. */
  1647. WS.prototype.addEventListeners = function(){
  1648. var self = this;
  1649. this.ws.onopen = function(){
  1650. self.onOpen();
  1651. };
  1652. this.ws.onclose = function(){
  1653. self.onClose();
  1654. };
  1655. this.ws.onmessage = function(ev){
  1656. self.onData(ev.data);
  1657. };
  1658. this.ws.onerror = function(e){
  1659. self.onError('websocket error', e);
  1660. };
  1661. };
  1662. /**
  1663. * Override `onData` to use a timer on iOS.
  1664. * See: https://gist.github.com/mloughran/2052006
  1665. *
  1666. * @api private
  1667. */
  1668. if ('undefined' != typeof navigator
  1669. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  1670. WS.prototype.onData = function(data){
  1671. var self = this;
  1672. setTimeout(function(){
  1673. Transport.prototype.onData.call(self, data);
  1674. }, 0);
  1675. };
  1676. }
  1677. /**
  1678. * Writes data to socket.
  1679. *
  1680. * @param {Array} array of packets.
  1681. * @api private
  1682. */
  1683. WS.prototype.write = function(packets){
  1684. var self = this;
  1685. this.writable = false;
  1686. // encodePacket efficient as it uses WS framing
  1687. // no need for encodePayload
  1688. var total = packets.length;
  1689. for (var i = 0, l = total; i < l; i++) {
  1690. (function(packet) {
  1691. parser.encodePacket(packet, self.supportsBinary, function(data) {
  1692. if (!BrowserWebSocket) {
  1693. // always create a new object (GH-437)
  1694. var opts = {};
  1695. if (packet.options) {
  1696. opts.compress = packet.options.compress;
  1697. }
  1698. if (self.perMessageDeflate) {
  1699. var len = 'string' == typeof data ? global.Buffer.byteLength(data) : data.length;
  1700. if (len < self.perMessageDeflate.threshold) {
  1701. opts.compress = false;
  1702. }
  1703. }
  1704. }
  1705. //Sometimes the websocket has already been closed but the browser didn't
  1706. //have a chance of informing us about it yet, in that case send will
  1707. //throw an error
  1708. try {
  1709. if (BrowserWebSocket) {
  1710. // TypeError is thrown when passing the second argument on Safari
  1711. self.ws.send(data);
  1712. } else {
  1713. self.ws.send(data, opts);
  1714. }
  1715. } catch (e){
  1716. debug('websocket closed before onclose event');
  1717. }
  1718. --total || done();
  1719. });
  1720. })(packets[i]);
  1721. }
  1722. function done(){
  1723. self.emit('flush');
  1724. // fake drain
  1725. // defer to next tick to allow Socket to clear writeBuffer
  1726. setTimeout(function(){
  1727. self.writable = true;
  1728. self.emit('drain');
  1729. }, 0);
  1730. }
  1731. };
  1732. /**
  1733. * Called upon close
  1734. *
  1735. * @api private
  1736. */
  1737. WS.prototype.onClose = function(){
  1738. Transport.prototype.onClose.call(this);
  1739. };
  1740. /**
  1741. * Closes socket.
  1742. *
  1743. * @api private
  1744. */
  1745. WS.prototype.doClose = function(){
  1746. if (typeof this.ws !== 'undefined') {
  1747. this.ws.close();
  1748. }
  1749. };
  1750. /**
  1751. * Generates uri for connection.
  1752. *
  1753. * @api private
  1754. */
  1755. WS.prototype.uri = function(){
  1756. var query = this.query || {};
  1757. var schema = this.secure ? 'wss' : 'ws';
  1758. var port = '';
  1759. // avoid port if default for schema
  1760. if (this.port && (('wss' == schema && this.port != 443)
  1761. || ('ws' == schema && this.port != 80))) {
  1762. port = ':' + this.port;
  1763. }
  1764. // append timestamp to URI
  1765. if (this.timestampRequests) {
  1766. query[this.timestampParam] = yeast();
  1767. }
  1768. // communicate binary support capabilities
  1769. if (!this.supportsBinary) {
  1770. query.b64 = 1;
  1771. }
  1772. query = parseqs.encode(query);
  1773. // prepend ? to query
  1774. if (query.length) {
  1775. query = '?' + query;
  1776. }
  1777. var ipv6 = this.hostname.indexOf(':') !== -1;
  1778. return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
  1779. };
  1780. /**
  1781. * Feature detection for WebSocket.
  1782. *
  1783. * @return {Boolean} whether this transport is available.
  1784. * @api public
  1785. */
  1786. WS.prototype.check = function(){
  1787. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  1788. };
  1789. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {})
  1790. },{"../transport":4,"component-inherit":17,"debug":18,"engine.io-parser":20,"parseqs":28,"ws":15,"yeast":31}],10:[function(_dereq_,module,exports){
  1791. // browser shim for xmlhttprequest module
  1792. var hasCORS = _dereq_('has-cors');
  1793. module.exports = function(opts) {
  1794. var xdomain = opts.xdomain;
  1795. // scheme must be same when usign XDomainRequest
  1796. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  1797. var xscheme = opts.xscheme;
  1798. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  1799. // https://github.com/Automattic/engine.io-client/pull/217
  1800. var enablesXDR = opts.enablesXDR;
  1801. // XMLHttpRequest can be disabled on IE
  1802. try {
  1803. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  1804. return new XMLHttpRequest();
  1805. }
  1806. } catch (e) { }
  1807. // Use XDomainRequest for IE8 if enablesXDR is true
  1808. // because loading bar keeps flashing when using jsonp-polling
  1809. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  1810. try {
  1811. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  1812. return new XDomainRequest();
  1813. }
  1814. } catch (e) { }
  1815. if (!xdomain) {
  1816. try {
  1817. return new ActiveXObject('Microsoft.XMLHTTP');
  1818. } catch(e) { }
  1819. }
  1820. }
  1821. },{"has-cors":23}],11:[function(_dereq_,module,exports){
  1822. module.exports = after
  1823. function after(count, callback, err_cb) {
  1824. var bail = false
  1825. err_cb = err_cb || noop
  1826. proxy.count = count
  1827. return (count === 0) ? callback() : proxy
  1828. function proxy(err, result) {
  1829. if (proxy.count <= 0) {
  1830. throw new Error('after called too many times')
  1831. }
  1832. --proxy.count
  1833. // after first error, rest are passed to err_cb
  1834. if (err) {
  1835. bail = true
  1836. callback(err)
  1837. // future error callbacks will go to error handler
  1838. callback = err_cb
  1839. } else if (proxy.count === 0 && !bail) {
  1840. callback(null, result)
  1841. }
  1842. }
  1843. }
  1844. function noop() {}
  1845. },{}],12:[function(_dereq_,module,exports){
  1846. /**
  1847. * An abstraction for slicing an arraybuffer even when
  1848. * ArrayBuffer.prototype.slice is not supported
  1849. *
  1850. * @api public
  1851. */
  1852. module.exports = function(arraybuffer, start, end) {
  1853. var bytes = arraybuffer.byteLength;
  1854. start = start || 0;
  1855. end = end || bytes;
  1856. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  1857. if (start < 0) { start += bytes; }
  1858. if (end < 0) { end += bytes; }
  1859. if (end > bytes) { end = bytes; }
  1860. if (start >= bytes || start >= end || bytes === 0) {
  1861. return new ArrayBuffer(0);
  1862. }
  1863. var abv = new Uint8Array(arraybuffer);
  1864. var result = new Uint8Array(end - start);
  1865. for (var i = start, ii = 0; i < end; i++, ii++) {
  1866. result[ii] = abv[i];
  1867. }
  1868. return result.buffer;
  1869. };
  1870. },{}],13:[function(_dereq_,module,exports){
  1871. /*
  1872. * base64-arraybuffer
  1873. * https://github.com/niklasvh/base64-arraybuffer
  1874. *
  1875. * Copyright (c) 2012 Niklas von Hertzen
  1876. * Licensed under the MIT license.
  1877. */
  1878. (function(chars){
  1879. "use strict";
  1880. exports.encode = function(arraybuffer) {
  1881. var bytes = new Uint8Array(arraybuffer),
  1882. i, len = bytes.length, base64 = "";
  1883. for (i = 0; i < len; i+=3) {
  1884. base64 += chars[bytes[i] >> 2];
  1885. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  1886. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  1887. base64 += chars[bytes[i + 2] & 63];
  1888. }
  1889. if ((len % 3) === 2) {
  1890. base64 = base64.substring(0, base64.length - 1) + "=";
  1891. } else if (len % 3 === 1) {
  1892. base64 = base64.substring(0, base64.length - 2) + "==";
  1893. }
  1894. return base64;
  1895. };
  1896. exports.decode = function(base64) {
  1897. var bufferLength = base64.length * 0.75,
  1898. len = base64.length, i, p = 0,
  1899. encoded1, encoded2, encoded3, encoded4;
  1900. if (base64[base64.length - 1] === "=") {
  1901. bufferLength--;
  1902. if (base64[base64.length - 2] === "=") {
  1903. bufferLength--;
  1904. }
  1905. }
  1906. var arraybuffer = new ArrayBuffer(bufferLength),
  1907. bytes = new Uint8Array(arraybuffer);
  1908. for (i = 0; i < len; i+=4) {
  1909. encoded1 = chars.indexOf(base64[i]);
  1910. encoded2 = chars.indexOf(base64[i+1]);
  1911. encoded3 = chars.indexOf(base64[i+2]);
  1912. encoded4 = chars.indexOf(base64[i+3]);
  1913. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  1914. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  1915. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  1916. }
  1917. return arraybuffer;
  1918. };
  1919. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  1920. },{}],14:[function(_dereq_,module,exports){
  1921. (function (global){
  1922. /**
  1923. * Create a blob builder even when vendor prefixes exist
  1924. */
  1925. var BlobBuilder = global.BlobBuilder
  1926. || global.WebKitBlobBuilder
  1927. || global.MSBlobBuilder
  1928. || global.MozBlobBuilder;
  1929. /**
  1930. * Check if Blob constructor is supported
  1931. */
  1932. var blobSupported = (function() {
  1933. try {
  1934. var a = new Blob(['hi']);
  1935. return a.size === 2;
  1936. } catch(e) {
  1937. return false;
  1938. }
  1939. })();
  1940. /**
  1941. * Check if Blob constructor supports ArrayBufferViews
  1942. * Fails in Safari 6, so we need to map to ArrayBuffers there.
  1943. */
  1944. var blobSupportsArrayBufferView = blobSupported && (function() {
  1945. try {
  1946. var b = new Blob([new Uint8Array([1,2])]);
  1947. return b.size === 2;
  1948. } catch(e) {
  1949. return false;
  1950. }
  1951. })();
  1952. /**
  1953. * Check if BlobBuilder is supported
  1954. */
  1955. var blobBuilderSupported = BlobBuilder
  1956. && BlobBuilder.prototype.append
  1957. && BlobBuilder.prototype.getBlob;
  1958. /**
  1959. * Helper function that maps ArrayBufferViews to ArrayBuffers
  1960. * Used by BlobBuilder constructor and old browsers that didn't
  1961. * support it in the Blob constructor.
  1962. */
  1963. function mapArrayBufferViews(ary) {
  1964. for (var i = 0; i < ary.length; i++) {
  1965. var chunk = ary[i];
  1966. if (chunk.buffer instanceof ArrayBuffer) {
  1967. var buf = chunk.buffer;
  1968. // if this is a subarray, make a copy so we only
  1969. // include the subarray region from the underlying buffer
  1970. if (chunk.byteLength !== buf.byteLength) {
  1971. var copy = new Uint8Array(chunk.byteLength);
  1972. copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
  1973. buf = copy.buffer;
  1974. }
  1975. ary[i] = buf;
  1976. }
  1977. }
  1978. }
  1979. function BlobBuilderConstructor(ary, options) {
  1980. options = options || {};
  1981. var bb = new BlobBuilder();
  1982. mapArrayBufferViews(ary);
  1983. for (var i = 0; i < ary.length; i++) {
  1984. bb.append(ary[i]);
  1985. }
  1986. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  1987. };
  1988. function BlobConstructor(ary, options) {
  1989. mapArrayBufferViews(ary);
  1990. return new Blob(ary, options || {});
  1991. };
  1992. module.exports = (function() {
  1993. if (blobSupported) {
  1994. return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
  1995. } else if (blobBuilderSupported) {
  1996. return BlobBuilderConstructor;
  1997. } else {
  1998. return undefined;
  1999. }
  2000. })();
  2001. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {})
  2002. },{}],15:[function(_dereq_,module,exports){
  2003. },{}],16:[function(_dereq_,module,exports){
  2004. /**
  2005. * Expose `Emitter`.
  2006. */
  2007. module.exports = Emitter;
  2008. /**
  2009. * Initialize a new `Emitter`.
  2010. *
  2011. * @api public
  2012. */
  2013. function Emitter(obj) {
  2014. if (obj) return mixin(obj);
  2015. };
  2016. /**
  2017. * Mixin the emitter properties.
  2018. *
  2019. * @param {Object} obj
  2020. * @return {Object}
  2021. * @api private
  2022. */
  2023. function mixin(obj) {
  2024. for (var key in Emitter.prototype) {
  2025. obj[key] = Emitter.prototype[key];
  2026. }
  2027. return obj;
  2028. }
  2029. /**
  2030. * Listen on the given `event` with `fn`.
  2031. *
  2032. * @param {String} event
  2033. * @param {Function} fn
  2034. * @return {Emitter}
  2035. * @api public
  2036. */
  2037. Emitter.prototype.on =
  2038. Emitter.prototype.addEventListener = function(event, fn){
  2039. this._callbacks = this._callbacks || {};
  2040. (this._callbacks[event] = this._callbacks[event] || [])
  2041. .push(fn);
  2042. return this;
  2043. };
  2044. /**
  2045. * Adds an `event` listener that will be invoked a single
  2046. * time then automatically removed.
  2047. *
  2048. * @param {String} event
  2049. * @param {Function} fn
  2050. * @return {Emitter}
  2051. * @api public
  2052. */
  2053. Emitter.prototype.once = function(event, fn){
  2054. var self = this;
  2055. this._callbacks = this._callbacks || {};
  2056. function on() {
  2057. self.off(event, on);
  2058. fn.apply(this, arguments);
  2059. }
  2060. on.fn = fn;
  2061. this.on(event, on);
  2062. return this;
  2063. };
  2064. /**
  2065. * Remove the given callback for `event` or all
  2066. * registered callbacks.
  2067. *
  2068. * @param {String} event
  2069. * @param {Function} fn
  2070. * @return {Emitter}
  2071. * @api public
  2072. */
  2073. Emitter.prototype.off =
  2074. Emitter.prototype.removeListener =
  2075. Emitter.prototype.removeAllListeners =
  2076. Emitter.prototype.removeEventListener = function(event, fn){
  2077. this._callbacks = this._callbacks || {};
  2078. // all
  2079. if (0 == arguments.length) {
  2080. this._callbacks = {};
  2081. return this;
  2082. }
  2083. // specific event
  2084. var callbacks = this._callbacks[event];
  2085. if (!callbacks) return this;
  2086. // remove all handlers
  2087. if (1 == arguments.length) {
  2088. delete this._callbacks[event];
  2089. return this;
  2090. }
  2091. // remove specific handler
  2092. var cb;
  2093. for (var i = 0; i < callbacks.length; i++) {
  2094. cb = callbacks[i];
  2095. if (cb === fn || cb.fn === fn) {
  2096. callbacks.splice(i, 1);
  2097. break;
  2098. }
  2099. }
  2100. return this;
  2101. };
  2102. /**
  2103. * Emit `event` with the given args.
  2104. *
  2105. * @param {String} event
  2106. * @param {Mixed} ...
  2107. * @return {Emitter}
  2108. */
  2109. Emitter.prototype.emit = function(event){
  2110. this._callbacks = this._callbacks || {};
  2111. var args = [].slice.call(arguments, 1)
  2112. , callbacks = this._callbacks[event];
  2113. if (callbacks) {
  2114. callbacks = callbacks.slice(0);
  2115. for (var i = 0, len = callbacks.length; i < len; ++i) {
  2116. callbacks[i].apply(this, args);
  2117. }
  2118. }
  2119. return this;
  2120. };
  2121. /**
  2122. * Return array of callbacks for `event`.
  2123. *
  2124. * @param {String} event
  2125. * @return {Array}
  2126. * @api public
  2127. */
  2128. Emitter.prototype.listeners = function(event){
  2129. this._callbacks = this._callbacks || {};
  2130. return this._callbacks[event] || [];
  2131. };
  2132. /**
  2133. * Check if this emitter has `event` handlers.
  2134. *
  2135. * @param {String} event
  2136. * @return {Boolean}
  2137. * @api public
  2138. */
  2139. Emitter.prototype.hasListeners = function(event){
  2140. return !! this.listeners(event).length;
  2141. };
  2142. },{}],17:[function(_dereq_,module,exports){
  2143. module.exports = function(a, b){
  2144. var fn = function(){};
  2145. fn.prototype = b.prototype;
  2146. a.prototype = new fn;
  2147. a.prototype.constructor = a;
  2148. };
  2149. },{}],18:[function(_dereq_,module,exports){
  2150. /**
  2151. * This is the web browser implementation of `debug()`.
  2152. *
  2153. * Expose `debug()` as the module.
  2154. */
  2155. exports = module.exports = _dereq_('./debug');
  2156. exports.log = log;
  2157. exports.formatArgs = formatArgs;
  2158. exports.save = save;
  2159. exports.load = load;
  2160. exports.useColors = useColors;
  2161. exports.storage = 'undefined' != typeof chrome
  2162. && 'undefined' != typeof chrome.storage
  2163. ? chrome.storage.local
  2164. : localstorage();
  2165. /**
  2166. * Colors.
  2167. */
  2168. exports.colors = [
  2169. 'lightseagreen',
  2170. 'forestgreen',
  2171. 'goldenrod',
  2172. 'dodgerblue',
  2173. 'darkorchid',
  2174. 'crimson'
  2175. ];
  2176. /**
  2177. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  2178. * and the Firebug extension (any Firefox version) are known
  2179. * to support "%c" CSS customizations.
  2180. *
  2181. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  2182. */
  2183. function useColors() {
  2184. // is webkit? http://stackoverflow.com/a/16459606/376773
  2185. return ('WebkitAppearance' in document.documentElement.style) ||
  2186. // is firebug? http://stackoverflow.com/a/398120/376773
  2187. (window.console && (console.firebug || (console.exception && console.table))) ||
  2188. // is firefox >= v31?
  2189. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  2190. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  2191. }
  2192. /**
  2193. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  2194. */
  2195. exports.formatters.j = function(v) {
  2196. return JSON.stringify(v);
  2197. };
  2198. /**
  2199. * Colorize log arguments if enabled.
  2200. *
  2201. * @api public
  2202. */
  2203. function formatArgs() {
  2204. var args = arguments;
  2205. var useColors = this.useColors;
  2206. args[0] = (useColors ? '%c' : '')
  2207. + this.namespace
  2208. + (useColors ? ' %c' : ' ')
  2209. + args[0]
  2210. + (useColors ? '%c ' : ' ')
  2211. + '+' + exports.humanize(this.diff);
  2212. if (!useColors) return args;
  2213. var c = 'color: ' + this.color;
  2214. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  2215. // the final "%c" is somewhat tricky, because there could be other
  2216. // arguments passed either before or after the %c, so we need to
  2217. // figure out the correct index to insert the CSS into
  2218. var index = 0;
  2219. var lastC = 0;
  2220. args[0].replace(/%[a-z%]/g, function(match) {
  2221. if ('%%' === match) return;
  2222. index++;
  2223. if ('%c' === match) {
  2224. // we only are interested in the *last* %c
  2225. // (the user may have provided their own)
  2226. lastC = index;
  2227. }
  2228. });
  2229. args.splice(lastC, 0, c);
  2230. return args;
  2231. }
  2232. /**
  2233. * Invokes `console.log()` when available.
  2234. * No-op when `console.log` is not a "function".
  2235. *
  2236. * @api public
  2237. */
  2238. function log() {
  2239. // this hackery is required for IE8/9, where
  2240. // the `console.log` function doesn't have 'apply'
  2241. return 'object' === typeof console
  2242. && console.log
  2243. && Function.prototype.apply.call(console.log, console, arguments);
  2244. }
  2245. /**
  2246. * Save `namespaces`.
  2247. *
  2248. * @param {String} namespaces
  2249. * @api private
  2250. */
  2251. function save(namespaces) {
  2252. try {
  2253. if (null == namespaces) {
  2254. exports.storage.removeItem('debug');
  2255. } else {
  2256. exports.storage.debug = namespaces;
  2257. }
  2258. } catch(e) {}
  2259. }
  2260. /**
  2261. * Load `namespaces`.
  2262. *
  2263. * @return {String} returns the previously persisted debug modes
  2264. * @api private
  2265. */
  2266. function load() {
  2267. var r;
  2268. try {
  2269. r = exports.storage.debug;
  2270. } catch(e) {}
  2271. return r;
  2272. }
  2273. /**
  2274. * Enable namespaces listed in `localStorage.debug` initially.
  2275. */
  2276. exports.enable(load());
  2277. /**
  2278. * Localstorage attempts to return the localstorage.
  2279. *
  2280. * This is necessary because safari throws
  2281. * when a user disables cookies/localstorage
  2282. * and you attempt to access it.
  2283. *
  2284. * @return {LocalStorage}
  2285. * @api private
  2286. */
  2287. function localstorage(){
  2288. try {
  2289. return window.localStorage;
  2290. } catch (e) {}
  2291. }
  2292. },{"./debug":19}],19:[function(_dereq_,module,exports){
  2293. /**
  2294. * This is the common logic for both the Node.js and web browser
  2295. * implementations of `debug()`.
  2296. *
  2297. * Expose `debug()` as the module.
  2298. */
  2299. exports = module.exports = debug;
  2300. exports.coerce = coerce;
  2301. exports.disable = disable;
  2302. exports.enable = enable;
  2303. exports.enabled = enabled;
  2304. exports.humanize = _dereq_('ms');
  2305. /**
  2306. * The currently active debug mode names, and names to skip.
  2307. */
  2308. exports.names = [];
  2309. exports.skips = [];
  2310. /**
  2311. * Map of special "%n" handling functions, for the debug "format" argument.
  2312. *
  2313. * Valid key names are a single, lowercased letter, i.e. "n".
  2314. */
  2315. exports.formatters = {};
  2316. /**
  2317. * Previously assigned color.
  2318. */
  2319. var prevColor = 0;
  2320. /**
  2321. * Previous log timestamp.
  2322. */
  2323. var prevTime;
  2324. /**
  2325. * Select a color.
  2326. *
  2327. * @return {Number}
  2328. * @api private
  2329. */
  2330. function selectColor() {
  2331. return exports.colors[prevColor++ % exports.colors.length];
  2332. }
  2333. /**
  2334. * Create a debugger with the given `namespace`.
  2335. *
  2336. * @param {String} namespace
  2337. * @return {Function}
  2338. * @api public
  2339. */
  2340. function debug(namespace) {
  2341. // define the `disabled` version
  2342. function disabled() {
  2343. }
  2344. disabled.enabled = false;
  2345. // define the `enabled` version
  2346. function enabled() {
  2347. var self = enabled;
  2348. // set `diff` timestamp
  2349. var curr = +new Date();
  2350. var ms = curr - (prevTime || curr);
  2351. self.diff = ms;
  2352. self.prev = prevTime;
  2353. self.curr = curr;
  2354. prevTime = curr;
  2355. // add the `color` if not set
  2356. if (null == self.useColors) self.useColors = exports.useColors();
  2357. if (null == self.color && self.useColors) self.color = selectColor();
  2358. var args = Array.prototype.slice.call(arguments);
  2359. args[0] = exports.coerce(args[0]);
  2360. if ('string' !== typeof args[0]) {
  2361. // anything else let's inspect with %o
  2362. args = ['%o'].concat(args);
  2363. }
  2364. // apply any `formatters` transformations
  2365. var index = 0;
  2366. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  2367. // if we encounter an escaped % then don't increase the array index
  2368. if (match === '%%') return match;
  2369. index++;
  2370. var formatter = exports.formatters[format];
  2371. if ('function' === typeof formatter) {
  2372. var val = args[index];
  2373. match = formatter.call(self, val);
  2374. // now we need to remove `args[index]` since it's inlined in the `format`
  2375. args.splice(index, 1);
  2376. index--;
  2377. }
  2378. return match;
  2379. });
  2380. if ('function' === typeof exports.formatArgs) {
  2381. args = exports.formatArgs.apply(self, args);
  2382. }
  2383. var logFn = enabled.log || exports.log || console.log.bind(console);
  2384. logFn.apply(self, args);
  2385. }
  2386. enabled.enabled = true;
  2387. var fn = exports.enabled(namespace) ? enabled : disabled;
  2388. fn.namespace = namespace;
  2389. return fn;
  2390. }
  2391. /**
  2392. * Enables a debug mode by namespaces. This can include modes
  2393. * separated by a colon and wildcards.
  2394. *
  2395. * @param {String} namespaces
  2396. * @api public
  2397. */
  2398. function enable(namespaces) {
  2399. exports.save(namespaces);
  2400. var split = (namespaces || '').split(/[\s,]+/);
  2401. var len = split.length;
  2402. for (var i = 0; i < len; i++) {
  2403. if (!split[i]) continue; // ignore empty strings
  2404. namespaces = split[i].replace(/\*/g, '.*?');
  2405. if (namespaces[0] === '-') {
  2406. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2407. } else {
  2408. exports.names.push(new RegExp('^' + namespaces + '$'));
  2409. }
  2410. }
  2411. }
  2412. /**
  2413. * Disable debug output.
  2414. *
  2415. * @api public
  2416. */
  2417. function disable() {
  2418. exports.enable('');
  2419. }
  2420. /**
  2421. * Returns true if the given mode name is enabled, false otherwise.
  2422. *
  2423. * @param {String} name
  2424. * @return {Boolean}
  2425. * @api public
  2426. */
  2427. function enabled(name) {
  2428. var i, len;
  2429. for (i = 0, len = exports.skips.length; i < len; i++) {
  2430. if (exports.skips[i].test(name)) {
  2431. return false;
  2432. }
  2433. }
  2434. for (i = 0, len = exports.names.length; i < len; i++) {
  2435. if (exports.names[i].test(name)) {
  2436. return true;
  2437. }
  2438. }
  2439. return false;
  2440. }
  2441. /**
  2442. * Coerce `val`.
  2443. *
  2444. * @param {Mixed} val
  2445. * @return {Mixed}
  2446. * @api private
  2447. */
  2448. function coerce(val) {
  2449. if (val instanceof Error) return val.stack || val.message;
  2450. return val;
  2451. }
  2452. },{"ms":26}],20:[function(_dereq_,module,exports){
  2453. (function (global){
  2454. /**
  2455. * Module dependencies.
  2456. */
  2457. var keys = _dereq_('./keys');
  2458. var hasBinary = _dereq_('has-binary');
  2459. var sliceBuffer = _dereq_('arraybuffer.slice');
  2460. var base64encoder = _dereq_('base64-arraybuffer');
  2461. var after = _dereq_('after');
  2462. var utf8 = _dereq_('utf8');
  2463. /**
  2464. * Check if we are running an android browser. That requires us to use
  2465. * ArrayBuffer with polling transports...
  2466. *
  2467. * http://ghinda.net/jpeg-blob-ajax-android/
  2468. */
  2469. var isAndroid = navigator.userAgent.match(/Android/i);
  2470. /**
  2471. * Check if we are running in PhantomJS.
  2472. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  2473. * https://github.com/ariya/phantomjs/issues/11395
  2474. * @type boolean
  2475. */
  2476. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  2477. /**
  2478. * When true, avoids using Blobs to encode payloads.
  2479. * @type boolean
  2480. */
  2481. var dontSendBlobs = isAndroid || isPhantomJS;
  2482. /**
  2483. * Current protocol version.
  2484. */
  2485. exports.protocol = 3;
  2486. /**
  2487. * Packet types.
  2488. */
  2489. var packets = exports.packets = {
  2490. open: 0 // non-ws
  2491. , close: 1 // non-ws
  2492. , ping: 2
  2493. , pong: 3
  2494. , message: 4
  2495. , upgrade: 5
  2496. , noop: 6
  2497. };
  2498. var packetslist = keys(packets);
  2499. /**
  2500. * Premade error packet.
  2501. */
  2502. var err = { type: 'error', data: 'parser error' };
  2503. /**
  2504. * Create a blob api even for blob builder when vendor prefixes exist
  2505. */
  2506. var Blob = _dereq_('blob');
  2507. /**
  2508. * Encodes a packet.
  2509. *
  2510. * <packet type id> [ <data> ]
  2511. *
  2512. * Example:
  2513. *
  2514. * 5hello world
  2515. * 3
  2516. * 4
  2517. *
  2518. * Binary is encoded in an identical principle
  2519. *
  2520. * @api private
  2521. */
  2522. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  2523. if ('function' == typeof supportsBinary) {
  2524. callback = supportsBinary;
  2525. supportsBinary = false;
  2526. }
  2527. if ('function' == typeof utf8encode) {
  2528. callback = utf8encode;
  2529. utf8encode = null;
  2530. }
  2531. var data = (packet.data === undefined)
  2532. ? undefined
  2533. : packet.data.buffer || packet.data;
  2534. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  2535. return encodeArrayBuffer(packet, supportsBinary, callback);
  2536. } else if (Blob && data instanceof global.Blob) {
  2537. return encodeBlob(packet, supportsBinary, callback);
  2538. }
  2539. // might be an object with { base64: true, data: dataAsBase64String }
  2540. if (data && data.base64) {
  2541. return encodeBase64Object(packet, callback);
  2542. }
  2543. // Sending data as a utf-8 string
  2544. var encoded = packets[packet.type];
  2545. // data fragment is optional
  2546. if (undefined !== packet.data) {
  2547. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  2548. }
  2549. return callback('' + encoded);
  2550. };
  2551. function encodeBase64Object(packet, callback) {
  2552. // packet data is an object { base64: true, data: dataAsBase64String }
  2553. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  2554. return callback(message);
  2555. }
  2556. /**
  2557. * Encode packet helpers for binary types
  2558. */
  2559. function encodeArrayBuffer(packet, supportsBinary, callback) {
  2560. if (!supportsBinary) {
  2561. return exports.encodeBase64Packet(packet, callback);
  2562. }
  2563. var data = packet.data;
  2564. var contentArray = new Uint8Array(data);
  2565. var resultBuffer = new Uint8Array(1 + data.byteLength);
  2566. resultBuffer[0] = packets[packet.type];
  2567. for (var i = 0; i < contentArray.length; i++) {
  2568. resultBuffer[i+1] = contentArray[i];
  2569. }
  2570. return callback(resultBuffer.buffer);
  2571. }
  2572. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  2573. if (!supportsBinary) {
  2574. return exports.encodeBase64Packet(packet, callback);
  2575. }
  2576. var fr = new FileReader();
  2577. fr.onload = function() {
  2578. packet.data = fr.result;
  2579. exports.encodePacket(packet, supportsBinary, true, callback);
  2580. };
  2581. return fr.readAsArrayBuffer(packet.data);
  2582. }
  2583. function encodeBlob(packet, supportsBinary, callback) {
  2584. if (!supportsBinary) {
  2585. return exports.encodeBase64Packet(packet, callback);
  2586. }
  2587. if (dontSendBlobs) {
  2588. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  2589. }
  2590. var length = new Uint8Array(1);
  2591. length[0] = packets[packet.type];
  2592. var blob = new Blob([length.buffer, packet.data]);
  2593. return callback(blob);
  2594. }
  2595. /**
  2596. * Encodes a packet with binary data in a base64 string
  2597. *
  2598. * @param {Object} packet, has `type` and `data`
  2599. * @return {String} base64 encoded message
  2600. */
  2601. exports.encodeBase64Packet = function(packet, callback) {
  2602. var message = 'b' + exports.packets[packet.type];
  2603. if (Blob && packet.data instanceof global.Blob) {
  2604. var fr = new FileReader();
  2605. fr.onload = function() {
  2606. var b64 = fr.result.split(',')[1];
  2607. callback(message + b64);
  2608. };
  2609. return fr.readAsDataURL(packet.data);
  2610. }
  2611. var b64data;
  2612. try {
  2613. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  2614. } catch (e) {
  2615. // iPhone Safari doesn't let you apply with typed arrays
  2616. var typed = new Uint8Array(packet.data);
  2617. var basic = new Array(typed.length);
  2618. for (var i = 0; i < typed.length; i++) {
  2619. basic[i] = typed[i];
  2620. }
  2621. b64data = String.fromCharCode.apply(null, basic);
  2622. }
  2623. message += global.btoa(b64data);
  2624. return callback(message);
  2625. };
  2626. /**
  2627. * Decodes a packet. Changes format to Blob if requested.
  2628. *
  2629. * @return {Object} with `type` and `data` (if any)
  2630. * @api private
  2631. */
  2632. exports.decodePacket = function (data, binaryType, utf8decode) {
  2633. // String data
  2634. if (typeof data == 'string' || data === undefined) {
  2635. if (data.charAt(0) == 'b') {
  2636. return exports.decodeBase64Packet(data.substr(1), binaryType);
  2637. }
  2638. if (utf8decode) {
  2639. try {
  2640. data = utf8.decode(data);
  2641. } catch (e) {
  2642. return err;
  2643. }
  2644. }
  2645. var type = data.charAt(0);
  2646. if (Number(type) != type || !packetslist[type]) {
  2647. return err;
  2648. }
  2649. if (data.length > 1) {
  2650. return { type: packetslist[type], data: data.substring(1) };
  2651. } else {
  2652. return { type: packetslist[type] };
  2653. }
  2654. }
  2655. var asArray = new Uint8Array(data);
  2656. var type = asArray[0];
  2657. var rest = sliceBuffer(data, 1);
  2658. if (Blob && binaryType === 'blob') {
  2659. rest = new Blob([rest]);
  2660. }
  2661. return { type: packetslist[type], data: rest };
  2662. };
  2663. /**
  2664. * Decodes a packet encoded in a base64 string
  2665. *
  2666. * @param {String} base64 encoded message
  2667. * @return {Object} with `type` and `data` (if any)
  2668. */
  2669. exports.decodeBase64Packet = function(msg, binaryType) {
  2670. var type = packetslist[msg.charAt(0)];
  2671. if (!global.ArrayBuffer) {
  2672. return { type: type, data: { base64: true, data: msg.substr(1) } };
  2673. }
  2674. var data = base64encoder.decode(msg.substr(1));
  2675. if (binaryType === 'blob' && Blob) {
  2676. data = new Blob([data]);
  2677. }
  2678. return { type: type, data: data };
  2679. };
  2680. /**
  2681. * Encodes multiple messages (payload).
  2682. *
  2683. * <length>:data
  2684. *
  2685. * Example:
  2686. *
  2687. * 11:hello world2:hi
  2688. *
  2689. * If any contents are binary, they will be encoded as base64 strings. Base64
  2690. * encoded strings are marked with a b before the length specifier
  2691. *
  2692. * @param {Array} packets
  2693. * @api private
  2694. */
  2695. exports.encodePayload = function (packets, supportsBinary, callback) {
  2696. if (typeof supportsBinary == 'function') {
  2697. callback = supportsBinary;
  2698. supportsBinary = null;
  2699. }
  2700. var isBinary = hasBinary(packets);
  2701. if (supportsBinary && isBinary) {
  2702. if (Blob && !dontSendBlobs) {
  2703. return exports.encodePayloadAsBlob(packets, callback);
  2704. }
  2705. return exports.encodePayloadAsArrayBuffer(packets, callback);
  2706. }
  2707. if (!packets.length) {
  2708. return callback('0:');
  2709. }
  2710. function setLengthHeader(message) {
  2711. return message.length + ':' + message;
  2712. }
  2713. function encodeOne(packet, doneCallback) {
  2714. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  2715. doneCallback(null, setLengthHeader(message));
  2716. });
  2717. }
  2718. map(packets, encodeOne, function(err, results) {
  2719. return callback(results.join(''));
  2720. });
  2721. };
  2722. /**
  2723. * Async array map using after
  2724. */
  2725. function map(ary, each, done) {
  2726. var result = new Array(ary.length);
  2727. var next = after(ary.length, done);
  2728. var eachWithIndex = function(i, el, cb) {
  2729. each(el, function(error, msg) {
  2730. result[i] = msg;
  2731. cb(error, result);
  2732. });
  2733. };
  2734. for (var i = 0; i < ary.length; i++) {
  2735. eachWithIndex(i, ary[i], next);
  2736. }
  2737. }
  2738. /*
  2739. * Decodes data when a payload is maybe expected. Possible binary contents are
  2740. * decoded from their base64 representation
  2741. *
  2742. * @param {String} data, callback method
  2743. * @api public
  2744. */
  2745. exports.decodePayload = function (data, binaryType, callback) {
  2746. if (typeof data != 'string') {
  2747. return exports.decodePayloadAsBinary(data, binaryType, callback);
  2748. }
  2749. if (typeof binaryType === 'function') {
  2750. callback = binaryType;
  2751. binaryType = null;
  2752. }
  2753. var packet;
  2754. if (data == '') {
  2755. // parser error - ignoring payload
  2756. return callback(err, 0, 1);
  2757. }
  2758. var length = ''
  2759. , n, msg;
  2760. for (var i = 0, l = data.length; i < l; i++) {
  2761. var chr = data.charAt(i);
  2762. if (':' != chr) {
  2763. length += chr;
  2764. } else {
  2765. if ('' == length || (length != (n = Number(length)))) {
  2766. // parser error - ignoring payload
  2767. return callback(err, 0, 1);
  2768. }
  2769. msg = data.substr(i + 1, n);
  2770. if (length != msg.length) {
  2771. // parser error - ignoring payload
  2772. return callback(err, 0, 1);
  2773. }
  2774. if (msg.length) {
  2775. packet = exports.decodePacket(msg, binaryType, true);
  2776. if (err.type == packet.type && err.data == packet.data) {
  2777. // parser error in individual packet - ignoring payload
  2778. return callback(err, 0, 1);
  2779. }
  2780. var ret = callback(packet, i + n, l);
  2781. if (false === ret) return;
  2782. }
  2783. // advance cursor
  2784. i += n;
  2785. length = '';
  2786. }
  2787. }
  2788. if (length != '') {
  2789. // parser error - ignoring payload
  2790. return callback(err, 0, 1);
  2791. }
  2792. };
  2793. /**
  2794. * Encodes multiple messages (payload) as binary.
  2795. *
  2796. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  2797. * 255><data>
  2798. *
  2799. * Example:
  2800. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  2801. *
  2802. * @param {Array} packets
  2803. * @return {ArrayBuffer} encoded payload
  2804. * @api private
  2805. */
  2806. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  2807. if (!packets.length) {
  2808. return callback(new ArrayBuffer(0));
  2809. }
  2810. function encodeOne(packet, doneCallback) {
  2811. exports.encodePacket(packet, true, true, function(data) {
  2812. return doneCallback(null, data);
  2813. });
  2814. }
  2815. map(packets, encodeOne, function(err, encodedPackets) {
  2816. var totalLength = encodedPackets.reduce(function(acc, p) {
  2817. var len;
  2818. if (typeof p === 'string'){
  2819. len = p.length;
  2820. } else {
  2821. len = p.byteLength;
  2822. }
  2823. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  2824. }, 0);
  2825. var resultArray = new Uint8Array(totalLength);
  2826. var bufferIndex = 0;
  2827. encodedPackets.forEach(function(p) {
  2828. var isString = typeof p === 'string';
  2829. var ab = p;
  2830. if (isString) {
  2831. var view = new Uint8Array(p.length);
  2832. for (var i = 0; i < p.length; i++) {
  2833. view[i] = p.charCodeAt(i);
  2834. }
  2835. ab = view.buffer;
  2836. }
  2837. if (isString) { // not true binary
  2838. resultArray[bufferIndex++] = 0;
  2839. } else { // true binary
  2840. resultArray[bufferIndex++] = 1;
  2841. }
  2842. var lenStr = ab.byteLength.toString();
  2843. for (var i = 0; i < lenStr.length; i++) {
  2844. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  2845. }
  2846. resultArray[bufferIndex++] = 255;
  2847. var view = new Uint8Array(ab);
  2848. for (var i = 0; i < view.length; i++) {
  2849. resultArray[bufferIndex++] = view[i];
  2850. }
  2851. });
  2852. return callback(resultArray.buffer);
  2853. });
  2854. };
  2855. /**
  2856. * Encode as Blob
  2857. */
  2858. exports.encodePayloadAsBlob = function(packets, callback) {
  2859. function encodeOne(packet, doneCallback) {
  2860. exports.encodePacket(packet, true, true, function(encoded) {
  2861. var binaryIdentifier = new Uint8Array(1);
  2862. binaryIdentifier[0] = 1;
  2863. if (typeof encoded === 'string') {
  2864. var view = new Uint8Array(encoded.length);
  2865. for (var i = 0; i < encoded.length; i++) {
  2866. view[i] = encoded.charCodeAt(i);
  2867. }
  2868. encoded = view.buffer;
  2869. binaryIdentifier[0] = 0;
  2870. }
  2871. var len = (encoded instanceof ArrayBuffer)
  2872. ? encoded.byteLength
  2873. : encoded.size;
  2874. var lenStr = len.toString();
  2875. var lengthAry = new Uint8Array(lenStr.length + 1);
  2876. for (var i = 0; i < lenStr.length; i++) {
  2877. lengthAry[i] = parseInt(lenStr[i]);
  2878. }
  2879. lengthAry[lenStr.length] = 255;
  2880. if (Blob) {
  2881. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  2882. doneCallback(null, blob);
  2883. }
  2884. });
  2885. }
  2886. map(packets, encodeOne, function(err, results) {
  2887. return callback(new Blob(results));
  2888. });
  2889. };
  2890. /*
  2891. * Decodes data when a payload is maybe expected. Strings are decoded by
  2892. * interpreting each byte as a key code for entries marked to start with 0. See
  2893. * description of encodePayloadAsBinary
  2894. *
  2895. * @param {ArrayBuffer} data, callback method
  2896. * @api public
  2897. */
  2898. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  2899. if (typeof binaryType === 'function') {
  2900. callback = binaryType;
  2901. binaryType = null;
  2902. }
  2903. var bufferTail = data;
  2904. var buffers = [];
  2905. var numberTooLong = false;
  2906. while (bufferTail.byteLength > 0) {
  2907. var tailArray = new Uint8Array(bufferTail);
  2908. var isString = tailArray[0] === 0;
  2909. var msgLength = '';
  2910. for (var i = 1; ; i++) {
  2911. if (tailArray[i] == 255) break;
  2912. if (msgLength.length > 310) {
  2913. numberTooLong = true;
  2914. break;
  2915. }
  2916. msgLength += tailArray[i];
  2917. }
  2918. if(numberTooLong) return callback(err, 0, 1);
  2919. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  2920. msgLength = parseInt(msgLength);
  2921. var msg = sliceBuffer(bufferTail, 0, msgLength);
  2922. if (isString) {
  2923. try {
  2924. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  2925. } catch (e) {
  2926. // iPhone Safari doesn't let you apply to typed arrays
  2927. var typed = new Uint8Array(msg);
  2928. msg = '';
  2929. for (var i = 0; i < typed.length; i++) {
  2930. msg += String.fromCharCode(typed[i]);
  2931. }
  2932. }
  2933. }
  2934. buffers.push(msg);
  2935. bufferTail = sliceBuffer(bufferTail, msgLength);
  2936. }
  2937. var total = buffers.length;
  2938. buffers.forEach(function(buffer, i) {
  2939. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  2940. });
  2941. };
  2942. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {})
  2943. },{"./keys":21,"after":11,"arraybuffer.slice":12,"base64-arraybuffer":13,"blob":14,"has-binary":22,"utf8":30}],21:[function(_dereq_,module,exports){
  2944. /**
  2945. * Gets the keys for an object.
  2946. *
  2947. * @return {Array} keys
  2948. * @api private
  2949. */
  2950. module.exports = Object.keys || function keys (obj){
  2951. var arr = [];
  2952. var has = Object.prototype.hasOwnProperty;
  2953. for (var i in obj) {
  2954. if (has.call(obj, i)) {
  2955. arr.push(i);
  2956. }
  2957. }
  2958. return arr;
  2959. };
  2960. },{}],22:[function(_dereq_,module,exports){
  2961. (function (global){
  2962. /*
  2963. * Module requirements.
  2964. */
  2965. var isArray = _dereq_('isarray');
  2966. /**
  2967. * Module exports.
  2968. */
  2969. module.exports = hasBinary;
  2970. /**
  2971. * Checks for binary data.
  2972. *
  2973. * Right now only Buffer and ArrayBuffer are supported..
  2974. *
  2975. * @param {Object} anything
  2976. * @api public
  2977. */
  2978. function hasBinary(data) {
  2979. function _hasBinary(obj) {
  2980. if (!obj) return false;
  2981. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  2982. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  2983. (global.Blob && obj instanceof Blob) ||
  2984. (global.File && obj instanceof File)
  2985. ) {
  2986. return true;
  2987. }
  2988. if (isArray(obj)) {
  2989. for (var i = 0; i < obj.length; i++) {
  2990. if (_hasBinary(obj[i])) {
  2991. return true;
  2992. }
  2993. }
  2994. } else if (obj && 'object' == typeof obj) {
  2995. if (obj.toJSON) {
  2996. obj = obj.toJSON();
  2997. }
  2998. for (var key in obj) {
  2999. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  3000. return true;
  3001. }
  3002. }
  3003. }
  3004. return false;
  3005. }
  3006. return _hasBinary(data);
  3007. }
  3008. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {})
  3009. },{"isarray":25}],23:[function(_dereq_,module,exports){
  3010. /**
  3011. * Module exports.
  3012. *
  3013. * Logic borrowed from Modernizr:
  3014. *
  3015. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  3016. */
  3017. try {
  3018. module.exports = typeof XMLHttpRequest !== 'undefined' &&
  3019. 'withCredentials' in new XMLHttpRequest();
  3020. } catch (err) {
  3021. // if XMLHttp support is disabled in IE then it will throw
  3022. // when trying to create
  3023. module.exports = false;
  3024. }
  3025. },{}],24:[function(_dereq_,module,exports){
  3026. var indexOf = [].indexOf;
  3027. module.exports = function(arr, obj){
  3028. if (indexOf) return arr.indexOf(obj);
  3029. for (var i = 0; i < arr.length; ++i) {
  3030. if (arr[i] === obj) return i;
  3031. }
  3032. return -1;
  3033. };
  3034. },{}],25:[function(_dereq_,module,exports){
  3035. module.exports = Array.isArray || function (arr) {
  3036. return Object.prototype.toString.call(arr) == '[object Array]';
  3037. };
  3038. },{}],26:[function(_dereq_,module,exports){
  3039. /**
  3040. * Helpers.
  3041. */
  3042. var s = 1000;
  3043. var m = s * 60;
  3044. var h = m * 60;
  3045. var d = h * 24;
  3046. var y = d * 365.25;
  3047. /**
  3048. * Parse or format the given `val`.
  3049. *
  3050. * Options:
  3051. *
  3052. * - `long` verbose formatting [false]
  3053. *
  3054. * @param {String|Number} val
  3055. * @param {Object} options
  3056. * @return {String|Number}
  3057. * @api public
  3058. */
  3059. module.exports = function(val, options){
  3060. options = options || {};
  3061. if ('string' == typeof val) return parse(val);
  3062. return options.long
  3063. ? long(val)
  3064. : short(val);
  3065. };
  3066. /**
  3067. * Parse the given `str` and return milliseconds.
  3068. *
  3069. * @param {String} str
  3070. * @return {Number}
  3071. * @api private
  3072. */
  3073. function parse(str) {
  3074. str = '' + str;
  3075. if (str.length > 10000) return;
  3076. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
  3077. if (!match) return;
  3078. var n = parseFloat(match[1]);
  3079. var type = (match[2] || 'ms').toLowerCase();
  3080. switch (type) {
  3081. case 'years':
  3082. case 'year':
  3083. case 'yrs':
  3084. case 'yr':
  3085. case 'y':
  3086. return n * y;
  3087. case 'days':
  3088. case 'day':
  3089. case 'd':
  3090. return n * d;
  3091. case 'hours':
  3092. case 'hour':
  3093. case 'hrs':
  3094. case 'hr':
  3095. case 'h':
  3096. return n * h;
  3097. case 'minutes':
  3098. case 'minute':
  3099. case 'mins':
  3100. case 'min':
  3101. case 'm':
  3102. return n * m;
  3103. case 'seconds':
  3104. case 'second':
  3105. case 'secs':
  3106. case 'sec':
  3107. case 's':
  3108. return n * s;
  3109. case 'milliseconds':
  3110. case 'millisecond':
  3111. case 'msecs':
  3112. case 'msec':
  3113. case 'ms':
  3114. return n;
  3115. }
  3116. }
  3117. /**
  3118. * Short format for `ms`.
  3119. *
  3120. * @param {Number} ms
  3121. * @return {String}
  3122. * @api private
  3123. */
  3124. function short(ms) {
  3125. if (ms >= d) return Math.round(ms / d) + 'd';
  3126. if (ms >= h) return Math.round(ms / h) + 'h';
  3127. if (ms >= m) return Math.round(ms / m) + 'm';
  3128. if (ms >= s) return Math.round(ms / s) + 's';
  3129. return ms + 'ms';
  3130. }
  3131. /**
  3132. * Long format for `ms`.
  3133. *
  3134. * @param {Number} ms
  3135. * @return {String}
  3136. * @api private
  3137. */
  3138. function long(ms) {
  3139. return plural(ms, d, 'day')
  3140. || plural(ms, h, 'hour')
  3141. || plural(ms, m, 'minute')
  3142. || plural(ms, s, 'second')
  3143. || ms + ' ms';
  3144. }
  3145. /**
  3146. * Pluralization helper.
  3147. */
  3148. function plural(ms, n, name) {
  3149. if (ms < n) return;
  3150. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  3151. return Math.ceil(ms / n) + ' ' + name + 's';
  3152. }
  3153. },{}],27:[function(_dereq_,module,exports){
  3154. (function (global){
  3155. /**
  3156. * JSON parse.
  3157. *
  3158. * @see Based on jQuery#parseJSON (MIT) and JSON2
  3159. * @api private
  3160. */
  3161. var rvalidchars = /^[\],:{}\s]*$/;
  3162. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  3163. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  3164. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  3165. var rtrimLeft = /^\s+/;
  3166. var rtrimRight = /\s+$/;
  3167. module.exports = function parsejson(data) {
  3168. if ('string' != typeof data || !data) {
  3169. return null;
  3170. }
  3171. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  3172. // Attempt to parse using the native JSON parser first
  3173. if (global.JSON && JSON.parse) {
  3174. return JSON.parse(data);
  3175. }
  3176. if (rvalidchars.test(data.replace(rvalidescape, '@')
  3177. .replace(rvalidtokens, ']')
  3178. .replace(rvalidbraces, ''))) {
  3179. return (new Function('return ' + data))();
  3180. }
  3181. };
  3182. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {})
  3183. },{}],28:[function(_dereq_,module,exports){
  3184. /**
  3185. * Compiles a querystring
  3186. * Returns string representation of the object
  3187. *
  3188. * @param {Object}
  3189. * @api private
  3190. */
  3191. exports.encode = function (obj) {
  3192. var str = '';
  3193. for (var i in obj) {
  3194. if (obj.hasOwnProperty(i)) {
  3195. if (str.length) str += '&';
  3196. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  3197. }
  3198. }
  3199. return str;
  3200. };
  3201. /**
  3202. * Parses a simple querystring into an object
  3203. *
  3204. * @param {String} qs
  3205. * @api private
  3206. */
  3207. exports.decode = function(qs){
  3208. var qry = {};
  3209. var pairs = qs.split('&');
  3210. for (var i = 0, l = pairs.length; i < l; i++) {
  3211. var pair = pairs[i].split('=');
  3212. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  3213. }
  3214. return qry;
  3215. };
  3216. },{}],29:[function(_dereq_,module,exports){
  3217. /**
  3218. * Parses an URI
  3219. *
  3220. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  3221. * @api private
  3222. */
  3223. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  3224. var parts = [
  3225. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  3226. ];
  3227. module.exports = function parseuri(str) {
  3228. var src = str,
  3229. b = str.indexOf('['),
  3230. e = str.indexOf(']');
  3231. if (b != -1 && e != -1) {
  3232. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  3233. }
  3234. var m = re.exec(str || ''),
  3235. uri = {},
  3236. i = 14;
  3237. while (i--) {
  3238. uri[parts[i]] = m[i] || '';
  3239. }
  3240. if (b != -1 && e != -1) {
  3241. uri.source = src;
  3242. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  3243. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  3244. uri.ipv6uri = true;
  3245. }
  3246. return uri;
  3247. };
  3248. },{}],30:[function(_dereq_,module,exports){
  3249. (function (global){
  3250. /*! https://mths.be/utf8js v2.0.0 by @mathias */
  3251. ;(function(root) {
  3252. // Detect free variables `exports`
  3253. var freeExports = typeof exports == 'object' && exports;
  3254. // Detect free variable `module`
  3255. var freeModule = typeof module == 'object' && module &&
  3256. module.exports == freeExports && module;
  3257. // Detect free variable `global`, from Node.js or Browserified code,
  3258. // and use it as `root`
  3259. var freeGlobal = typeof global == 'object' && global;
  3260. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  3261. root = freeGlobal;
  3262. }
  3263. /*--------------------------------------------------------------------------*/
  3264. var stringFromCharCode = String.fromCharCode;
  3265. // Taken from https://mths.be/punycode
  3266. function ucs2decode(string) {
  3267. var output = [];
  3268. var counter = 0;
  3269. var length = string.length;
  3270. var value;
  3271. var extra;
  3272. while (counter < length) {
  3273. value = string.charCodeAt(counter++);
  3274. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  3275. // high surrogate, and there is a next character
  3276. extra = string.charCodeAt(counter++);
  3277. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  3278. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  3279. } else {
  3280. // unmatched surrogate; only append this code unit, in case the next
  3281. // code unit is the high surrogate of a surrogate pair
  3282. output.push(value);
  3283. counter--;
  3284. }
  3285. } else {
  3286. output.push(value);
  3287. }
  3288. }
  3289. return output;
  3290. }
  3291. // Taken from https://mths.be/punycode
  3292. function ucs2encode(array) {
  3293. var length = array.length;
  3294. var index = -1;
  3295. var value;
  3296. var output = '';
  3297. while (++index < length) {
  3298. value = array[index];
  3299. if (value > 0xFFFF) {
  3300. value -= 0x10000;
  3301. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  3302. value = 0xDC00 | value & 0x3FF;
  3303. }
  3304. output += stringFromCharCode(value);
  3305. }
  3306. return output;
  3307. }
  3308. function checkScalarValue(codePoint) {
  3309. if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
  3310. throw Error(
  3311. 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
  3312. ' is not a scalar value'
  3313. );
  3314. }
  3315. }
  3316. /*--------------------------------------------------------------------------*/
  3317. function createByte(codePoint, shift) {
  3318. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  3319. }
  3320. function encodeCodePoint(codePoint) {
  3321. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  3322. return stringFromCharCode(codePoint);
  3323. }
  3324. var symbol = '';
  3325. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  3326. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  3327. }
  3328. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  3329. checkScalarValue(codePoint);
  3330. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  3331. symbol += createByte(codePoint, 6);
  3332. }
  3333. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  3334. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  3335. symbol += createByte(codePoint, 12);
  3336. symbol += createByte(codePoint, 6);
  3337. }
  3338. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  3339. return symbol;
  3340. }
  3341. function utf8encode(string) {
  3342. var codePoints = ucs2decode(string);
  3343. var length = codePoints.length;
  3344. var index = -1;
  3345. var codePoint;
  3346. var byteString = '';
  3347. while (++index < length) {
  3348. codePoint = codePoints[index];
  3349. byteString += encodeCodePoint(codePoint);
  3350. }
  3351. return byteString;
  3352. }
  3353. /*--------------------------------------------------------------------------*/
  3354. function readContinuationByte() {
  3355. if (byteIndex >= byteCount) {
  3356. throw Error('Invalid byte index');
  3357. }
  3358. var continuationByte = byteArray[byteIndex] & 0xFF;
  3359. byteIndex++;
  3360. if ((continuationByte & 0xC0) == 0x80) {
  3361. return continuationByte & 0x3F;
  3362. }
  3363. // If we end up here, it’s not a continuation byte
  3364. throw Error('Invalid continuation byte');
  3365. }
  3366. function decodeSymbol() {
  3367. var byte1;
  3368. var byte2;
  3369. var byte3;
  3370. var byte4;
  3371. var codePoint;
  3372. if (byteIndex > byteCount) {
  3373. throw Error('Invalid byte index');
  3374. }
  3375. if (byteIndex == byteCount) {
  3376. return false;
  3377. }
  3378. // Read first byte
  3379. byte1 = byteArray[byteIndex] & 0xFF;
  3380. byteIndex++;
  3381. // 1-byte sequence (no continuation bytes)
  3382. if ((byte1 & 0x80) == 0) {
  3383. return byte1;
  3384. }
  3385. // 2-byte sequence
  3386. if ((byte1 & 0xE0) == 0xC0) {
  3387. var byte2 = readContinuationByte();
  3388. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  3389. if (codePoint >= 0x80) {
  3390. return codePoint;
  3391. } else {
  3392. throw Error('Invalid continuation byte');
  3393. }
  3394. }
  3395. // 3-byte sequence (may include unpaired surrogates)
  3396. if ((byte1 & 0xF0) == 0xE0) {
  3397. byte2 = readContinuationByte();
  3398. byte3 = readContinuationByte();
  3399. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  3400. if (codePoint >= 0x0800) {
  3401. checkScalarValue(codePoint);
  3402. return codePoint;
  3403. } else {
  3404. throw Error('Invalid continuation byte');
  3405. }
  3406. }
  3407. // 4-byte sequence
  3408. if ((byte1 & 0xF8) == 0xF0) {
  3409. byte2 = readContinuationByte();
  3410. byte3 = readContinuationByte();
  3411. byte4 = readContinuationByte();
  3412. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  3413. (byte3 << 0x06) | byte4;
  3414. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  3415. return codePoint;
  3416. }
  3417. }
  3418. throw Error('Invalid UTF-8 detected');
  3419. }
  3420. var byteArray;
  3421. var byteCount;
  3422. var byteIndex;
  3423. function utf8decode(byteString) {
  3424. byteArray = ucs2decode(byteString);
  3425. byteCount = byteArray.length;
  3426. byteIndex = 0;
  3427. var codePoints = [];
  3428. var tmp;
  3429. while ((tmp = decodeSymbol()) !== false) {
  3430. codePoints.push(tmp);
  3431. }
  3432. return ucs2encode(codePoints);
  3433. }
  3434. /*--------------------------------------------------------------------------*/
  3435. var utf8 = {
  3436. 'version': '2.0.0',
  3437. 'encode': utf8encode,
  3438. 'decode': utf8decode
  3439. };
  3440. // Some AMD build optimizers, like r.js, check for specific condition patterns
  3441. // like the following:
  3442. if (
  3443. typeof define == 'function' &&
  3444. typeof define.amd == 'object' &&
  3445. define.amd
  3446. ) {
  3447. define(function() {
  3448. return utf8;
  3449. });
  3450. } else if (freeExports && !freeExports.nodeType) {
  3451. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  3452. freeModule.exports = utf8;
  3453. } else { // in Narwhal or RingoJS v0.7.0-
  3454. var object = {};
  3455. var hasOwnProperty = object.hasOwnProperty;
  3456. for (var key in utf8) {
  3457. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  3458. }
  3459. }
  3460. } else { // in Rhino or a web browser
  3461. root.utf8 = utf8;
  3462. }
  3463. }(this));
  3464. }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {})
  3465. },{}],31:[function(_dereq_,module,exports){
  3466. 'use strict';
  3467. var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
  3468. , length = 64
  3469. , map = {}
  3470. , seed = 0
  3471. , i = 0
  3472. , prev;
  3473. /**
  3474. * Return a string representing the specified number.
  3475. *
  3476. * @param {Number} num The number to convert.
  3477. * @returns {String} The string representation of the number.
  3478. * @api public
  3479. */
  3480. function encode(num) {
  3481. var encoded = '';
  3482. do {
  3483. encoded = alphabet[num % length] + encoded;
  3484. num = Math.floor(num / length);
  3485. } while (num > 0);
  3486. return encoded;
  3487. }
  3488. /**
  3489. * Return the integer value specified by the given string.
  3490. *
  3491. * @param {String} str The string to convert.
  3492. * @returns {Number} The integer value represented by the string.
  3493. * @api public
  3494. */
  3495. function decode(str) {
  3496. var decoded = 0;
  3497. for (i = 0; i < str.length; i++) {
  3498. decoded = decoded * length + map[str.charAt(i)];
  3499. }
  3500. return decoded;
  3501. }
  3502. /**
  3503. * Yeast: A tiny growing id generator.
  3504. *
  3505. * @returns {String} A unique id.
  3506. * @api public
  3507. */
  3508. function yeast() {
  3509. var now = encode(+new Date());
  3510. if (now !== prev) return seed = 0, prev = now;
  3511. return now +'.'+ encode(seed++);
  3512. }
  3513. //
  3514. // Map each character to its index.
  3515. //
  3516. for (; i < length; i++) map[alphabet[i]] = i;
  3517. //
  3518. // Expose the `yeast`, `encode` and `decode` functions.
  3519. //
  3520. yeast.encode = encode;
  3521. yeast.decode = decode;
  3522. module.exports = yeast;
  3523. },{}]},{},[1])(1)
  3524. });