Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

socket.io.js 116KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560
  1. /*!
  2. * Socket.IO v4.5.3
  3. * (c) 2014-2022 Guillermo Rauch
  4. * Released under the MIT License.
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  8. typeof define === 'function' && define.amd ? define(factory) :
  9. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.io = factory());
  10. })(this, (function () { 'use strict';
  11. function _typeof(obj) {
  12. "@babel/helpers - typeof";
  13. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
  14. return typeof obj;
  15. } : function (obj) {
  16. return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  17. }, _typeof(obj);
  18. }
  19. function _classCallCheck(instance, Constructor) {
  20. if (!(instance instanceof Constructor)) {
  21. throw new TypeError("Cannot call a class as a function");
  22. }
  23. }
  24. function _defineProperties(target, props) {
  25. for (var i = 0; i < props.length; i++) {
  26. var descriptor = props[i];
  27. descriptor.enumerable = descriptor.enumerable || false;
  28. descriptor.configurable = true;
  29. if ("value" in descriptor) descriptor.writable = true;
  30. Object.defineProperty(target, descriptor.key, descriptor);
  31. }
  32. }
  33. function _createClass(Constructor, protoProps, staticProps) {
  34. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  35. if (staticProps) _defineProperties(Constructor, staticProps);
  36. Object.defineProperty(Constructor, "prototype", {
  37. writable: false
  38. });
  39. return Constructor;
  40. }
  41. function _extends() {
  42. _extends = Object.assign ? Object.assign.bind() : function (target) {
  43. for (var i = 1; i < arguments.length; i++) {
  44. var source = arguments[i];
  45. for (var key in source) {
  46. if (Object.prototype.hasOwnProperty.call(source, key)) {
  47. target[key] = source[key];
  48. }
  49. }
  50. }
  51. return target;
  52. };
  53. return _extends.apply(this, arguments);
  54. }
  55. function _inherits(subClass, superClass) {
  56. if (typeof superClass !== "function" && superClass !== null) {
  57. throw new TypeError("Super expression must either be null or a function");
  58. }
  59. subClass.prototype = Object.create(superClass && superClass.prototype, {
  60. constructor: {
  61. value: subClass,
  62. writable: true,
  63. configurable: true
  64. }
  65. });
  66. Object.defineProperty(subClass, "prototype", {
  67. writable: false
  68. });
  69. if (superClass) _setPrototypeOf(subClass, superClass);
  70. }
  71. function _getPrototypeOf(o) {
  72. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
  73. return o.__proto__ || Object.getPrototypeOf(o);
  74. };
  75. return _getPrototypeOf(o);
  76. }
  77. function _setPrototypeOf(o, p) {
  78. _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
  79. o.__proto__ = p;
  80. return o;
  81. };
  82. return _setPrototypeOf(o, p);
  83. }
  84. function _isNativeReflectConstruct() {
  85. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  86. if (Reflect.construct.sham) return false;
  87. if (typeof Proxy === "function") return true;
  88. try {
  89. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  90. return true;
  91. } catch (e) {
  92. return false;
  93. }
  94. }
  95. function _construct(Parent, args, Class) {
  96. if (_isNativeReflectConstruct()) {
  97. _construct = Reflect.construct.bind();
  98. } else {
  99. _construct = function _construct(Parent, args, Class) {
  100. var a = [null];
  101. a.push.apply(a, args);
  102. var Constructor = Function.bind.apply(Parent, a);
  103. var instance = new Constructor();
  104. if (Class) _setPrototypeOf(instance, Class.prototype);
  105. return instance;
  106. };
  107. }
  108. return _construct.apply(null, arguments);
  109. }
  110. function _isNativeFunction(fn) {
  111. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  112. }
  113. function _wrapNativeSuper(Class) {
  114. var _cache = typeof Map === "function" ? new Map() : undefined;
  115. _wrapNativeSuper = function _wrapNativeSuper(Class) {
  116. if (Class === null || !_isNativeFunction(Class)) return Class;
  117. if (typeof Class !== "function") {
  118. throw new TypeError("Super expression must either be null or a function");
  119. }
  120. if (typeof _cache !== "undefined") {
  121. if (_cache.has(Class)) return _cache.get(Class);
  122. _cache.set(Class, Wrapper);
  123. }
  124. function Wrapper() {
  125. return _construct(Class, arguments, _getPrototypeOf(this).constructor);
  126. }
  127. Wrapper.prototype = Object.create(Class.prototype, {
  128. constructor: {
  129. value: Wrapper,
  130. enumerable: false,
  131. writable: true,
  132. configurable: true
  133. }
  134. });
  135. return _setPrototypeOf(Wrapper, Class);
  136. };
  137. return _wrapNativeSuper(Class);
  138. }
  139. function _assertThisInitialized(self) {
  140. if (self === void 0) {
  141. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  142. }
  143. return self;
  144. }
  145. function _possibleConstructorReturn(self, call) {
  146. if (call && (typeof call === "object" || typeof call === "function")) {
  147. return call;
  148. } else if (call !== void 0) {
  149. throw new TypeError("Derived constructors may only return object or undefined");
  150. }
  151. return _assertThisInitialized(self);
  152. }
  153. function _createSuper(Derived) {
  154. var hasNativeReflectConstruct = _isNativeReflectConstruct();
  155. return function _createSuperInternal() {
  156. var Super = _getPrototypeOf(Derived),
  157. result;
  158. if (hasNativeReflectConstruct) {
  159. var NewTarget = _getPrototypeOf(this).constructor;
  160. result = Reflect.construct(Super, arguments, NewTarget);
  161. } else {
  162. result = Super.apply(this, arguments);
  163. }
  164. return _possibleConstructorReturn(this, result);
  165. };
  166. }
  167. function _superPropBase(object, property) {
  168. while (!Object.prototype.hasOwnProperty.call(object, property)) {
  169. object = _getPrototypeOf(object);
  170. if (object === null) break;
  171. }
  172. return object;
  173. }
  174. function _get() {
  175. if (typeof Reflect !== "undefined" && Reflect.get) {
  176. _get = Reflect.get.bind();
  177. } else {
  178. _get = function _get(target, property, receiver) {
  179. var base = _superPropBase(target, property);
  180. if (!base) return;
  181. var desc = Object.getOwnPropertyDescriptor(base, property);
  182. if (desc.get) {
  183. return desc.get.call(arguments.length < 3 ? target : receiver);
  184. }
  185. return desc.value;
  186. };
  187. }
  188. return _get.apply(this, arguments);
  189. }
  190. function _unsupportedIterableToArray(o, minLen) {
  191. if (!o) return;
  192. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  193. var n = Object.prototype.toString.call(o).slice(8, -1);
  194. if (n === "Object" && o.constructor) n = o.constructor.name;
  195. if (n === "Map" || n === "Set") return Array.from(o);
  196. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  197. }
  198. function _arrayLikeToArray(arr, len) {
  199. if (len == null || len > arr.length) len = arr.length;
  200. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  201. return arr2;
  202. }
  203. function _createForOfIteratorHelper(o, allowArrayLike) {
  204. var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
  205. if (!it) {
  206. if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
  207. if (it) o = it;
  208. var i = 0;
  209. var F = function () {};
  210. return {
  211. s: F,
  212. n: function () {
  213. if (i >= o.length) return {
  214. done: true
  215. };
  216. return {
  217. done: false,
  218. value: o[i++]
  219. };
  220. },
  221. e: function (e) {
  222. throw e;
  223. },
  224. f: F
  225. };
  226. }
  227. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  228. }
  229. var normalCompletion = true,
  230. didErr = false,
  231. err;
  232. return {
  233. s: function () {
  234. it = it.call(o);
  235. },
  236. n: function () {
  237. var step = it.next();
  238. normalCompletion = step.done;
  239. return step;
  240. },
  241. e: function (e) {
  242. didErr = true;
  243. err = e;
  244. },
  245. f: function () {
  246. try {
  247. if (!normalCompletion && it.return != null) it.return();
  248. } finally {
  249. if (didErr) throw err;
  250. }
  251. }
  252. };
  253. }
  254. var PACKET_TYPES = Object.create(null); // no Map = no polyfill
  255. PACKET_TYPES["open"] = "0";
  256. PACKET_TYPES["close"] = "1";
  257. PACKET_TYPES["ping"] = "2";
  258. PACKET_TYPES["pong"] = "3";
  259. PACKET_TYPES["message"] = "4";
  260. PACKET_TYPES["upgrade"] = "5";
  261. PACKET_TYPES["noop"] = "6";
  262. var PACKET_TYPES_REVERSE = Object.create(null);
  263. Object.keys(PACKET_TYPES).forEach(function (key) {
  264. PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
  265. });
  266. var ERROR_PACKET = {
  267. type: "error",
  268. data: "parser error"
  269. };
  270. var withNativeBlob$1 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
  271. var withNativeArrayBuffer$2 = typeof ArrayBuffer === "function"; // ArrayBuffer.isView method is not defined in IE10
  272. var isView$1 = function isView(obj) {
  273. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
  274. };
  275. var encodePacket = function encodePacket(_ref, supportsBinary, callback) {
  276. var type = _ref.type,
  277. data = _ref.data;
  278. if (withNativeBlob$1 && data instanceof Blob) {
  279. if (supportsBinary) {
  280. return callback(data);
  281. } else {
  282. return encodeBlobAsBase64(data, callback);
  283. }
  284. } else if (withNativeArrayBuffer$2 && (data instanceof ArrayBuffer || isView$1(data))) {
  285. if (supportsBinary) {
  286. return callback(data);
  287. } else {
  288. return encodeBlobAsBase64(new Blob([data]), callback);
  289. }
  290. } // plain string
  291. return callback(PACKET_TYPES[type] + (data || ""));
  292. };
  293. var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) {
  294. var fileReader = new FileReader();
  295. fileReader.onload = function () {
  296. var content = fileReader.result.split(",")[1];
  297. callback("b" + content);
  298. };
  299. return fileReader.readAsDataURL(data);
  300. };
  301. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Use a lookup table to find the index.
  302. var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
  303. for (var i$1 = 0; i$1 < chars.length; i$1++) {
  304. lookup$1[chars.charCodeAt(i$1)] = i$1;
  305. }
  306. var decode$1 = function decode(base64) {
  307. var bufferLength = base64.length * 0.75,
  308. len = base64.length,
  309. i,
  310. p = 0,
  311. encoded1,
  312. encoded2,
  313. encoded3,
  314. encoded4;
  315. if (base64[base64.length - 1] === '=') {
  316. bufferLength--;
  317. if (base64[base64.length - 2] === '=') {
  318. bufferLength--;
  319. }
  320. }
  321. var arraybuffer = new ArrayBuffer(bufferLength),
  322. bytes = new Uint8Array(arraybuffer);
  323. for (i = 0; i < len; i += 4) {
  324. encoded1 = lookup$1[base64.charCodeAt(i)];
  325. encoded2 = lookup$1[base64.charCodeAt(i + 1)];
  326. encoded3 = lookup$1[base64.charCodeAt(i + 2)];
  327. encoded4 = lookup$1[base64.charCodeAt(i + 3)];
  328. bytes[p++] = encoded1 << 2 | encoded2 >> 4;
  329. bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
  330. bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  331. }
  332. return arraybuffer;
  333. };
  334. var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function";
  335. var decodePacket = function decodePacket(encodedPacket, binaryType) {
  336. if (typeof encodedPacket !== "string") {
  337. return {
  338. type: "message",
  339. data: mapBinary(encodedPacket, binaryType)
  340. };
  341. }
  342. var type = encodedPacket.charAt(0);
  343. if (type === "b") {
  344. return {
  345. type: "message",
  346. data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
  347. };
  348. }
  349. var packetType = PACKET_TYPES_REVERSE[type];
  350. if (!packetType) {
  351. return ERROR_PACKET;
  352. }
  353. return encodedPacket.length > 1 ? {
  354. type: PACKET_TYPES_REVERSE[type],
  355. data: encodedPacket.substring(1)
  356. } : {
  357. type: PACKET_TYPES_REVERSE[type]
  358. };
  359. };
  360. var decodeBase64Packet = function decodeBase64Packet(data, binaryType) {
  361. if (withNativeArrayBuffer$1) {
  362. var decoded = decode$1(data);
  363. return mapBinary(decoded, binaryType);
  364. } else {
  365. return {
  366. base64: true,
  367. data: data
  368. }; // fallback for old browsers
  369. }
  370. };
  371. var mapBinary = function mapBinary(data, binaryType) {
  372. switch (binaryType) {
  373. case "blob":
  374. return data instanceof ArrayBuffer ? new Blob([data]) : data;
  375. case "arraybuffer":
  376. default:
  377. return data;
  378. // assuming the data is already an ArrayBuffer
  379. }
  380. };
  381. var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text
  382. var encodePayload = function encodePayload(packets, callback) {
  383. // some packets may be added to the array while encoding, so the initial length must be saved
  384. var length = packets.length;
  385. var encodedPackets = new Array(length);
  386. var count = 0;
  387. packets.forEach(function (packet, i) {
  388. // force base64 encoding for binary packets
  389. encodePacket(packet, false, function (encodedPacket) {
  390. encodedPackets[i] = encodedPacket;
  391. if (++count === length) {
  392. callback(encodedPackets.join(SEPARATOR));
  393. }
  394. });
  395. });
  396. };
  397. var decodePayload = function decodePayload(encodedPayload, binaryType) {
  398. var encodedPackets = encodedPayload.split(SEPARATOR);
  399. var packets = [];
  400. for (var i = 0; i < encodedPackets.length; i++) {
  401. var decodedPacket = decodePacket(encodedPackets[i], binaryType);
  402. packets.push(decodedPacket);
  403. if (decodedPacket.type === "error") {
  404. break;
  405. }
  406. }
  407. return packets;
  408. };
  409. var protocol$1 = 4;
  410. /**
  411. * Initialize a new `Emitter`.
  412. *
  413. * @api public
  414. */
  415. function Emitter(obj) {
  416. if (obj) return mixin(obj);
  417. }
  418. /**
  419. * Mixin the emitter properties.
  420. *
  421. * @param {Object} obj
  422. * @return {Object}
  423. * @api private
  424. */
  425. function mixin(obj) {
  426. for (var key in Emitter.prototype) {
  427. obj[key] = Emitter.prototype[key];
  428. }
  429. return obj;
  430. }
  431. /**
  432. * Listen on the given `event` with `fn`.
  433. *
  434. * @param {String} event
  435. * @param {Function} fn
  436. * @return {Emitter}
  437. * @api public
  438. */
  439. Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
  440. this._callbacks = this._callbacks || {};
  441. (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
  442. return this;
  443. };
  444. /**
  445. * Adds an `event` listener that will be invoked a single
  446. * time then automatically removed.
  447. *
  448. * @param {String} event
  449. * @param {Function} fn
  450. * @return {Emitter}
  451. * @api public
  452. */
  453. Emitter.prototype.once = function (event, fn) {
  454. function on() {
  455. this.off(event, on);
  456. fn.apply(this, arguments);
  457. }
  458. on.fn = fn;
  459. this.on(event, on);
  460. return this;
  461. };
  462. /**
  463. * Remove the given callback for `event` or all
  464. * registered callbacks.
  465. *
  466. * @param {String} event
  467. * @param {Function} fn
  468. * @return {Emitter}
  469. * @api public
  470. */
  471. Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
  472. this._callbacks = this._callbacks || {}; // all
  473. if (0 == arguments.length) {
  474. this._callbacks = {};
  475. return this;
  476. } // specific event
  477. var callbacks = this._callbacks['$' + event];
  478. if (!callbacks) return this; // remove all handlers
  479. if (1 == arguments.length) {
  480. delete this._callbacks['$' + event];
  481. return this;
  482. } // remove specific handler
  483. var cb;
  484. for (var i = 0; i < callbacks.length; i++) {
  485. cb = callbacks[i];
  486. if (cb === fn || cb.fn === fn) {
  487. callbacks.splice(i, 1);
  488. break;
  489. }
  490. } // Remove event specific arrays for event types that no
  491. // one is subscribed for to avoid memory leak.
  492. if (callbacks.length === 0) {
  493. delete this._callbacks['$' + event];
  494. }
  495. return this;
  496. };
  497. /**
  498. * Emit `event` with the given args.
  499. *
  500. * @param {String} event
  501. * @param {Mixed} ...
  502. * @return {Emitter}
  503. */
  504. Emitter.prototype.emit = function (event) {
  505. this._callbacks = this._callbacks || {};
  506. var args = new Array(arguments.length - 1),
  507. callbacks = this._callbacks['$' + event];
  508. for (var i = 1; i < arguments.length; i++) {
  509. args[i - 1] = arguments[i];
  510. }
  511. if (callbacks) {
  512. callbacks = callbacks.slice(0);
  513. for (var i = 0, len = callbacks.length; i < len; ++i) {
  514. callbacks[i].apply(this, args);
  515. }
  516. }
  517. return this;
  518. }; // alias used for reserved events (protected method)
  519. Emitter.prototype.emitReserved = Emitter.prototype.emit;
  520. /**
  521. * Return array of callbacks for `event`.
  522. *
  523. * @param {String} event
  524. * @return {Array}
  525. * @api public
  526. */
  527. Emitter.prototype.listeners = function (event) {
  528. this._callbacks = this._callbacks || {};
  529. return this._callbacks['$' + event] || [];
  530. };
  531. /**
  532. * Check if this emitter has `event` handlers.
  533. *
  534. * @param {String} event
  535. * @return {Boolean}
  536. * @api public
  537. */
  538. Emitter.prototype.hasListeners = function (event) {
  539. return !!this.listeners(event).length;
  540. };
  541. var globalThisShim = function () {
  542. if (typeof self !== "undefined") {
  543. return self;
  544. } else if (typeof window !== "undefined") {
  545. return window;
  546. } else {
  547. return Function("return this")();
  548. }
  549. }();
  550. function pick(obj) {
  551. for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  552. attr[_key - 1] = arguments[_key];
  553. }
  554. return attr.reduce(function (acc, k) {
  555. if (obj.hasOwnProperty(k)) {
  556. acc[k] = obj[k];
  557. }
  558. return acc;
  559. }, {});
  560. } // Keep a reference to the real timeout functions so they can be used when overridden
  561. var NATIVE_SET_TIMEOUT = setTimeout;
  562. var NATIVE_CLEAR_TIMEOUT = clearTimeout;
  563. function installTimerFunctions(obj, opts) {
  564. if (opts.useNativeTimers) {
  565. obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
  566. obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
  567. } else {
  568. obj.setTimeoutFn = setTimeout.bind(globalThisShim);
  569. obj.clearTimeoutFn = clearTimeout.bind(globalThisShim);
  570. }
  571. } // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
  572. var BASE64_OVERHEAD = 1.33; // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
  573. function byteLength(obj) {
  574. if (typeof obj === "string") {
  575. return utf8Length(obj);
  576. } // arraybuffer or blob
  577. return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
  578. }
  579. function utf8Length(str) {
  580. var c = 0,
  581. length = 0;
  582. for (var i = 0, l = str.length; i < l; i++) {
  583. c = str.charCodeAt(i);
  584. if (c < 0x80) {
  585. length += 1;
  586. } else if (c < 0x800) {
  587. length += 2;
  588. } else if (c < 0xd800 || c >= 0xe000) {
  589. length += 3;
  590. } else {
  591. i++;
  592. length += 4;
  593. }
  594. }
  595. return length;
  596. }
  597. var TransportError = /*#__PURE__*/function (_Error) {
  598. _inherits(TransportError, _Error);
  599. var _super = _createSuper(TransportError);
  600. function TransportError(reason, description, context) {
  601. var _this;
  602. _classCallCheck(this, TransportError);
  603. _this = _super.call(this, reason);
  604. _this.description = description;
  605. _this.context = context;
  606. _this.type = "TransportError";
  607. return _this;
  608. }
  609. return _createClass(TransportError);
  610. }( /*#__PURE__*/_wrapNativeSuper(Error));
  611. var Transport = /*#__PURE__*/function (_Emitter) {
  612. _inherits(Transport, _Emitter);
  613. var _super2 = _createSuper(Transport);
  614. /**
  615. * Transport abstract constructor.
  616. *
  617. * @param {Object} options.
  618. * @api private
  619. */
  620. function Transport(opts) {
  621. var _this2;
  622. _classCallCheck(this, Transport);
  623. _this2 = _super2.call(this);
  624. _this2.writable = false;
  625. installTimerFunctions(_assertThisInitialized(_this2), opts);
  626. _this2.opts = opts;
  627. _this2.query = opts.query;
  628. _this2.readyState = "";
  629. _this2.socket = opts.socket;
  630. return _this2;
  631. }
  632. /**
  633. * Emits an error.
  634. *
  635. * @param {String} reason
  636. * @param description
  637. * @param context - the error context
  638. * @return {Transport} for chaining
  639. * @api protected
  640. */
  641. _createClass(Transport, [{
  642. key: "onError",
  643. value: function onError(reason, description, context) {
  644. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "error", new TransportError(reason, description, context));
  645. return this;
  646. }
  647. /**
  648. * Opens the transport.
  649. *
  650. * @api public
  651. */
  652. }, {
  653. key: "open",
  654. value: function open() {
  655. if ("closed" === this.readyState || "" === this.readyState) {
  656. this.readyState = "opening";
  657. this.doOpen();
  658. }
  659. return this;
  660. }
  661. /**
  662. * Closes the transport.
  663. *
  664. * @api public
  665. */
  666. }, {
  667. key: "close",
  668. value: function close() {
  669. if ("opening" === this.readyState || "open" === this.readyState) {
  670. this.doClose();
  671. this.onClose();
  672. }
  673. return this;
  674. }
  675. /**
  676. * Sends multiple packets.
  677. *
  678. * @param {Array} packets
  679. * @api public
  680. */
  681. }, {
  682. key: "send",
  683. value: function send(packets) {
  684. if ("open" === this.readyState) {
  685. this.write(packets);
  686. }
  687. }
  688. /**
  689. * Called upon open
  690. *
  691. * @api protected
  692. */
  693. }, {
  694. key: "onOpen",
  695. value: function onOpen() {
  696. this.readyState = "open";
  697. this.writable = true;
  698. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "open");
  699. }
  700. /**
  701. * Called with data.
  702. *
  703. * @param {String} data
  704. * @api protected
  705. */
  706. }, {
  707. key: "onData",
  708. value: function onData(data) {
  709. var packet = decodePacket(data, this.socket.binaryType);
  710. this.onPacket(packet);
  711. }
  712. /**
  713. * Called with a decoded packet.
  714. *
  715. * @api protected
  716. */
  717. }, {
  718. key: "onPacket",
  719. value: function onPacket(packet) {
  720. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "packet", packet);
  721. }
  722. /**
  723. * Called upon close.
  724. *
  725. * @api protected
  726. */
  727. }, {
  728. key: "onClose",
  729. value: function onClose(details) {
  730. this.readyState = "closed";
  731. _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "close", details);
  732. }
  733. }]);
  734. return Transport;
  735. }(Emitter);
  736. // imported from https://github.com/unshiftio/yeast
  737. var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''),
  738. length = 64,
  739. map = {};
  740. var seed = 0,
  741. i = 0,
  742. prev;
  743. /**
  744. * Return a string representing the specified number.
  745. *
  746. * @param {Number} num The number to convert.
  747. * @returns {String} The string representation of the number.
  748. * @api public
  749. */
  750. function encode$1(num) {
  751. var encoded = '';
  752. do {
  753. encoded = alphabet[num % length] + encoded;
  754. num = Math.floor(num / length);
  755. } while (num > 0);
  756. return encoded;
  757. }
  758. /**
  759. * Yeast: A tiny growing id generator.
  760. *
  761. * @returns {String} A unique id.
  762. * @api public
  763. */
  764. function yeast() {
  765. var now = encode$1(+new Date());
  766. if (now !== prev) return seed = 0, prev = now;
  767. return now + '.' + encode$1(seed++);
  768. } //
  769. // Map each character to its index.
  770. //
  771. for (; i < length; i++) {
  772. map[alphabet[i]] = i;
  773. }
  774. // imported from https://github.com/galkn/querystring
  775. /**
  776. * Compiles a querystring
  777. * Returns string representation of the object
  778. *
  779. * @param {Object}
  780. * @api private
  781. */
  782. function encode(obj) {
  783. var str = '';
  784. for (var i in obj) {
  785. if (obj.hasOwnProperty(i)) {
  786. if (str.length) str += '&';
  787. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  788. }
  789. }
  790. return str;
  791. }
  792. /**
  793. * Parses a simple querystring into an object
  794. *
  795. * @param {String} qs
  796. * @api private
  797. */
  798. function decode(qs) {
  799. var qry = {};
  800. var pairs = qs.split('&');
  801. for (var i = 0, l = pairs.length; i < l; i++) {
  802. var pair = pairs[i].split('=');
  803. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  804. }
  805. return qry;
  806. }
  807. // imported from https://github.com/component/has-cors
  808. var value = false;
  809. try {
  810. value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest();
  811. } catch (err) {// if XMLHttp support is disabled in IE then it will throw
  812. // when trying to create
  813. }
  814. var hasCORS = value;
  815. // browser shim for xmlhttprequest module
  816. function XHR(opts) {
  817. var xdomain = opts.xdomain; // XMLHttpRequest can be disabled on IE
  818. try {
  819. if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  820. return new XMLHttpRequest();
  821. }
  822. } catch (e) {}
  823. if (!xdomain) {
  824. try {
  825. return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
  826. } catch (e) {}
  827. }
  828. }
  829. function empty() {}
  830. var hasXHR2 = function () {
  831. var xhr = new XHR({
  832. xdomain: false
  833. });
  834. return null != xhr.responseType;
  835. }();
  836. var Polling = /*#__PURE__*/function (_Transport) {
  837. _inherits(Polling, _Transport);
  838. var _super = _createSuper(Polling);
  839. /**
  840. * XHR Polling constructor.
  841. *
  842. * @param {Object} opts
  843. * @api public
  844. */
  845. function Polling(opts) {
  846. var _this;
  847. _classCallCheck(this, Polling);
  848. _this = _super.call(this, opts);
  849. _this.polling = false;
  850. if (typeof location !== "undefined") {
  851. var isSSL = "https:" === location.protocol;
  852. var port = location.port; // some user agents have empty `location.port`
  853. if (!port) {
  854. port = isSSL ? "443" : "80";
  855. }
  856. _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
  857. _this.xs = opts.secure !== isSSL;
  858. }
  859. /**
  860. * XHR supports binary
  861. */
  862. var forceBase64 = opts && opts.forceBase64;
  863. _this.supportsBinary = hasXHR2 && !forceBase64;
  864. return _this;
  865. }
  866. /**
  867. * Transport name.
  868. */
  869. _createClass(Polling, [{
  870. key: "name",
  871. get: function get() {
  872. return "polling";
  873. }
  874. /**
  875. * Opens the socket (triggers polling). We write a PING message to determine
  876. * when the transport is open.
  877. *
  878. * @api private
  879. */
  880. }, {
  881. key: "doOpen",
  882. value: function doOpen() {
  883. this.poll();
  884. }
  885. /**
  886. * Pauses polling.
  887. *
  888. * @param {Function} callback upon buffers are flushed and transport is paused
  889. * @api private
  890. */
  891. }, {
  892. key: "pause",
  893. value: function pause(onPause) {
  894. var _this2 = this;
  895. this.readyState = "pausing";
  896. var pause = function pause() {
  897. _this2.readyState = "paused";
  898. onPause();
  899. };
  900. if (this.polling || !this.writable) {
  901. var total = 0;
  902. if (this.polling) {
  903. total++;
  904. this.once("pollComplete", function () {
  905. --total || pause();
  906. });
  907. }
  908. if (!this.writable) {
  909. total++;
  910. this.once("drain", function () {
  911. --total || pause();
  912. });
  913. }
  914. } else {
  915. pause();
  916. }
  917. }
  918. /**
  919. * Starts polling cycle.
  920. *
  921. * @api public
  922. */
  923. }, {
  924. key: "poll",
  925. value: function poll() {
  926. this.polling = true;
  927. this.doPoll();
  928. this.emitReserved("poll");
  929. }
  930. /**
  931. * Overloads onData to detect payloads.
  932. *
  933. * @api private
  934. */
  935. }, {
  936. key: "onData",
  937. value: function onData(data) {
  938. var _this3 = this;
  939. var callback = function callback(packet) {
  940. // if its the first message we consider the transport open
  941. if ("opening" === _this3.readyState && packet.type === "open") {
  942. _this3.onOpen();
  943. } // if its a close packet, we close the ongoing requests
  944. if ("close" === packet.type) {
  945. _this3.onClose({
  946. description: "transport closed by the server"
  947. });
  948. return false;
  949. } // otherwise bypass onData and handle the message
  950. _this3.onPacket(packet);
  951. }; // decode payload
  952. decodePayload(data, this.socket.binaryType).forEach(callback); // if an event did not trigger closing
  953. if ("closed" !== this.readyState) {
  954. // if we got data we're not polling
  955. this.polling = false;
  956. this.emitReserved("pollComplete");
  957. if ("open" === this.readyState) {
  958. this.poll();
  959. }
  960. }
  961. }
  962. /**
  963. * For polling, send a close packet.
  964. *
  965. * @api private
  966. */
  967. }, {
  968. key: "doClose",
  969. value: function doClose() {
  970. var _this4 = this;
  971. var close = function close() {
  972. _this4.write([{
  973. type: "close"
  974. }]);
  975. };
  976. if ("open" === this.readyState) {
  977. close();
  978. } else {
  979. // in case we're trying to close while
  980. // handshaking is in progress (GH-164)
  981. this.once("open", close);
  982. }
  983. }
  984. /**
  985. * Writes a packets payload.
  986. *
  987. * @param {Array} data packets
  988. * @param {Function} drain callback
  989. * @api private
  990. */
  991. }, {
  992. key: "write",
  993. value: function write(packets) {
  994. var _this5 = this;
  995. this.writable = false;
  996. encodePayload(packets, function (data) {
  997. _this5.doWrite(data, function () {
  998. _this5.writable = true;
  999. _this5.emitReserved("drain");
  1000. });
  1001. });
  1002. }
  1003. /**
  1004. * Generates uri for connection.
  1005. *
  1006. * @api private
  1007. */
  1008. }, {
  1009. key: "uri",
  1010. value: function uri() {
  1011. var query = this.query || {};
  1012. var schema = this.opts.secure ? "https" : "http";
  1013. var port = ""; // cache busting is forced
  1014. if (false !== this.opts.timestampRequests) {
  1015. query[this.opts.timestampParam] = yeast();
  1016. }
  1017. if (!this.supportsBinary && !query.sid) {
  1018. query.b64 = 1;
  1019. } // avoid port if default for schema
  1020. if (this.opts.port && ("https" === schema && Number(this.opts.port) !== 443 || "http" === schema && Number(this.opts.port) !== 80)) {
  1021. port = ":" + this.opts.port;
  1022. }
  1023. var encodedQuery = encode(query);
  1024. var ipv6 = this.opts.hostname.indexOf(":") !== -1;
  1025. return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : "");
  1026. }
  1027. /**
  1028. * Creates a request.
  1029. *
  1030. * @param {String} method
  1031. * @api private
  1032. */
  1033. }, {
  1034. key: "request",
  1035. value: function request() {
  1036. var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  1037. _extends(opts, {
  1038. xd: this.xd,
  1039. xs: this.xs
  1040. }, this.opts);
  1041. return new Request(this.uri(), opts);
  1042. }
  1043. /**
  1044. * Sends data.
  1045. *
  1046. * @param {String} data to send.
  1047. * @param {Function} called upon flush.
  1048. * @api private
  1049. */
  1050. }, {
  1051. key: "doWrite",
  1052. value: function doWrite(data, fn) {
  1053. var _this6 = this;
  1054. var req = this.request({
  1055. method: "POST",
  1056. data: data
  1057. });
  1058. req.on("success", fn);
  1059. req.on("error", function (xhrStatus, context) {
  1060. _this6.onError("xhr post error", xhrStatus, context);
  1061. });
  1062. }
  1063. /**
  1064. * Starts a poll cycle.
  1065. *
  1066. * @api private
  1067. */
  1068. }, {
  1069. key: "doPoll",
  1070. value: function doPoll() {
  1071. var _this7 = this;
  1072. var req = this.request();
  1073. req.on("data", this.onData.bind(this));
  1074. req.on("error", function (xhrStatus, context) {
  1075. _this7.onError("xhr poll error", xhrStatus, context);
  1076. });
  1077. this.pollXhr = req;
  1078. }
  1079. }]);
  1080. return Polling;
  1081. }(Transport);
  1082. var Request = /*#__PURE__*/function (_Emitter) {
  1083. _inherits(Request, _Emitter);
  1084. var _super2 = _createSuper(Request);
  1085. /**
  1086. * Request constructor
  1087. *
  1088. * @param {Object} options
  1089. * @api public
  1090. */
  1091. function Request(uri, opts) {
  1092. var _this8;
  1093. _classCallCheck(this, Request);
  1094. _this8 = _super2.call(this);
  1095. installTimerFunctions(_assertThisInitialized(_this8), opts);
  1096. _this8.opts = opts;
  1097. _this8.method = opts.method || "GET";
  1098. _this8.uri = uri;
  1099. _this8.async = false !== opts.async;
  1100. _this8.data = undefined !== opts.data ? opts.data : null;
  1101. _this8.create();
  1102. return _this8;
  1103. }
  1104. /**
  1105. * Creates the XHR object and sends the request.
  1106. *
  1107. * @api private
  1108. */
  1109. _createClass(Request, [{
  1110. key: "create",
  1111. value: function create() {
  1112. var _this9 = this;
  1113. var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
  1114. opts.xdomain = !!this.opts.xd;
  1115. opts.xscheme = !!this.opts.xs;
  1116. var xhr = this.xhr = new XHR(opts);
  1117. try {
  1118. xhr.open(this.method, this.uri, this.async);
  1119. try {
  1120. if (this.opts.extraHeaders) {
  1121. xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
  1122. for (var i in this.opts.extraHeaders) {
  1123. if (this.opts.extraHeaders.hasOwnProperty(i)) {
  1124. xhr.setRequestHeader(i, this.opts.extraHeaders[i]);
  1125. }
  1126. }
  1127. }
  1128. } catch (e) {}
  1129. if ("POST" === this.method) {
  1130. try {
  1131. xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
  1132. } catch (e) {}
  1133. }
  1134. try {
  1135. xhr.setRequestHeader("Accept", "*/*");
  1136. } catch (e) {} // ie6 check
  1137. if ("withCredentials" in xhr) {
  1138. xhr.withCredentials = this.opts.withCredentials;
  1139. }
  1140. if (this.opts.requestTimeout) {
  1141. xhr.timeout = this.opts.requestTimeout;
  1142. }
  1143. xhr.onreadystatechange = function () {
  1144. if (4 !== xhr.readyState) return;
  1145. if (200 === xhr.status || 1223 === xhr.status) {
  1146. _this9.onLoad();
  1147. } else {
  1148. // make sure the `error` event handler that's user-set
  1149. // does not throw in the same tick and gets caught here
  1150. _this9.setTimeoutFn(function () {
  1151. _this9.onError(typeof xhr.status === "number" ? xhr.status : 0);
  1152. }, 0);
  1153. }
  1154. };
  1155. xhr.send(this.data);
  1156. } catch (e) {
  1157. // Need to defer since .create() is called directly from the constructor
  1158. // and thus the 'error' event can only be only bound *after* this exception
  1159. // occurs. Therefore, also, we cannot throw here at all.
  1160. this.setTimeoutFn(function () {
  1161. _this9.onError(e);
  1162. }, 0);
  1163. return;
  1164. }
  1165. if (typeof document !== "undefined") {
  1166. this.index = Request.requestsCount++;
  1167. Request.requests[this.index] = this;
  1168. }
  1169. }
  1170. /**
  1171. * Called upon error.
  1172. *
  1173. * @api private
  1174. */
  1175. }, {
  1176. key: "onError",
  1177. value: function onError(err) {
  1178. this.emitReserved("error", err, this.xhr);
  1179. this.cleanup(true);
  1180. }
  1181. /**
  1182. * Cleans up house.
  1183. *
  1184. * @api private
  1185. */
  1186. }, {
  1187. key: "cleanup",
  1188. value: function cleanup(fromError) {
  1189. if ("undefined" === typeof this.xhr || null === this.xhr) {
  1190. return;
  1191. }
  1192. this.xhr.onreadystatechange = empty;
  1193. if (fromError) {
  1194. try {
  1195. this.xhr.abort();
  1196. } catch (e) {}
  1197. }
  1198. if (typeof document !== "undefined") {
  1199. delete Request.requests[this.index];
  1200. }
  1201. this.xhr = null;
  1202. }
  1203. /**
  1204. * Called upon load.
  1205. *
  1206. * @api private
  1207. */
  1208. }, {
  1209. key: "onLoad",
  1210. value: function onLoad() {
  1211. var data = this.xhr.responseText;
  1212. if (data !== null) {
  1213. this.emitReserved("data", data);
  1214. this.emitReserved("success");
  1215. this.cleanup();
  1216. }
  1217. }
  1218. /**
  1219. * Aborts the request.
  1220. *
  1221. * @api public
  1222. */
  1223. }, {
  1224. key: "abort",
  1225. value: function abort() {
  1226. this.cleanup();
  1227. }
  1228. }]);
  1229. return Request;
  1230. }(Emitter);
  1231. Request.requestsCount = 0;
  1232. Request.requests = {};
  1233. /**
  1234. * Aborts pending requests when unloading the window. This is needed to prevent
  1235. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  1236. * emitted.
  1237. */
  1238. if (typeof document !== "undefined") {
  1239. // @ts-ignore
  1240. if (typeof attachEvent === "function") {
  1241. // @ts-ignore
  1242. attachEvent("onunload", unloadHandler);
  1243. } else if (typeof addEventListener === "function") {
  1244. var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
  1245. addEventListener(terminationEvent, unloadHandler, false);
  1246. }
  1247. }
  1248. function unloadHandler() {
  1249. for (var i in Request.requests) {
  1250. if (Request.requests.hasOwnProperty(i)) {
  1251. Request.requests[i].abort();
  1252. }
  1253. }
  1254. }
  1255. var nextTick = function () {
  1256. var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
  1257. if (isPromiseAvailable) {
  1258. return function (cb) {
  1259. return Promise.resolve().then(cb);
  1260. };
  1261. } else {
  1262. return function (cb, setTimeoutFn) {
  1263. return setTimeoutFn(cb, 0);
  1264. };
  1265. }
  1266. }();
  1267. var WebSocket = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
  1268. var usingBrowserWebSocket = true;
  1269. var defaultBinaryType = "arraybuffer";
  1270. var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
  1271. var WS = /*#__PURE__*/function (_Transport) {
  1272. _inherits(WS, _Transport);
  1273. var _super = _createSuper(WS);
  1274. /**
  1275. * WebSocket transport constructor.
  1276. *
  1277. * @api {Object} connection options
  1278. * @api public
  1279. */
  1280. function WS(opts) {
  1281. var _this;
  1282. _classCallCheck(this, WS);
  1283. _this = _super.call(this, opts);
  1284. _this.supportsBinary = !opts.forceBase64;
  1285. return _this;
  1286. }
  1287. /**
  1288. * Transport name.
  1289. *
  1290. * @api public
  1291. */
  1292. _createClass(WS, [{
  1293. key: "name",
  1294. get: function get() {
  1295. return "websocket";
  1296. }
  1297. /**
  1298. * Opens socket.
  1299. *
  1300. * @api private
  1301. */
  1302. }, {
  1303. key: "doOpen",
  1304. value: function doOpen() {
  1305. if (!this.check()) {
  1306. // let probe timeout
  1307. return;
  1308. }
  1309. var uri = this.uri();
  1310. var protocols = this.opts.protocols; // React Native only supports the 'headers' option, and will print a warning if anything else is passed
  1311. var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
  1312. if (this.opts.extraHeaders) {
  1313. opts.headers = this.opts.extraHeaders;
  1314. }
  1315. try {
  1316. this.ws = usingBrowserWebSocket && !isReactNative ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts);
  1317. } catch (err) {
  1318. return this.emitReserved("error", err);
  1319. }
  1320. this.ws.binaryType = this.socket.binaryType || defaultBinaryType;
  1321. this.addEventListeners();
  1322. }
  1323. /**
  1324. * Adds event listeners to the socket
  1325. *
  1326. * @api private
  1327. */
  1328. }, {
  1329. key: "addEventListeners",
  1330. value: function addEventListeners() {
  1331. var _this2 = this;
  1332. this.ws.onopen = function () {
  1333. if (_this2.opts.autoUnref) {
  1334. _this2.ws._socket.unref();
  1335. }
  1336. _this2.onOpen();
  1337. };
  1338. this.ws.onclose = function (closeEvent) {
  1339. return _this2.onClose({
  1340. description: "websocket connection closed",
  1341. context: closeEvent
  1342. });
  1343. };
  1344. this.ws.onmessage = function (ev) {
  1345. return _this2.onData(ev.data);
  1346. };
  1347. this.ws.onerror = function (e) {
  1348. return _this2.onError("websocket error", e);
  1349. };
  1350. }
  1351. /**
  1352. * Writes data to socket.
  1353. *
  1354. * @param {Array} array of packets.
  1355. * @api private
  1356. */
  1357. }, {
  1358. key: "write",
  1359. value: function write(packets) {
  1360. var _this3 = this;
  1361. this.writable = false; // encodePacket efficient as it uses WS framing
  1362. // no need for encodePayload
  1363. var _loop = function _loop(i) {
  1364. var packet = packets[i];
  1365. var lastPacket = i === packets.length - 1;
  1366. encodePacket(packet, _this3.supportsBinary, function (data) {
  1367. // always create a new object (GH-437)
  1368. var opts = {};
  1369. // have a chance of informing us about it yet, in that case send will
  1370. // throw an error
  1371. try {
  1372. if (usingBrowserWebSocket) {
  1373. // TypeError is thrown when passing the second argument on Safari
  1374. _this3.ws.send(data);
  1375. }
  1376. } catch (e) {}
  1377. if (lastPacket) {
  1378. // fake drain
  1379. // defer to next tick to allow Socket to clear writeBuffer
  1380. nextTick(function () {
  1381. _this3.writable = true;
  1382. _this3.emitReserved("drain");
  1383. }, _this3.setTimeoutFn);
  1384. }
  1385. });
  1386. };
  1387. for (var i = 0; i < packets.length; i++) {
  1388. _loop(i);
  1389. }
  1390. }
  1391. /**
  1392. * Closes socket.
  1393. *
  1394. * @api private
  1395. */
  1396. }, {
  1397. key: "doClose",
  1398. value: function doClose() {
  1399. if (typeof this.ws !== "undefined") {
  1400. this.ws.close();
  1401. this.ws = null;
  1402. }
  1403. }
  1404. /**
  1405. * Generates uri for connection.
  1406. *
  1407. * @api private
  1408. */
  1409. }, {
  1410. key: "uri",
  1411. value: function uri() {
  1412. var query = this.query || {};
  1413. var schema = this.opts.secure ? "wss" : "ws";
  1414. var port = ""; // avoid port if default for schema
  1415. if (this.opts.port && ("wss" === schema && Number(this.opts.port) !== 443 || "ws" === schema && Number(this.opts.port) !== 80)) {
  1416. port = ":" + this.opts.port;
  1417. } // append timestamp to URI
  1418. if (this.opts.timestampRequests) {
  1419. query[this.opts.timestampParam] = yeast();
  1420. } // communicate binary support capabilities
  1421. if (!this.supportsBinary) {
  1422. query.b64 = 1;
  1423. }
  1424. var encodedQuery = encode(query);
  1425. var ipv6 = this.opts.hostname.indexOf(":") !== -1;
  1426. return schema + "://" + (ipv6 ? "[" + this.opts.hostname + "]" : this.opts.hostname) + port + this.opts.path + (encodedQuery.length ? "?" + encodedQuery : "");
  1427. }
  1428. /**
  1429. * Feature detection for WebSocket.
  1430. *
  1431. * @return {Boolean} whether this transport is available.
  1432. * @api public
  1433. */
  1434. }, {
  1435. key: "check",
  1436. value: function check() {
  1437. return !!WebSocket;
  1438. }
  1439. }]);
  1440. return WS;
  1441. }(Transport);
  1442. var transports = {
  1443. websocket: WS,
  1444. polling: Polling
  1445. };
  1446. // imported from https://github.com/galkn/parseuri
  1447. /**
  1448. * Parses an URI
  1449. *
  1450. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  1451. * @api private
  1452. */
  1453. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  1454. var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'];
  1455. function parse(str) {
  1456. var src = str,
  1457. b = str.indexOf('['),
  1458. e = str.indexOf(']');
  1459. if (b != -1 && e != -1) {
  1460. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  1461. }
  1462. var m = re.exec(str || ''),
  1463. uri = {},
  1464. i = 14;
  1465. while (i--) {
  1466. uri[parts[i]] = m[i] || '';
  1467. }
  1468. if (b != -1 && e != -1) {
  1469. uri.source = src;
  1470. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  1471. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  1472. uri.ipv6uri = true;
  1473. }
  1474. uri.pathNames = pathNames(uri, uri['path']);
  1475. uri.queryKey = queryKey(uri, uri['query']);
  1476. return uri;
  1477. }
  1478. function pathNames(obj, path) {
  1479. var regx = /\/{2,9}/g,
  1480. names = path.replace(regx, "/").split("/");
  1481. if (path.slice(0, 1) == '/' || path.length === 0) {
  1482. names.splice(0, 1);
  1483. }
  1484. if (path.slice(-1) == '/') {
  1485. names.splice(names.length - 1, 1);
  1486. }
  1487. return names;
  1488. }
  1489. function queryKey(uri, query) {
  1490. var data = {};
  1491. query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
  1492. if ($1) {
  1493. data[$1] = $2;
  1494. }
  1495. });
  1496. return data;
  1497. }
  1498. var Socket$1 = /*#__PURE__*/function (_Emitter) {
  1499. _inherits(Socket, _Emitter);
  1500. var _super = _createSuper(Socket);
  1501. /**
  1502. * Socket constructor.
  1503. *
  1504. * @param {String|Object} uri or options
  1505. * @param {Object} opts - options
  1506. * @api public
  1507. */
  1508. function Socket(uri) {
  1509. var _this;
  1510. var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1511. _classCallCheck(this, Socket);
  1512. _this = _super.call(this);
  1513. if (uri && "object" === _typeof(uri)) {
  1514. opts = uri;
  1515. uri = null;
  1516. }
  1517. if (uri) {
  1518. uri = parse(uri);
  1519. opts.hostname = uri.host;
  1520. opts.secure = uri.protocol === "https" || uri.protocol === "wss";
  1521. opts.port = uri.port;
  1522. if (uri.query) opts.query = uri.query;
  1523. } else if (opts.host) {
  1524. opts.hostname = parse(opts.host).host;
  1525. }
  1526. installTimerFunctions(_assertThisInitialized(_this), opts);
  1527. _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
  1528. if (opts.hostname && !opts.port) {
  1529. // if no port is specified manually, use the protocol default
  1530. opts.port = _this.secure ? "443" : "80";
  1531. }
  1532. _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
  1533. _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80");
  1534. _this.transports = opts.transports || ["polling", "websocket"];
  1535. _this.readyState = "";
  1536. _this.writeBuffer = [];
  1537. _this.prevBufferLen = 0;
  1538. _this.opts = _extends({
  1539. path: "/engine.io",
  1540. agent: false,
  1541. withCredentials: false,
  1542. upgrade: true,
  1543. timestampParam: "t",
  1544. rememberUpgrade: false,
  1545. rejectUnauthorized: true,
  1546. perMessageDeflate: {
  1547. threshold: 1024
  1548. },
  1549. transportOptions: {},
  1550. closeOnBeforeunload: true
  1551. }, opts);
  1552. _this.opts.path = _this.opts.path.replace(/\/$/, "") + "/";
  1553. if (typeof _this.opts.query === "string") {
  1554. _this.opts.query = decode(_this.opts.query);
  1555. } // set on handshake
  1556. _this.id = null;
  1557. _this.upgrades = null;
  1558. _this.pingInterval = null;
  1559. _this.pingTimeout = null; // set on heartbeat
  1560. _this.pingTimeoutTimer = null;
  1561. if (typeof addEventListener === "function") {
  1562. if (_this.opts.closeOnBeforeunload) {
  1563. // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener
  1564. // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is
  1565. // closed/reloaded)
  1566. _this.beforeunloadEventListener = function () {
  1567. if (_this.transport) {
  1568. // silently close the transport
  1569. _this.transport.removeAllListeners();
  1570. _this.transport.close();
  1571. }
  1572. };
  1573. addEventListener("beforeunload", _this.beforeunloadEventListener, false);
  1574. }
  1575. if (_this.hostname !== "localhost") {
  1576. _this.offlineEventListener = function () {
  1577. _this.onClose("transport close", {
  1578. description: "network connection lost"
  1579. });
  1580. };
  1581. addEventListener("offline", _this.offlineEventListener, false);
  1582. }
  1583. }
  1584. _this.open();
  1585. return _this;
  1586. }
  1587. /**
  1588. * Creates transport of the given type.
  1589. *
  1590. * @param {String} transport name
  1591. * @return {Transport}
  1592. * @api private
  1593. */
  1594. _createClass(Socket, [{
  1595. key: "createTransport",
  1596. value: function createTransport(name) {
  1597. var query = _extends({}, this.opts.query); // append engine.io protocol identifier
  1598. query.EIO = protocol$1; // transport name
  1599. query.transport = name; // session id if we already have one
  1600. if (this.id) query.sid = this.id;
  1601. var opts = _extends({}, this.opts.transportOptions[name], this.opts, {
  1602. query: query,
  1603. socket: this,
  1604. hostname: this.hostname,
  1605. secure: this.secure,
  1606. port: this.port
  1607. });
  1608. return new transports[name](opts);
  1609. }
  1610. /**
  1611. * Initializes transport to use and starts probe.
  1612. *
  1613. * @api private
  1614. */
  1615. }, {
  1616. key: "open",
  1617. value: function open() {
  1618. var _this2 = this;
  1619. var transport;
  1620. if (this.opts.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1) {
  1621. transport = "websocket";
  1622. } else if (0 === this.transports.length) {
  1623. // Emit error on next tick so it can be listened to
  1624. this.setTimeoutFn(function () {
  1625. _this2.emitReserved("error", "No transports available");
  1626. }, 0);
  1627. return;
  1628. } else {
  1629. transport = this.transports[0];
  1630. }
  1631. this.readyState = "opening"; // Retry with the next transport if the transport is disabled (jsonp: false)
  1632. try {
  1633. transport = this.createTransport(transport);
  1634. } catch (e) {
  1635. this.transports.shift();
  1636. this.open();
  1637. return;
  1638. }
  1639. transport.open();
  1640. this.setTransport(transport);
  1641. }
  1642. /**
  1643. * Sets the current transport. Disables the existing one (if any).
  1644. *
  1645. * @api private
  1646. */
  1647. }, {
  1648. key: "setTransport",
  1649. value: function setTransport(transport) {
  1650. var _this3 = this;
  1651. if (this.transport) {
  1652. this.transport.removeAllListeners();
  1653. } // set up transport
  1654. this.transport = transport; // set up transport listeners
  1655. transport.on("drain", this.onDrain.bind(this)).on("packet", this.onPacket.bind(this)).on("error", this.onError.bind(this)).on("close", function (reason) {
  1656. return _this3.onClose("transport close", reason);
  1657. });
  1658. }
  1659. /**
  1660. * Probes a transport.
  1661. *
  1662. * @param {String} transport name
  1663. * @api private
  1664. */
  1665. }, {
  1666. key: "probe",
  1667. value: function probe(name) {
  1668. var _this4 = this;
  1669. var transport = this.createTransport(name);
  1670. var failed = false;
  1671. Socket.priorWebsocketSuccess = false;
  1672. var onTransportOpen = function onTransportOpen() {
  1673. if (failed) return;
  1674. transport.send([{
  1675. type: "ping",
  1676. data: "probe"
  1677. }]);
  1678. transport.once("packet", function (msg) {
  1679. if (failed) return;
  1680. if ("pong" === msg.type && "probe" === msg.data) {
  1681. _this4.upgrading = true;
  1682. _this4.emitReserved("upgrading", transport);
  1683. if (!transport) return;
  1684. Socket.priorWebsocketSuccess = "websocket" === transport.name;
  1685. _this4.transport.pause(function () {
  1686. if (failed) return;
  1687. if ("closed" === _this4.readyState) return;
  1688. cleanup();
  1689. _this4.setTransport(transport);
  1690. transport.send([{
  1691. type: "upgrade"
  1692. }]);
  1693. _this4.emitReserved("upgrade", transport);
  1694. transport = null;
  1695. _this4.upgrading = false;
  1696. _this4.flush();
  1697. });
  1698. } else {
  1699. var err = new Error("probe error"); // @ts-ignore
  1700. err.transport = transport.name;
  1701. _this4.emitReserved("upgradeError", err);
  1702. }
  1703. });
  1704. };
  1705. function freezeTransport() {
  1706. if (failed) return; // Any callback called by transport should be ignored since now
  1707. failed = true;
  1708. cleanup();
  1709. transport.close();
  1710. transport = null;
  1711. } // Handle any error that happens while probing
  1712. var onerror = function onerror(err) {
  1713. var error = new Error("probe error: " + err); // @ts-ignore
  1714. error.transport = transport.name;
  1715. freezeTransport();
  1716. _this4.emitReserved("upgradeError", error);
  1717. };
  1718. function onTransportClose() {
  1719. onerror("transport closed");
  1720. } // When the socket is closed while we're probing
  1721. function onclose() {
  1722. onerror("socket closed");
  1723. } // When the socket is upgraded while we're probing
  1724. function onupgrade(to) {
  1725. if (transport && to.name !== transport.name) {
  1726. freezeTransport();
  1727. }
  1728. } // Remove all listeners on the transport and on self
  1729. var cleanup = function cleanup() {
  1730. transport.removeListener("open", onTransportOpen);
  1731. transport.removeListener("error", onerror);
  1732. transport.removeListener("close", onTransportClose);
  1733. _this4.off("close", onclose);
  1734. _this4.off("upgrading", onupgrade);
  1735. };
  1736. transport.once("open", onTransportOpen);
  1737. transport.once("error", onerror);
  1738. transport.once("close", onTransportClose);
  1739. this.once("close", onclose);
  1740. this.once("upgrading", onupgrade);
  1741. transport.open();
  1742. }
  1743. /**
  1744. * Called when connection is deemed open.
  1745. *
  1746. * @api private
  1747. */
  1748. }, {
  1749. key: "onOpen",
  1750. value: function onOpen() {
  1751. this.readyState = "open";
  1752. Socket.priorWebsocketSuccess = "websocket" === this.transport.name;
  1753. this.emitReserved("open");
  1754. this.flush(); // we check for `readyState` in case an `open`
  1755. // listener already closed the socket
  1756. if ("open" === this.readyState && this.opts.upgrade && this.transport.pause) {
  1757. var i = 0;
  1758. var l = this.upgrades.length;
  1759. for (; i < l; i++) {
  1760. this.probe(this.upgrades[i]);
  1761. }
  1762. }
  1763. }
  1764. /**
  1765. * Handles a packet.
  1766. *
  1767. * @api private
  1768. */
  1769. }, {
  1770. key: "onPacket",
  1771. value: function onPacket(packet) {
  1772. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  1773. this.emitReserved("packet", packet); // Socket is live - any packet counts
  1774. this.emitReserved("heartbeat");
  1775. switch (packet.type) {
  1776. case "open":
  1777. this.onHandshake(JSON.parse(packet.data));
  1778. break;
  1779. case "ping":
  1780. this.resetPingTimeout();
  1781. this.sendPacket("pong");
  1782. this.emitReserved("ping");
  1783. this.emitReserved("pong");
  1784. break;
  1785. case "error":
  1786. var err = new Error("server error"); // @ts-ignore
  1787. err.code = packet.data;
  1788. this.onError(err);
  1789. break;
  1790. case "message":
  1791. this.emitReserved("data", packet.data);
  1792. this.emitReserved("message", packet.data);
  1793. break;
  1794. }
  1795. }
  1796. }
  1797. /**
  1798. * Called upon handshake completion.
  1799. *
  1800. * @param {Object} data - handshake obj
  1801. * @api private
  1802. */
  1803. }, {
  1804. key: "onHandshake",
  1805. value: function onHandshake(data) {
  1806. this.emitReserved("handshake", data);
  1807. this.id = data.sid;
  1808. this.transport.query.sid = data.sid;
  1809. this.upgrades = this.filterUpgrades(data.upgrades);
  1810. this.pingInterval = data.pingInterval;
  1811. this.pingTimeout = data.pingTimeout;
  1812. this.maxPayload = data.maxPayload;
  1813. this.onOpen(); // In case open handler closes socket
  1814. if ("closed" === this.readyState) return;
  1815. this.resetPingTimeout();
  1816. }
  1817. /**
  1818. * Sets and resets ping timeout timer based on server pings.
  1819. *
  1820. * @api private
  1821. */
  1822. }, {
  1823. key: "resetPingTimeout",
  1824. value: function resetPingTimeout() {
  1825. var _this5 = this;
  1826. this.clearTimeoutFn(this.pingTimeoutTimer);
  1827. this.pingTimeoutTimer = this.setTimeoutFn(function () {
  1828. _this5.onClose("ping timeout");
  1829. }, this.pingInterval + this.pingTimeout);
  1830. if (this.opts.autoUnref) {
  1831. this.pingTimeoutTimer.unref();
  1832. }
  1833. }
  1834. /**
  1835. * Called on `drain` event
  1836. *
  1837. * @api private
  1838. */
  1839. }, {
  1840. key: "onDrain",
  1841. value: function onDrain() {
  1842. this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important
  1843. // for example, when upgrading, upgrade packet is sent over,
  1844. // and a nonzero prevBufferLen could cause problems on `drain`
  1845. this.prevBufferLen = 0;
  1846. if (0 === this.writeBuffer.length) {
  1847. this.emitReserved("drain");
  1848. } else {
  1849. this.flush();
  1850. }
  1851. }
  1852. /**
  1853. * Flush write buffers.
  1854. *
  1855. * @api private
  1856. */
  1857. }, {
  1858. key: "flush",
  1859. value: function flush() {
  1860. if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
  1861. var packets = this.getWritablePackets();
  1862. this.transport.send(packets); // keep track of current length of writeBuffer
  1863. // splice writeBuffer and callbackBuffer on `drain`
  1864. this.prevBufferLen = packets.length;
  1865. this.emitReserved("flush");
  1866. }
  1867. }
  1868. /**
  1869. * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
  1870. * long-polling)
  1871. *
  1872. * @private
  1873. */
  1874. }, {
  1875. key: "getWritablePackets",
  1876. value: function getWritablePackets() {
  1877. var shouldCheckPayloadSize = this.maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
  1878. if (!shouldCheckPayloadSize) {
  1879. return this.writeBuffer;
  1880. }
  1881. var payloadSize = 1; // first packet type
  1882. for (var i = 0; i < this.writeBuffer.length; i++) {
  1883. var data = this.writeBuffer[i].data;
  1884. if (data) {
  1885. payloadSize += byteLength(data);
  1886. }
  1887. if (i > 0 && payloadSize > this.maxPayload) {
  1888. return this.writeBuffer.slice(0, i);
  1889. }
  1890. payloadSize += 2; // separator + packet type
  1891. }
  1892. return this.writeBuffer;
  1893. }
  1894. /**
  1895. * Sends a message.
  1896. *
  1897. * @param {String} message.
  1898. * @param {Function} callback function.
  1899. * @param {Object} options.
  1900. * @return {Socket} for chaining.
  1901. * @api public
  1902. */
  1903. }, {
  1904. key: "write",
  1905. value: function write(msg, options, fn) {
  1906. this.sendPacket("message", msg, options, fn);
  1907. return this;
  1908. }
  1909. }, {
  1910. key: "send",
  1911. value: function send(msg, options, fn) {
  1912. this.sendPacket("message", msg, options, fn);
  1913. return this;
  1914. }
  1915. /**
  1916. * Sends a packet.
  1917. *
  1918. * @param {String} packet type.
  1919. * @param {String} data.
  1920. * @param {Object} options.
  1921. * @param {Function} callback function.
  1922. * @api private
  1923. */
  1924. }, {
  1925. key: "sendPacket",
  1926. value: function sendPacket(type, data, options, fn) {
  1927. if ("function" === typeof data) {
  1928. fn = data;
  1929. data = undefined;
  1930. }
  1931. if ("function" === typeof options) {
  1932. fn = options;
  1933. options = null;
  1934. }
  1935. if ("closing" === this.readyState || "closed" === this.readyState) {
  1936. return;
  1937. }
  1938. options = options || {};
  1939. options.compress = false !== options.compress;
  1940. var packet = {
  1941. type: type,
  1942. data: data,
  1943. options: options
  1944. };
  1945. this.emitReserved("packetCreate", packet);
  1946. this.writeBuffer.push(packet);
  1947. if (fn) this.once("flush", fn);
  1948. this.flush();
  1949. }
  1950. /**
  1951. * Closes the connection.
  1952. *
  1953. * @api public
  1954. */
  1955. }, {
  1956. key: "close",
  1957. value: function close() {
  1958. var _this6 = this;
  1959. var close = function close() {
  1960. _this6.onClose("forced close");
  1961. _this6.transport.close();
  1962. };
  1963. var cleanupAndClose = function cleanupAndClose() {
  1964. _this6.off("upgrade", cleanupAndClose);
  1965. _this6.off("upgradeError", cleanupAndClose);
  1966. close();
  1967. };
  1968. var waitForUpgrade = function waitForUpgrade() {
  1969. // wait for upgrade to finish since we can't send packets while pausing a transport
  1970. _this6.once("upgrade", cleanupAndClose);
  1971. _this6.once("upgradeError", cleanupAndClose);
  1972. };
  1973. if ("opening" === this.readyState || "open" === this.readyState) {
  1974. this.readyState = "closing";
  1975. if (this.writeBuffer.length) {
  1976. this.once("drain", function () {
  1977. if (_this6.upgrading) {
  1978. waitForUpgrade();
  1979. } else {
  1980. close();
  1981. }
  1982. });
  1983. } else if (this.upgrading) {
  1984. waitForUpgrade();
  1985. } else {
  1986. close();
  1987. }
  1988. }
  1989. return this;
  1990. }
  1991. /**
  1992. * Called upon transport error
  1993. *
  1994. * @api private
  1995. */
  1996. }, {
  1997. key: "onError",
  1998. value: function onError(err) {
  1999. Socket.priorWebsocketSuccess = false;
  2000. this.emitReserved("error", err);
  2001. this.onClose("transport error", err);
  2002. }
  2003. /**
  2004. * Called upon transport close.
  2005. *
  2006. * @api private
  2007. */
  2008. }, {
  2009. key: "onClose",
  2010. value: function onClose(reason, description) {
  2011. if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
  2012. // clear timers
  2013. this.clearTimeoutFn(this.pingTimeoutTimer); // stop event from firing again for transport
  2014. this.transport.removeAllListeners("close"); // ensure transport won't stay open
  2015. this.transport.close(); // ignore further transport communication
  2016. this.transport.removeAllListeners();
  2017. if (typeof removeEventListener === "function") {
  2018. removeEventListener("beforeunload", this.beforeunloadEventListener, false);
  2019. removeEventListener("offline", this.offlineEventListener, false);
  2020. } // set ready state
  2021. this.readyState = "closed"; // clear session id
  2022. this.id = null; // emit close event
  2023. this.emitReserved("close", reason, description); // clean buffers after, so users can still
  2024. // grab the buffers on `close` event
  2025. this.writeBuffer = [];
  2026. this.prevBufferLen = 0;
  2027. }
  2028. }
  2029. /**
  2030. * Filters upgrades, returning only those matching client transports.
  2031. *
  2032. * @param {Array} server upgrades
  2033. * @api private
  2034. *
  2035. */
  2036. }, {
  2037. key: "filterUpgrades",
  2038. value: function filterUpgrades(upgrades) {
  2039. var filteredUpgrades = [];
  2040. var i = 0;
  2041. var j = upgrades.length;
  2042. for (; i < j; i++) {
  2043. if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]);
  2044. }
  2045. return filteredUpgrades;
  2046. }
  2047. }]);
  2048. return Socket;
  2049. }(Emitter);
  2050. Socket$1.protocol = protocol$1;
  2051. Socket$1.protocol;
  2052. /**
  2053. * URL parser.
  2054. *
  2055. * @param uri - url
  2056. * @param path - the request path of the connection
  2057. * @param loc - An object meant to mimic window.location.
  2058. * Defaults to window.location.
  2059. * @public
  2060. */
  2061. function url(uri) {
  2062. var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  2063. var loc = arguments.length > 2 ? arguments[2] : undefined;
  2064. var obj = uri; // default to window.location
  2065. loc = loc || typeof location !== "undefined" && location;
  2066. if (null == uri) uri = loc.protocol + "//" + loc.host; // relative path support
  2067. if (typeof uri === "string") {
  2068. if ("/" === uri.charAt(0)) {
  2069. if ("/" === uri.charAt(1)) {
  2070. uri = loc.protocol + uri;
  2071. } else {
  2072. uri = loc.host + uri;
  2073. }
  2074. }
  2075. if (!/^(https?|wss?):\/\//.test(uri)) {
  2076. if ("undefined" !== typeof loc) {
  2077. uri = loc.protocol + "//" + uri;
  2078. } else {
  2079. uri = "https://" + uri;
  2080. }
  2081. } // parse
  2082. obj = parse(uri);
  2083. } // make sure we treat `localhost:80` and `localhost` equally
  2084. if (!obj.port) {
  2085. if (/^(http|ws)$/.test(obj.protocol)) {
  2086. obj.port = "80";
  2087. } else if (/^(http|ws)s$/.test(obj.protocol)) {
  2088. obj.port = "443";
  2089. }
  2090. }
  2091. obj.path = obj.path || "/";
  2092. var ipv6 = obj.host.indexOf(":") !== -1;
  2093. var host = ipv6 ? "[" + obj.host + "]" : obj.host; // define unique id
  2094. obj.id = obj.protocol + "://" + host + ":" + obj.port + path; // define href
  2095. obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
  2096. return obj;
  2097. }
  2098. var withNativeArrayBuffer = typeof ArrayBuffer === "function";
  2099. var isView = function isView(obj) {
  2100. return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
  2101. };
  2102. var toString = Object.prototype.toString;
  2103. var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
  2104. var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
  2105. /**
  2106. * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File.
  2107. *
  2108. * @private
  2109. */
  2110. function isBinary(obj) {
  2111. return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File;
  2112. }
  2113. function hasBinary(obj, toJSON) {
  2114. if (!obj || _typeof(obj) !== "object") {
  2115. return false;
  2116. }
  2117. if (Array.isArray(obj)) {
  2118. for (var i = 0, l = obj.length; i < l; i++) {
  2119. if (hasBinary(obj[i])) {
  2120. return true;
  2121. }
  2122. }
  2123. return false;
  2124. }
  2125. if (isBinary(obj)) {
  2126. return true;
  2127. }
  2128. if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
  2129. return hasBinary(obj.toJSON(), true);
  2130. }
  2131. for (var key in obj) {
  2132. if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
  2133. return true;
  2134. }
  2135. }
  2136. return false;
  2137. }
  2138. /**
  2139. * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder.
  2140. *
  2141. * @param {Object} packet - socket.io event packet
  2142. * @return {Object} with deconstructed packet and list of buffers
  2143. * @public
  2144. */
  2145. function deconstructPacket(packet) {
  2146. var buffers = [];
  2147. var packetData = packet.data;
  2148. var pack = packet;
  2149. pack.data = _deconstructPacket(packetData, buffers);
  2150. pack.attachments = buffers.length; // number of binary 'attachments'
  2151. return {
  2152. packet: pack,
  2153. buffers: buffers
  2154. };
  2155. }
  2156. function _deconstructPacket(data, buffers) {
  2157. if (!data) return data;
  2158. if (isBinary(data)) {
  2159. var placeholder = {
  2160. _placeholder: true,
  2161. num: buffers.length
  2162. };
  2163. buffers.push(data);
  2164. return placeholder;
  2165. } else if (Array.isArray(data)) {
  2166. var newData = new Array(data.length);
  2167. for (var i = 0; i < data.length; i++) {
  2168. newData[i] = _deconstructPacket(data[i], buffers);
  2169. }
  2170. return newData;
  2171. } else if (_typeof(data) === "object" && !(data instanceof Date)) {
  2172. var _newData = {};
  2173. for (var key in data) {
  2174. if (Object.prototype.hasOwnProperty.call(data, key)) {
  2175. _newData[key] = _deconstructPacket(data[key], buffers);
  2176. }
  2177. }
  2178. return _newData;
  2179. }
  2180. return data;
  2181. }
  2182. /**
  2183. * Reconstructs a binary packet from its placeholder packet and buffers
  2184. *
  2185. * @param {Object} packet - event packet with placeholders
  2186. * @param {Array} buffers - binary buffers to put in placeholder positions
  2187. * @return {Object} reconstructed packet
  2188. * @public
  2189. */
  2190. function reconstructPacket(packet, buffers) {
  2191. packet.data = _reconstructPacket(packet.data, buffers);
  2192. packet.attachments = undefined; // no longer useful
  2193. return packet;
  2194. }
  2195. function _reconstructPacket(data, buffers) {
  2196. if (!data) return data;
  2197. if (data && data._placeholder) {
  2198. return buffers[data.num]; // appropriate buffer (should be natural order anyway)
  2199. } else if (Array.isArray(data)) {
  2200. for (var i = 0; i < data.length; i++) {
  2201. data[i] = _reconstructPacket(data[i], buffers);
  2202. }
  2203. } else if (_typeof(data) === "object") {
  2204. for (var key in data) {
  2205. if (Object.prototype.hasOwnProperty.call(data, key)) {
  2206. data[key] = _reconstructPacket(data[key], buffers);
  2207. }
  2208. }
  2209. }
  2210. return data;
  2211. }
  2212. /**
  2213. * Protocol version.
  2214. *
  2215. * @public
  2216. */
  2217. var protocol = 5;
  2218. var PacketType;
  2219. (function (PacketType) {
  2220. PacketType[PacketType["CONNECT"] = 0] = "CONNECT";
  2221. PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT";
  2222. PacketType[PacketType["EVENT"] = 2] = "EVENT";
  2223. PacketType[PacketType["ACK"] = 3] = "ACK";
  2224. PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
  2225. PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT";
  2226. PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK";
  2227. })(PacketType || (PacketType = {}));
  2228. /**
  2229. * A socket.io Encoder instance
  2230. */
  2231. var Encoder = /*#__PURE__*/function () {
  2232. /**
  2233. * Encoder constructor
  2234. *
  2235. * @param {function} replacer - custom replacer to pass down to JSON.parse
  2236. */
  2237. function Encoder(replacer) {
  2238. _classCallCheck(this, Encoder);
  2239. this.replacer = replacer;
  2240. }
  2241. /**
  2242. * Encode a packet as a single string if non-binary, or as a
  2243. * buffer sequence, depending on packet type.
  2244. *
  2245. * @param {Object} obj - packet object
  2246. */
  2247. _createClass(Encoder, [{
  2248. key: "encode",
  2249. value: function encode(obj) {
  2250. if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
  2251. if (hasBinary(obj)) {
  2252. obj.type = obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK;
  2253. return this.encodeAsBinary(obj);
  2254. }
  2255. }
  2256. return [this.encodeAsString(obj)];
  2257. }
  2258. /**
  2259. * Encode packet as string.
  2260. */
  2261. }, {
  2262. key: "encodeAsString",
  2263. value: function encodeAsString(obj) {
  2264. // first is type
  2265. var str = "" + obj.type; // attachments if we have them
  2266. if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
  2267. str += obj.attachments + "-";
  2268. } // if we have a namespace other than `/`
  2269. // we append it followed by a comma `,`
  2270. if (obj.nsp && "/" !== obj.nsp) {
  2271. str += obj.nsp + ",";
  2272. } // immediately followed by the id
  2273. if (null != obj.id) {
  2274. str += obj.id;
  2275. } // json data
  2276. if (null != obj.data) {
  2277. str += JSON.stringify(obj.data, this.replacer);
  2278. }
  2279. return str;
  2280. }
  2281. /**
  2282. * Encode packet as 'buffer sequence' by removing blobs, and
  2283. * deconstructing packet into object with placeholders and
  2284. * a list of buffers.
  2285. */
  2286. }, {
  2287. key: "encodeAsBinary",
  2288. value: function encodeAsBinary(obj) {
  2289. var deconstruction = deconstructPacket(obj);
  2290. var pack = this.encodeAsString(deconstruction.packet);
  2291. var buffers = deconstruction.buffers;
  2292. buffers.unshift(pack); // add packet info to beginning of data list
  2293. return buffers; // write all the buffers
  2294. }
  2295. }]);
  2296. return Encoder;
  2297. }();
  2298. /**
  2299. * A socket.io Decoder instance
  2300. *
  2301. * @return {Object} decoder
  2302. */
  2303. var Decoder = /*#__PURE__*/function (_Emitter) {
  2304. _inherits(Decoder, _Emitter);
  2305. var _super = _createSuper(Decoder);
  2306. /**
  2307. * Decoder constructor
  2308. *
  2309. * @param {function} reviver - custom reviver to pass down to JSON.stringify
  2310. */
  2311. function Decoder(reviver) {
  2312. var _this;
  2313. _classCallCheck(this, Decoder);
  2314. _this = _super.call(this);
  2315. _this.reviver = reviver;
  2316. return _this;
  2317. }
  2318. /**
  2319. * Decodes an encoded packet string into packet JSON.
  2320. *
  2321. * @param {String} obj - encoded packet
  2322. */
  2323. _createClass(Decoder, [{
  2324. key: "add",
  2325. value: function add(obj) {
  2326. var packet;
  2327. if (typeof obj === "string") {
  2328. packet = this.decodeString(obj);
  2329. if (packet.type === PacketType.BINARY_EVENT || packet.type === PacketType.BINARY_ACK) {
  2330. // binary packet's json
  2331. this.reconstructor = new BinaryReconstructor(packet); // no attachments, labeled binary but no binary data to follow
  2332. if (packet.attachments === 0) {
  2333. _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
  2334. }
  2335. } else {
  2336. // non-binary full packet
  2337. _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
  2338. }
  2339. } else if (isBinary(obj) || obj.base64) {
  2340. // raw binary data
  2341. if (!this.reconstructor) {
  2342. throw new Error("got binary data when not reconstructing a packet");
  2343. } else {
  2344. packet = this.reconstructor.takeBinaryData(obj);
  2345. if (packet) {
  2346. // received final buffer
  2347. this.reconstructor = null;
  2348. _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet);
  2349. }
  2350. }
  2351. } else {
  2352. throw new Error("Unknown type: " + obj);
  2353. }
  2354. }
  2355. /**
  2356. * Decode a packet String (JSON data)
  2357. *
  2358. * @param {String} str
  2359. * @return {Object} packet
  2360. */
  2361. }, {
  2362. key: "decodeString",
  2363. value: function decodeString(str) {
  2364. var i = 0; // look up type
  2365. var p = {
  2366. type: Number(str.charAt(0))
  2367. };
  2368. if (PacketType[p.type] === undefined) {
  2369. throw new Error("unknown packet type " + p.type);
  2370. } // look up attachments if type binary
  2371. if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
  2372. var start = i + 1;
  2373. while (str.charAt(++i) !== "-" && i != str.length) {}
  2374. var buf = str.substring(start, i);
  2375. if (buf != Number(buf) || str.charAt(i) !== "-") {
  2376. throw new Error("Illegal attachments");
  2377. }
  2378. p.attachments = Number(buf);
  2379. } // look up namespace (if any)
  2380. if ("/" === str.charAt(i + 1)) {
  2381. var _start = i + 1;
  2382. while (++i) {
  2383. var c = str.charAt(i);
  2384. if ("," === c) break;
  2385. if (i === str.length) break;
  2386. }
  2387. p.nsp = str.substring(_start, i);
  2388. } else {
  2389. p.nsp = "/";
  2390. } // look up id
  2391. var next = str.charAt(i + 1);
  2392. if ("" !== next && Number(next) == next) {
  2393. var _start2 = i + 1;
  2394. while (++i) {
  2395. var _c = str.charAt(i);
  2396. if (null == _c || Number(_c) != _c) {
  2397. --i;
  2398. break;
  2399. }
  2400. if (i === str.length) break;
  2401. }
  2402. p.id = Number(str.substring(_start2, i + 1));
  2403. } // look up json data
  2404. if (str.charAt(++i)) {
  2405. var payload = this.tryParse(str.substr(i));
  2406. if (Decoder.isPayloadValid(p.type, payload)) {
  2407. p.data = payload;
  2408. } else {
  2409. throw new Error("invalid payload");
  2410. }
  2411. }
  2412. return p;
  2413. }
  2414. }, {
  2415. key: "tryParse",
  2416. value: function tryParse(str) {
  2417. try {
  2418. return JSON.parse(str, this.reviver);
  2419. } catch (e) {
  2420. return false;
  2421. }
  2422. }
  2423. }, {
  2424. key: "destroy",
  2425. value:
  2426. /**
  2427. * Deallocates a parser's resources
  2428. */
  2429. function destroy() {
  2430. if (this.reconstructor) {
  2431. this.reconstructor.finishedReconstruction();
  2432. }
  2433. }
  2434. }], [{
  2435. key: "isPayloadValid",
  2436. value: function isPayloadValid(type, payload) {
  2437. switch (type) {
  2438. case PacketType.CONNECT:
  2439. return _typeof(payload) === "object";
  2440. case PacketType.DISCONNECT:
  2441. return payload === undefined;
  2442. case PacketType.CONNECT_ERROR:
  2443. return typeof payload === "string" || _typeof(payload) === "object";
  2444. case PacketType.EVENT:
  2445. case PacketType.BINARY_EVENT:
  2446. return Array.isArray(payload) && payload.length > 0;
  2447. case PacketType.ACK:
  2448. case PacketType.BINARY_ACK:
  2449. return Array.isArray(payload);
  2450. }
  2451. }
  2452. }]);
  2453. return Decoder;
  2454. }(Emitter);
  2455. /**
  2456. * A manager of a binary event's 'buffer sequence'. Should
  2457. * be constructed whenever a packet of type BINARY_EVENT is
  2458. * decoded.
  2459. *
  2460. * @param {Object} packet
  2461. * @return {BinaryReconstructor} initialized reconstructor
  2462. */
  2463. var BinaryReconstructor = /*#__PURE__*/function () {
  2464. function BinaryReconstructor(packet) {
  2465. _classCallCheck(this, BinaryReconstructor);
  2466. this.packet = packet;
  2467. this.buffers = [];
  2468. this.reconPack = packet;
  2469. }
  2470. /**
  2471. * Method to be called when binary data received from connection
  2472. * after a BINARY_EVENT packet.
  2473. *
  2474. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  2475. * @return {null | Object} returns null if more binary data is expected or
  2476. * a reconstructed packet object if all buffers have been received.
  2477. */
  2478. _createClass(BinaryReconstructor, [{
  2479. key: "takeBinaryData",
  2480. value: function takeBinaryData(binData) {
  2481. this.buffers.push(binData);
  2482. if (this.buffers.length === this.reconPack.attachments) {
  2483. // done with buffer list
  2484. var packet = reconstructPacket(this.reconPack, this.buffers);
  2485. this.finishedReconstruction();
  2486. return packet;
  2487. }
  2488. return null;
  2489. }
  2490. /**
  2491. * Cleans up binary packet reconstruction variables.
  2492. */
  2493. }, {
  2494. key: "finishedReconstruction",
  2495. value: function finishedReconstruction() {
  2496. this.reconPack = null;
  2497. this.buffers = [];
  2498. }
  2499. }]);
  2500. return BinaryReconstructor;
  2501. }();
  2502. var parser = /*#__PURE__*/Object.freeze({
  2503. __proto__: null,
  2504. protocol: protocol,
  2505. get PacketType () { return PacketType; },
  2506. Encoder: Encoder,
  2507. Decoder: Decoder
  2508. });
  2509. function on(obj, ev, fn) {
  2510. obj.on(ev, fn);
  2511. return function subDestroy() {
  2512. obj.off(ev, fn);
  2513. };
  2514. }
  2515. /**
  2516. * Internal events.
  2517. * These events can't be emitted by the user.
  2518. */
  2519. var RESERVED_EVENTS = Object.freeze({
  2520. connect: 1,
  2521. connect_error: 1,
  2522. disconnect: 1,
  2523. disconnecting: 1,
  2524. // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
  2525. newListener: 1,
  2526. removeListener: 1
  2527. });
  2528. /**
  2529. * A Socket is the fundamental class for interacting with the server.
  2530. *
  2531. * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate.
  2532. *
  2533. * @example
  2534. * const socket = io();
  2535. *
  2536. * socket.on("connect", () => {
  2537. * console.log("connected");
  2538. * });
  2539. *
  2540. * // send an event to the server
  2541. * socket.emit("foo", "bar");
  2542. *
  2543. * socket.on("foobar", () => {
  2544. * // an event was received from the server
  2545. * });
  2546. *
  2547. * // upon disconnection
  2548. * socket.on("disconnect", (reason) => {
  2549. * console.log(`disconnected due to ${reason}`);
  2550. * });
  2551. */
  2552. var Socket = /*#__PURE__*/function (_Emitter) {
  2553. _inherits(Socket, _Emitter);
  2554. var _super = _createSuper(Socket);
  2555. /**
  2556. * `Socket` constructor.
  2557. */
  2558. function Socket(io, nsp, opts) {
  2559. var _this;
  2560. _classCallCheck(this, Socket);
  2561. _this = _super.call(this);
  2562. /**
  2563. * Whether the socket is currently connected to the server.
  2564. *
  2565. * @example
  2566. * const socket = io();
  2567. *
  2568. * socket.on("connect", () => {
  2569. * console.log(socket.connected); // true
  2570. * });
  2571. *
  2572. * socket.on("disconnect", () => {
  2573. * console.log(socket.connected); // false
  2574. * });
  2575. */
  2576. _this.connected = false;
  2577. /**
  2578. * Buffer for packets received before the CONNECT packet
  2579. */
  2580. _this.receiveBuffer = [];
  2581. /**
  2582. * Buffer for packets that will be sent once the socket is connected
  2583. */
  2584. _this.sendBuffer = [];
  2585. _this.ids = 0;
  2586. _this.acks = {};
  2587. _this.flags = {};
  2588. _this.io = io;
  2589. _this.nsp = nsp;
  2590. if (opts && opts.auth) {
  2591. _this.auth = opts.auth;
  2592. }
  2593. if (_this.io._autoConnect) _this.open();
  2594. return _this;
  2595. }
  2596. /**
  2597. * Whether the socket is currently disconnected
  2598. *
  2599. * @example
  2600. * const socket = io();
  2601. *
  2602. * socket.on("connect", () => {
  2603. * console.log(socket.disconnected); // false
  2604. * });
  2605. *
  2606. * socket.on("disconnect", () => {
  2607. * console.log(socket.disconnected); // true
  2608. * });
  2609. */
  2610. _createClass(Socket, [{
  2611. key: "disconnected",
  2612. get: function get() {
  2613. return !this.connected;
  2614. }
  2615. /**
  2616. * Subscribe to open, close and packet events
  2617. *
  2618. * @private
  2619. */
  2620. }, {
  2621. key: "subEvents",
  2622. value: function subEvents() {
  2623. if (this.subs) return;
  2624. var io = this.io;
  2625. this.subs = [on(io, "open", this.onopen.bind(this)), on(io, "packet", this.onpacket.bind(this)), on(io, "error", this.onerror.bind(this)), on(io, "close", this.onclose.bind(this))];
  2626. }
  2627. /**
  2628. * Whether the Socket will try to reconnect when its Manager connects or reconnects.
  2629. *
  2630. * @example
  2631. * const socket = io();
  2632. *
  2633. * console.log(socket.active); // true
  2634. *
  2635. * socket.on("disconnect", (reason) => {
  2636. * if (reason === "io server disconnect") {
  2637. * // the disconnection was initiated by the server, you need to manually reconnect
  2638. * console.log(socket.active); // false
  2639. * }
  2640. * // else the socket will automatically try to reconnect
  2641. * console.log(socket.active); // true
  2642. * });
  2643. */
  2644. }, {
  2645. key: "active",
  2646. get: function get() {
  2647. return !!this.subs;
  2648. }
  2649. /**
  2650. * "Opens" the socket.
  2651. *
  2652. * @example
  2653. * const socket = io({
  2654. * autoConnect: false
  2655. * });
  2656. *
  2657. * socket.connect();
  2658. */
  2659. }, {
  2660. key: "connect",
  2661. value: function connect() {
  2662. if (this.connected) return this;
  2663. this.subEvents();
  2664. if (!this.io["_reconnecting"]) this.io.open(); // ensure open
  2665. if ("open" === this.io._readyState) this.onopen();
  2666. return this;
  2667. }
  2668. /**
  2669. * Alias for {@link connect()}.
  2670. */
  2671. }, {
  2672. key: "open",
  2673. value: function open() {
  2674. return this.connect();
  2675. }
  2676. /**
  2677. * Sends a `message` event.
  2678. *
  2679. * This method mimics the WebSocket.send() method.
  2680. *
  2681. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
  2682. *
  2683. * @example
  2684. * socket.send("hello");
  2685. *
  2686. * // this is equivalent to
  2687. * socket.emit("message", "hello");
  2688. *
  2689. * @return self
  2690. */
  2691. }, {
  2692. key: "send",
  2693. value: function send() {
  2694. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2695. args[_key] = arguments[_key];
  2696. }
  2697. args.unshift("message");
  2698. this.emit.apply(this, args);
  2699. return this;
  2700. }
  2701. /**
  2702. * Override `emit`.
  2703. * If the event is in `events`, it's emitted normally.
  2704. *
  2705. * @example
  2706. * socket.emit("hello", "world");
  2707. *
  2708. * // all serializable datastructures are supported (no need to call JSON.stringify)
  2709. * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
  2710. *
  2711. * // with an acknowledgement from the server
  2712. * socket.emit("hello", "world", (val) => {
  2713. * // ...
  2714. * });
  2715. *
  2716. * @return self
  2717. */
  2718. }, {
  2719. key: "emit",
  2720. value: function emit(ev) {
  2721. if (RESERVED_EVENTS.hasOwnProperty(ev)) {
  2722. throw new Error('"' + ev.toString() + '" is a reserved event name');
  2723. }
  2724. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  2725. args[_key2 - 1] = arguments[_key2];
  2726. }
  2727. args.unshift(ev);
  2728. var packet = {
  2729. type: PacketType.EVENT,
  2730. data: args
  2731. };
  2732. packet.options = {};
  2733. packet.options.compress = this.flags.compress !== false; // event ack callback
  2734. if ("function" === typeof args[args.length - 1]) {
  2735. var id = this.ids++;
  2736. var ack = args.pop();
  2737. this._registerAckCallback(id, ack);
  2738. packet.id = id;
  2739. }
  2740. var isTransportWritable = this.io.engine && this.io.engine.transport && this.io.engine.transport.writable;
  2741. var discardPacket = this.flags["volatile"] && (!isTransportWritable || !this.connected);
  2742. if (discardPacket) ; else if (this.connected) {
  2743. this.notifyOutgoingListeners(packet);
  2744. this.packet(packet);
  2745. } else {
  2746. this.sendBuffer.push(packet);
  2747. }
  2748. this.flags = {};
  2749. return this;
  2750. }
  2751. /**
  2752. * @private
  2753. */
  2754. }, {
  2755. key: "_registerAckCallback",
  2756. value: function _registerAckCallback(id, ack) {
  2757. var _this2 = this;
  2758. var timeout = this.flags.timeout;
  2759. if (timeout === undefined) {
  2760. this.acks[id] = ack;
  2761. return;
  2762. } // @ts-ignore
  2763. var timer = this.io.setTimeoutFn(function () {
  2764. delete _this2.acks[id];
  2765. for (var i = 0; i < _this2.sendBuffer.length; i++) {
  2766. if (_this2.sendBuffer[i].id === id) {
  2767. _this2.sendBuffer.splice(i, 1);
  2768. }
  2769. }
  2770. ack.call(_this2, new Error("operation has timed out"));
  2771. }, timeout);
  2772. this.acks[id] = function () {
  2773. // @ts-ignore
  2774. _this2.io.clearTimeoutFn(timer);
  2775. for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  2776. args[_key3] = arguments[_key3];
  2777. }
  2778. ack.apply(_this2, [null].concat(args));
  2779. };
  2780. }
  2781. /**
  2782. * Sends a packet.
  2783. *
  2784. * @param packet
  2785. * @private
  2786. */
  2787. }, {
  2788. key: "packet",
  2789. value: function packet(_packet) {
  2790. _packet.nsp = this.nsp;
  2791. this.io._packet(_packet);
  2792. }
  2793. /**
  2794. * Called upon engine `open`.
  2795. *
  2796. * @private
  2797. */
  2798. }, {
  2799. key: "onopen",
  2800. value: function onopen() {
  2801. var _this3 = this;
  2802. if (typeof this.auth == "function") {
  2803. this.auth(function (data) {
  2804. _this3.packet({
  2805. type: PacketType.CONNECT,
  2806. data: data
  2807. });
  2808. });
  2809. } else {
  2810. this.packet({
  2811. type: PacketType.CONNECT,
  2812. data: this.auth
  2813. });
  2814. }
  2815. }
  2816. /**
  2817. * Called upon engine or manager `error`.
  2818. *
  2819. * @param err
  2820. * @private
  2821. */
  2822. }, {
  2823. key: "onerror",
  2824. value: function onerror(err) {
  2825. if (!this.connected) {
  2826. this.emitReserved("connect_error", err);
  2827. }
  2828. }
  2829. /**
  2830. * Called upon engine `close`.
  2831. *
  2832. * @param reason
  2833. * @param description
  2834. * @private
  2835. */
  2836. }, {
  2837. key: "onclose",
  2838. value: function onclose(reason, description) {
  2839. this.connected = false;
  2840. delete this.id;
  2841. this.emitReserved("disconnect", reason, description);
  2842. }
  2843. /**
  2844. * Called with socket packet.
  2845. *
  2846. * @param packet
  2847. * @private
  2848. */
  2849. }, {
  2850. key: "onpacket",
  2851. value: function onpacket(packet) {
  2852. var sameNamespace = packet.nsp === this.nsp;
  2853. if (!sameNamespace) return;
  2854. switch (packet.type) {
  2855. case PacketType.CONNECT:
  2856. if (packet.data && packet.data.sid) {
  2857. var id = packet.data.sid;
  2858. this.onconnect(id);
  2859. } else {
  2860. this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
  2861. }
  2862. break;
  2863. case PacketType.EVENT:
  2864. case PacketType.BINARY_EVENT:
  2865. this.onevent(packet);
  2866. break;
  2867. case PacketType.ACK:
  2868. case PacketType.BINARY_ACK:
  2869. this.onack(packet);
  2870. break;
  2871. case PacketType.DISCONNECT:
  2872. this.ondisconnect();
  2873. break;
  2874. case PacketType.CONNECT_ERROR:
  2875. this.destroy();
  2876. var err = new Error(packet.data.message); // @ts-ignore
  2877. err.data = packet.data.data;
  2878. this.emitReserved("connect_error", err);
  2879. break;
  2880. }
  2881. }
  2882. /**
  2883. * Called upon a server event.
  2884. *
  2885. * @param packet
  2886. * @private
  2887. */
  2888. }, {
  2889. key: "onevent",
  2890. value: function onevent(packet) {
  2891. var args = packet.data || [];
  2892. if (null != packet.id) {
  2893. args.push(this.ack(packet.id));
  2894. }
  2895. if (this.connected) {
  2896. this.emitEvent(args);
  2897. } else {
  2898. this.receiveBuffer.push(Object.freeze(args));
  2899. }
  2900. }
  2901. }, {
  2902. key: "emitEvent",
  2903. value: function emitEvent(args) {
  2904. if (this._anyListeners && this._anyListeners.length) {
  2905. var listeners = this._anyListeners.slice();
  2906. var _iterator = _createForOfIteratorHelper(listeners),
  2907. _step;
  2908. try {
  2909. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  2910. var listener = _step.value;
  2911. listener.apply(this, args);
  2912. }
  2913. } catch (err) {
  2914. _iterator.e(err);
  2915. } finally {
  2916. _iterator.f();
  2917. }
  2918. }
  2919. _get(_getPrototypeOf(Socket.prototype), "emit", this).apply(this, args);
  2920. }
  2921. /**
  2922. * Produces an ack callback to emit with an event.
  2923. *
  2924. * @private
  2925. */
  2926. }, {
  2927. key: "ack",
  2928. value: function ack(id) {
  2929. var self = this;
  2930. var sent = false;
  2931. return function () {
  2932. // prevent double callbacks
  2933. if (sent) return;
  2934. sent = true;
  2935. for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  2936. args[_key4] = arguments[_key4];
  2937. }
  2938. self.packet({
  2939. type: PacketType.ACK,
  2940. id: id,
  2941. data: args
  2942. });
  2943. };
  2944. }
  2945. /**
  2946. * Called upon a server acknowlegement.
  2947. *
  2948. * @param packet
  2949. * @private
  2950. */
  2951. }, {
  2952. key: "onack",
  2953. value: function onack(packet) {
  2954. var ack = this.acks[packet.id];
  2955. if ("function" === typeof ack) {
  2956. ack.apply(this, packet.data);
  2957. delete this.acks[packet.id];
  2958. }
  2959. }
  2960. /**
  2961. * Called upon server connect.
  2962. *
  2963. * @private
  2964. */
  2965. }, {
  2966. key: "onconnect",
  2967. value: function onconnect(id) {
  2968. this.id = id;
  2969. this.connected = true;
  2970. this.emitBuffered();
  2971. this.emitReserved("connect");
  2972. }
  2973. /**
  2974. * Emit buffered events (received and emitted).
  2975. *
  2976. * @private
  2977. */
  2978. }, {
  2979. key: "emitBuffered",
  2980. value: function emitBuffered() {
  2981. var _this4 = this;
  2982. this.receiveBuffer.forEach(function (args) {
  2983. return _this4.emitEvent(args);
  2984. });
  2985. this.receiveBuffer = [];
  2986. this.sendBuffer.forEach(function (packet) {
  2987. _this4.notifyOutgoingListeners(packet);
  2988. _this4.packet(packet);
  2989. });
  2990. this.sendBuffer = [];
  2991. }
  2992. /**
  2993. * Called upon server disconnect.
  2994. *
  2995. * @private
  2996. */
  2997. }, {
  2998. key: "ondisconnect",
  2999. value: function ondisconnect() {
  3000. this.destroy();
  3001. this.onclose("io server disconnect");
  3002. }
  3003. /**
  3004. * Called upon forced client/server side disconnections,
  3005. * this method ensures the manager stops tracking us and
  3006. * that reconnections don't get triggered for this.
  3007. *
  3008. * @private
  3009. */
  3010. }, {
  3011. key: "destroy",
  3012. value: function destroy() {
  3013. if (this.subs) {
  3014. // clean subscriptions to avoid reconnections
  3015. this.subs.forEach(function (subDestroy) {
  3016. return subDestroy();
  3017. });
  3018. this.subs = undefined;
  3019. }
  3020. this.io["_destroy"](this);
  3021. }
  3022. /**
  3023. * Disconnects the socket manually. In that case, the socket will not try to reconnect.
  3024. *
  3025. * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
  3026. *
  3027. * @example
  3028. * const socket = io();
  3029. *
  3030. * socket.on("disconnect", (reason) => {
  3031. * // console.log(reason); prints "io client disconnect"
  3032. * });
  3033. *
  3034. * socket.disconnect();
  3035. *
  3036. * @return self
  3037. */
  3038. }, {
  3039. key: "disconnect",
  3040. value: function disconnect() {
  3041. if (this.connected) {
  3042. this.packet({
  3043. type: PacketType.DISCONNECT
  3044. });
  3045. } // remove socket from pool
  3046. this.destroy();
  3047. if (this.connected) {
  3048. // fire events
  3049. this.onclose("io client disconnect");
  3050. }
  3051. return this;
  3052. }
  3053. /**
  3054. * Alias for {@link disconnect()}.
  3055. *
  3056. * @return self
  3057. */
  3058. }, {
  3059. key: "close",
  3060. value: function close() {
  3061. return this.disconnect();
  3062. }
  3063. /**
  3064. * Sets the compress flag.
  3065. *
  3066. * @example
  3067. * socket.compress(false).emit("hello");
  3068. *
  3069. * @param compress - if `true`, compresses the sending data
  3070. * @return self
  3071. */
  3072. }, {
  3073. key: "compress",
  3074. value: function compress(_compress) {
  3075. this.flags.compress = _compress;
  3076. return this;
  3077. }
  3078. /**
  3079. * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
  3080. * ready to send messages.
  3081. *
  3082. * @example
  3083. * socket.volatile.emit("hello"); // the server may or may not receive it
  3084. *
  3085. * @returns self
  3086. */
  3087. }, {
  3088. key: "volatile",
  3089. get: function get() {
  3090. this.flags["volatile"] = true;
  3091. return this;
  3092. }
  3093. /**
  3094. * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
  3095. * given number of milliseconds have elapsed without an acknowledgement from the server:
  3096. *
  3097. * @example
  3098. * socket.timeout(5000).emit("my-event", (err) => {
  3099. * if (err) {
  3100. * // the server did not acknowledge the event in the given delay
  3101. * }
  3102. * });
  3103. *
  3104. * @returns self
  3105. */
  3106. }, {
  3107. key: "timeout",
  3108. value: function timeout(_timeout) {
  3109. this.flags.timeout = _timeout;
  3110. return this;
  3111. }
  3112. /**
  3113. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3114. * callback.
  3115. *
  3116. * @example
  3117. * socket.onAny((event, ...args) => {
  3118. * console.log(`got ${event}`);
  3119. * });
  3120. *
  3121. * @param listener
  3122. */
  3123. }, {
  3124. key: "onAny",
  3125. value: function onAny(listener) {
  3126. this._anyListeners = this._anyListeners || [];
  3127. this._anyListeners.push(listener);
  3128. return this;
  3129. }
  3130. /**
  3131. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3132. * callback. The listener is added to the beginning of the listeners array.
  3133. *
  3134. * @example
  3135. * socket.prependAny((event, ...args) => {
  3136. * console.log(`got event ${event}`);
  3137. * });
  3138. *
  3139. * @param listener
  3140. */
  3141. }, {
  3142. key: "prependAny",
  3143. value: function prependAny(listener) {
  3144. this._anyListeners = this._anyListeners || [];
  3145. this._anyListeners.unshift(listener);
  3146. return this;
  3147. }
  3148. /**
  3149. * Removes the listener that will be fired when any event is emitted.
  3150. *
  3151. * @example
  3152. * const catchAllListener = (event, ...args) => {
  3153. * console.log(`got event ${event}`);
  3154. * }
  3155. *
  3156. * socket.onAny(catchAllListener);
  3157. *
  3158. * // remove a specific listener
  3159. * socket.offAny(catchAllListener);
  3160. *
  3161. * // or remove all listeners
  3162. * socket.offAny();
  3163. *
  3164. * @param listener
  3165. */
  3166. }, {
  3167. key: "offAny",
  3168. value: function offAny(listener) {
  3169. if (!this._anyListeners) {
  3170. return this;
  3171. }
  3172. if (listener) {
  3173. var listeners = this._anyListeners;
  3174. for (var i = 0; i < listeners.length; i++) {
  3175. if (listener === listeners[i]) {
  3176. listeners.splice(i, 1);
  3177. return this;
  3178. }
  3179. }
  3180. } else {
  3181. this._anyListeners = [];
  3182. }
  3183. return this;
  3184. }
  3185. /**
  3186. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  3187. * e.g. to remove listeners.
  3188. */
  3189. }, {
  3190. key: "listenersAny",
  3191. value: function listenersAny() {
  3192. return this._anyListeners || [];
  3193. }
  3194. /**
  3195. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3196. * callback.
  3197. *
  3198. * Note: acknowledgements sent to the server are not included.
  3199. *
  3200. * @example
  3201. * socket.onAnyOutgoing((event, ...args) => {
  3202. * console.log(`sent event ${event}`);
  3203. * });
  3204. *
  3205. * @param listener
  3206. */
  3207. }, {
  3208. key: "onAnyOutgoing",
  3209. value: function onAnyOutgoing(listener) {
  3210. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  3211. this._anyOutgoingListeners.push(listener);
  3212. return this;
  3213. }
  3214. /**
  3215. * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
  3216. * callback. The listener is added to the beginning of the listeners array.
  3217. *
  3218. * Note: acknowledgements sent to the server are not included.
  3219. *
  3220. * @example
  3221. * socket.prependAnyOutgoing((event, ...args) => {
  3222. * console.log(`sent event ${event}`);
  3223. * });
  3224. *
  3225. * @param listener
  3226. */
  3227. }, {
  3228. key: "prependAnyOutgoing",
  3229. value: function prependAnyOutgoing(listener) {
  3230. this._anyOutgoingListeners = this._anyOutgoingListeners || [];
  3231. this._anyOutgoingListeners.unshift(listener);
  3232. return this;
  3233. }
  3234. /**
  3235. * Removes the listener that will be fired when any event is emitted.
  3236. *
  3237. * @example
  3238. * const catchAllListener = (event, ...args) => {
  3239. * console.log(`sent event ${event}`);
  3240. * }
  3241. *
  3242. * socket.onAnyOutgoing(catchAllListener);
  3243. *
  3244. * // remove a specific listener
  3245. * socket.offAnyOutgoing(catchAllListener);
  3246. *
  3247. * // or remove all listeners
  3248. * socket.offAnyOutgoing();
  3249. *
  3250. * @param [listener] - the catch-all listener (optional)
  3251. */
  3252. }, {
  3253. key: "offAnyOutgoing",
  3254. value: function offAnyOutgoing(listener) {
  3255. if (!this._anyOutgoingListeners) {
  3256. return this;
  3257. }
  3258. if (listener) {
  3259. var listeners = this._anyOutgoingListeners;
  3260. for (var i = 0; i < listeners.length; i++) {
  3261. if (listener === listeners[i]) {
  3262. listeners.splice(i, 1);
  3263. return this;
  3264. }
  3265. }
  3266. } else {
  3267. this._anyOutgoingListeners = [];
  3268. }
  3269. return this;
  3270. }
  3271. /**
  3272. * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
  3273. * e.g. to remove listeners.
  3274. */
  3275. }, {
  3276. key: "listenersAnyOutgoing",
  3277. value: function listenersAnyOutgoing() {
  3278. return this._anyOutgoingListeners || [];
  3279. }
  3280. /**
  3281. * Notify the listeners for each packet sent
  3282. *
  3283. * @param packet
  3284. *
  3285. * @private
  3286. */
  3287. }, {
  3288. key: "notifyOutgoingListeners",
  3289. value: function notifyOutgoingListeners(packet) {
  3290. if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
  3291. var listeners = this._anyOutgoingListeners.slice();
  3292. var _iterator2 = _createForOfIteratorHelper(listeners),
  3293. _step2;
  3294. try {
  3295. for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
  3296. var listener = _step2.value;
  3297. listener.apply(this, packet.data);
  3298. }
  3299. } catch (err) {
  3300. _iterator2.e(err);
  3301. } finally {
  3302. _iterator2.f();
  3303. }
  3304. }
  3305. }
  3306. }]);
  3307. return Socket;
  3308. }(Emitter);
  3309. /**
  3310. * Initialize backoff timer with `opts`.
  3311. *
  3312. * - `min` initial timeout in milliseconds [100]
  3313. * - `max` max timeout [10000]
  3314. * - `jitter` [0]
  3315. * - `factor` [2]
  3316. *
  3317. * @param {Object} opts
  3318. * @api public
  3319. */
  3320. function Backoff(opts) {
  3321. opts = opts || {};
  3322. this.ms = opts.min || 100;
  3323. this.max = opts.max || 10000;
  3324. this.factor = opts.factor || 2;
  3325. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  3326. this.attempts = 0;
  3327. }
  3328. /**
  3329. * Return the backoff duration.
  3330. *
  3331. * @return {Number}
  3332. * @api public
  3333. */
  3334. Backoff.prototype.duration = function () {
  3335. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  3336. if (this.jitter) {
  3337. var rand = Math.random();
  3338. var deviation = Math.floor(rand * this.jitter * ms);
  3339. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  3340. }
  3341. return Math.min(ms, this.max) | 0;
  3342. };
  3343. /**
  3344. * Reset the number of attempts.
  3345. *
  3346. * @api public
  3347. */
  3348. Backoff.prototype.reset = function () {
  3349. this.attempts = 0;
  3350. };
  3351. /**
  3352. * Set the minimum duration
  3353. *
  3354. * @api public
  3355. */
  3356. Backoff.prototype.setMin = function (min) {
  3357. this.ms = min;
  3358. };
  3359. /**
  3360. * Set the maximum duration
  3361. *
  3362. * @api public
  3363. */
  3364. Backoff.prototype.setMax = function (max) {
  3365. this.max = max;
  3366. };
  3367. /**
  3368. * Set the jitter
  3369. *
  3370. * @api public
  3371. */
  3372. Backoff.prototype.setJitter = function (jitter) {
  3373. this.jitter = jitter;
  3374. };
  3375. var Manager = /*#__PURE__*/function (_Emitter) {
  3376. _inherits(Manager, _Emitter);
  3377. var _super = _createSuper(Manager);
  3378. function Manager(uri, opts) {
  3379. var _this;
  3380. _classCallCheck(this, Manager);
  3381. var _a;
  3382. _this = _super.call(this);
  3383. _this.nsps = {};
  3384. _this.subs = [];
  3385. if (uri && "object" === _typeof(uri)) {
  3386. opts = uri;
  3387. uri = undefined;
  3388. }
  3389. opts = opts || {};
  3390. opts.path = opts.path || "/socket.io";
  3391. _this.opts = opts;
  3392. installTimerFunctions(_assertThisInitialized(_this), opts);
  3393. _this.reconnection(opts.reconnection !== false);
  3394. _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  3395. _this.reconnectionDelay(opts.reconnectionDelay || 1000);
  3396. _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  3397. _this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
  3398. _this.backoff = new Backoff({
  3399. min: _this.reconnectionDelay(),
  3400. max: _this.reconnectionDelayMax(),
  3401. jitter: _this.randomizationFactor()
  3402. });
  3403. _this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  3404. _this._readyState = "closed";
  3405. _this.uri = uri;
  3406. var _parser = opts.parser || parser;
  3407. _this.encoder = new _parser.Encoder();
  3408. _this.decoder = new _parser.Decoder();
  3409. _this._autoConnect = opts.autoConnect !== false;
  3410. if (_this._autoConnect) _this.open();
  3411. return _this;
  3412. }
  3413. _createClass(Manager, [{
  3414. key: "reconnection",
  3415. value: function reconnection(v) {
  3416. if (!arguments.length) return this._reconnection;
  3417. this._reconnection = !!v;
  3418. return this;
  3419. }
  3420. }, {
  3421. key: "reconnectionAttempts",
  3422. value: function reconnectionAttempts(v) {
  3423. if (v === undefined) return this._reconnectionAttempts;
  3424. this._reconnectionAttempts = v;
  3425. return this;
  3426. }
  3427. }, {
  3428. key: "reconnectionDelay",
  3429. value: function reconnectionDelay(v) {
  3430. var _a;
  3431. if (v === undefined) return this._reconnectionDelay;
  3432. this._reconnectionDelay = v;
  3433. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
  3434. return this;
  3435. }
  3436. }, {
  3437. key: "randomizationFactor",
  3438. value: function randomizationFactor(v) {
  3439. var _a;
  3440. if (v === undefined) return this._randomizationFactor;
  3441. this._randomizationFactor = v;
  3442. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
  3443. return this;
  3444. }
  3445. }, {
  3446. key: "reconnectionDelayMax",
  3447. value: function reconnectionDelayMax(v) {
  3448. var _a;
  3449. if (v === undefined) return this._reconnectionDelayMax;
  3450. this._reconnectionDelayMax = v;
  3451. (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
  3452. return this;
  3453. }
  3454. }, {
  3455. key: "timeout",
  3456. value: function timeout(v) {
  3457. if (!arguments.length) return this._timeout;
  3458. this._timeout = v;
  3459. return this;
  3460. }
  3461. /**
  3462. * Starts trying to reconnect if reconnection is enabled and we have not
  3463. * started reconnecting yet
  3464. *
  3465. * @private
  3466. */
  3467. }, {
  3468. key: "maybeReconnectOnOpen",
  3469. value: function maybeReconnectOnOpen() {
  3470. // Only try to reconnect if it's the first time we're connecting
  3471. if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
  3472. // keeps reconnection from firing twice for the same reconnection loop
  3473. this.reconnect();
  3474. }
  3475. }
  3476. /**
  3477. * Sets the current transport `socket`.
  3478. *
  3479. * @param {Function} fn - optional, callback
  3480. * @return self
  3481. * @public
  3482. */
  3483. }, {
  3484. key: "open",
  3485. value: function open(fn) {
  3486. var _this2 = this;
  3487. if (~this._readyState.indexOf("open")) return this;
  3488. this.engine = new Socket$1(this.uri, this.opts);
  3489. var socket = this.engine;
  3490. var self = this;
  3491. this._readyState = "opening";
  3492. this.skipReconnect = false; // emit `open`
  3493. var openSubDestroy = on(socket, "open", function () {
  3494. self.onopen();
  3495. fn && fn();
  3496. }); // emit `error`
  3497. var errorSub = on(socket, "error", function (err) {
  3498. self.cleanup();
  3499. self._readyState = "closed";
  3500. _this2.emitReserved("error", err);
  3501. if (fn) {
  3502. fn(err);
  3503. } else {
  3504. // Only do this if there is no fn to handle the error
  3505. self.maybeReconnectOnOpen();
  3506. }
  3507. });
  3508. if (false !== this._timeout) {
  3509. var timeout = this._timeout;
  3510. if (timeout === 0) {
  3511. openSubDestroy(); // prevents a race condition with the 'open' event
  3512. } // set timer
  3513. var timer = this.setTimeoutFn(function () {
  3514. openSubDestroy();
  3515. socket.close(); // @ts-ignore
  3516. socket.emit("error", new Error("timeout"));
  3517. }, timeout);
  3518. if (this.opts.autoUnref) {
  3519. timer.unref();
  3520. }
  3521. this.subs.push(function subDestroy() {
  3522. clearTimeout(timer);
  3523. });
  3524. }
  3525. this.subs.push(openSubDestroy);
  3526. this.subs.push(errorSub);
  3527. return this;
  3528. }
  3529. /**
  3530. * Alias for open()
  3531. *
  3532. * @return self
  3533. * @public
  3534. */
  3535. }, {
  3536. key: "connect",
  3537. value: function connect(fn) {
  3538. return this.open(fn);
  3539. }
  3540. /**
  3541. * Called upon transport open.
  3542. *
  3543. * @private
  3544. */
  3545. }, {
  3546. key: "onopen",
  3547. value: function onopen() {
  3548. // clear old subs
  3549. this.cleanup(); // mark as open
  3550. this._readyState = "open";
  3551. this.emitReserved("open"); // add new subs
  3552. var socket = this.engine;
  3553. this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)), on(this.decoder, "decoded", this.ondecoded.bind(this)));
  3554. }
  3555. /**
  3556. * Called upon a ping.
  3557. *
  3558. * @private
  3559. */
  3560. }, {
  3561. key: "onping",
  3562. value: function onping() {
  3563. this.emitReserved("ping");
  3564. }
  3565. /**
  3566. * Called with data.
  3567. *
  3568. * @private
  3569. */
  3570. }, {
  3571. key: "ondata",
  3572. value: function ondata(data) {
  3573. try {
  3574. this.decoder.add(data);
  3575. } catch (e) {
  3576. this.onclose("parse error", e);
  3577. }
  3578. }
  3579. /**
  3580. * Called when parser fully decodes a packet.
  3581. *
  3582. * @private
  3583. */
  3584. }, {
  3585. key: "ondecoded",
  3586. value: function ondecoded(packet) {
  3587. var _this3 = this;
  3588. // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error"
  3589. nextTick(function () {
  3590. _this3.emitReserved("packet", packet);
  3591. }, this.setTimeoutFn);
  3592. }
  3593. /**
  3594. * Called upon socket error.
  3595. *
  3596. * @private
  3597. */
  3598. }, {
  3599. key: "onerror",
  3600. value: function onerror(err) {
  3601. this.emitReserved("error", err);
  3602. }
  3603. /**
  3604. * Creates a new socket for the given `nsp`.
  3605. *
  3606. * @return {Socket}
  3607. * @public
  3608. */
  3609. }, {
  3610. key: "socket",
  3611. value: function socket(nsp, opts) {
  3612. var socket = this.nsps[nsp];
  3613. if (!socket) {
  3614. socket = new Socket(this, nsp, opts);
  3615. this.nsps[nsp] = socket;
  3616. }
  3617. return socket;
  3618. }
  3619. /**
  3620. * Called upon a socket close.
  3621. *
  3622. * @param socket
  3623. * @private
  3624. */
  3625. }, {
  3626. key: "_destroy",
  3627. value: function _destroy(socket) {
  3628. var nsps = Object.keys(this.nsps);
  3629. for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) {
  3630. var nsp = _nsps[_i];
  3631. var _socket = this.nsps[nsp];
  3632. if (_socket.active) {
  3633. return;
  3634. }
  3635. }
  3636. this._close();
  3637. }
  3638. /**
  3639. * Writes a packet.
  3640. *
  3641. * @param packet
  3642. * @private
  3643. */
  3644. }, {
  3645. key: "_packet",
  3646. value: function _packet(packet) {
  3647. var encodedPackets = this.encoder.encode(packet);
  3648. for (var i = 0; i < encodedPackets.length; i++) {
  3649. this.engine.write(encodedPackets[i], packet.options);
  3650. }
  3651. }
  3652. /**
  3653. * Clean up transport subscriptions and packet buffer.
  3654. *
  3655. * @private
  3656. */
  3657. }, {
  3658. key: "cleanup",
  3659. value: function cleanup() {
  3660. this.subs.forEach(function (subDestroy) {
  3661. return subDestroy();
  3662. });
  3663. this.subs.length = 0;
  3664. this.decoder.destroy();
  3665. }
  3666. /**
  3667. * Close the current socket.
  3668. *
  3669. * @private
  3670. */
  3671. }, {
  3672. key: "_close",
  3673. value: function _close() {
  3674. this.skipReconnect = true;
  3675. this._reconnecting = false;
  3676. this.onclose("forced close");
  3677. if (this.engine) this.engine.close();
  3678. }
  3679. /**
  3680. * Alias for close()
  3681. *
  3682. * @private
  3683. */
  3684. }, {
  3685. key: "disconnect",
  3686. value: function disconnect() {
  3687. return this._close();
  3688. }
  3689. /**
  3690. * Called upon engine close.
  3691. *
  3692. * @private
  3693. */
  3694. }, {
  3695. key: "onclose",
  3696. value: function onclose(reason, description) {
  3697. this.cleanup();
  3698. this.backoff.reset();
  3699. this._readyState = "closed";
  3700. this.emitReserved("close", reason, description);
  3701. if (this._reconnection && !this.skipReconnect) {
  3702. this.reconnect();
  3703. }
  3704. }
  3705. /**
  3706. * Attempt a reconnection.
  3707. *
  3708. * @private
  3709. */
  3710. }, {
  3711. key: "reconnect",
  3712. value: function reconnect() {
  3713. var _this4 = this;
  3714. if (this._reconnecting || this.skipReconnect) return this;
  3715. var self = this;
  3716. if (this.backoff.attempts >= this._reconnectionAttempts) {
  3717. this.backoff.reset();
  3718. this.emitReserved("reconnect_failed");
  3719. this._reconnecting = false;
  3720. } else {
  3721. var delay = this.backoff.duration();
  3722. this._reconnecting = true;
  3723. var timer = this.setTimeoutFn(function () {
  3724. if (self.skipReconnect) return;
  3725. _this4.emitReserved("reconnect_attempt", self.backoff.attempts); // check again for the case socket closed in above events
  3726. if (self.skipReconnect) return;
  3727. self.open(function (err) {
  3728. if (err) {
  3729. self._reconnecting = false;
  3730. self.reconnect();
  3731. _this4.emitReserved("reconnect_error", err);
  3732. } else {
  3733. self.onreconnect();
  3734. }
  3735. });
  3736. }, delay);
  3737. if (this.opts.autoUnref) {
  3738. timer.unref();
  3739. }
  3740. this.subs.push(function subDestroy() {
  3741. clearTimeout(timer);
  3742. });
  3743. }
  3744. }
  3745. /**
  3746. * Called upon successful reconnect.
  3747. *
  3748. * @private
  3749. */
  3750. }, {
  3751. key: "onreconnect",
  3752. value: function onreconnect() {
  3753. var attempt = this.backoff.attempts;
  3754. this._reconnecting = false;
  3755. this.backoff.reset();
  3756. this.emitReserved("reconnect", attempt);
  3757. }
  3758. }]);
  3759. return Manager;
  3760. }(Emitter);
  3761. /**
  3762. * Managers cache.
  3763. */
  3764. var cache = {};
  3765. function lookup(uri, opts) {
  3766. if (_typeof(uri) === "object") {
  3767. opts = uri;
  3768. uri = undefined;
  3769. }
  3770. opts = opts || {};
  3771. var parsed = url(uri, opts.path || "/socket.io");
  3772. var source = parsed.source;
  3773. var id = parsed.id;
  3774. var path = parsed.path;
  3775. var sameNamespace = cache[id] && path in cache[id]["nsps"];
  3776. var newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
  3777. var io;
  3778. if (newConnection) {
  3779. io = new Manager(source, opts);
  3780. } else {
  3781. if (!cache[id]) {
  3782. cache[id] = new Manager(source, opts);
  3783. }
  3784. io = cache[id];
  3785. }
  3786. if (parsed.query && !opts.query) {
  3787. opts.query = parsed.queryKey;
  3788. }
  3789. return io.socket(parsed.path, opts);
  3790. } // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a
  3791. // namespace (e.g. `io.connect(...)`), for backward compatibility
  3792. _extends(lookup, {
  3793. Manager: Manager,
  3794. Socket: Socket,
  3795. io: lookup,
  3796. connect: lookup
  3797. });
  3798. return lookup;
  3799. }));
  3800. //# sourceMappingURL=socket.io.js.map